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..26f45cfa26 --- /dev/null +++ b/assertj/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.baeldung + assertj + 1.0.0-SNAPSHOT + + + + com.google.guava + guava + 19.0 + + + junit + junit + 4.12 + test + + + org.assertj + assertj-core + 3.4.1 + test + + + org.assertj + assertj-guava + 3.0.0 + + + + + + + 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/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java new file mode 100644 index 0000000000..558ce87d70 --- /dev/null +++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java @@ -0,0 +1,96 @@ +package com.baeldung.assertj.introduction; + +import com.google.common.base.Optional; +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multimaps; +import com.google.common.collect.Range; +import com.google.common.collect.Sets; +import com.google.common.collect.Table; +import com.google.common.collect.TreeRangeMap; +import com.google.common.io.Files; +import org.assertj.guava.data.MapEntry; +import org.junit.Test; + +import java.io.File; +import java.util.HashMap; + +import static org.assertj.guava.api.Assertions.assertThat; +import static org.assertj.guava.api.Assertions.entry; + +public class AssertJGuavaTest { + + @Test + public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception { + final File temp = File.createTempFile("bael", "dung"); + final File temp2 = File.createTempFile("bael", "dung2"); + + assertThat(Files.asByteSource(temp)) + .hasSize(0) + .hasSameContentAs(Files.asByteSource(temp2)); + } + + @Test + public void givenMultimap_whenVerifying_thenCorrect() throws Exception { + final Multimap mmap = Multimaps.newMultimap(new HashMap<>(), Sets::newHashSet); + mmap.put(1, "one"); + mmap.put(1, "1"); + + assertThat(mmap) + .hasSize(2) + .containsKeys(1) + .contains(entry(1, "one")) + .contains(entry(1, "1")); + } + + @Test + public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception { + final Optional something = Optional.of("something"); + + assertThat(something) + .isPresent() + .extractingValue() + .isEqualTo("something"); + } + + @Test + public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception { + final Range range = Range.openClosed("a", "g"); + + assertThat(range) + .hasOpenedLowerBound() + .isNotEmpty() + .hasClosedUpperBound() + .contains("b"); + } + + @Test + public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception { + final TreeRangeMap map = TreeRangeMap.create(); + + map.put(Range.closed(0, 60), "F"); + map.put(Range.closed(61, 70), "D"); + + assertThat(map) + .isNotEmpty() + .containsKeys(0) + .contains(MapEntry.entry(34, "F")); + } + + @Test + public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception { + final Table table = HashBasedTable.create(2, 2); + + table.put(1, "A", "PRESENT"); + table.put(1, "B", "ABSENT"); + + assertThat(table) + .hasRowCount(1) + .containsValues("ABSENT") + .containsCell(1, "B", "ABSENT"); + } + + + + +} diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index f99d85f564..8c9bb36f7d 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -63,6 +63,12 @@ test + + org.assertj + assertj-core + 3.4.1 + + org.mockito mockito-core 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/.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/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/dependency-injection/build.gradle b/dependency-injection/build.gradle deleted file mode 100644 index 968636154d..0000000000 --- a/dependency-injection/build.gradle +++ /dev/null @@ -1,43 +0,0 @@ -apply plugin: 'java' -apply plugin: 'eclipse' - -allprojects { - apply plugin: 'java' - sourceCompatibility = 1.6 - targetCompatibility = 1.6 -} - -repositories { - mavenCentral() -} - -sourceSets { - main { - resources.srcDirs = ["src/main/java","src/main/resources"] - } - test { - resources.srcDirs = ["src/main/java", "src/main/resources", "src/test/resources"] - } -} - -configurations { - compile -} - -test { - testLogging { - events 'started', 'passed' - } -} - -dependencies { - testCompile('junit:junit:4.11') - testCompile('org.mockito:mockito-all:1.10.19') - testCompile group: 'org.springframework', name: 'spring-test', version: '4.2.6.RELEASE' - testCompile group: 'org.springframework', name: 'spring-core', version: '4.2.6.RELEASE' - testCompile group: 'org.springframework', name: 'spring-beans', version: '4.2.6.RELEASE' - testCompile group: 'org.springframework', name: 'spring-context', version: '4.2.6.RELEASE' - testCompile group: 'javax.inject', name: 'javax.inject', version: '1' - - testRuntime('junit:junit:4.11') -} diff --git a/dependency-injection/docs/autowired-name-demo-classdiagram.png b/dependency-injection/docs/autowired-name-demo-classdiagram.png deleted file mode 100644 index f367fdbf41..0000000000 Binary files a/dependency-injection/docs/autowired-name-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/autowired-type-demo-classdiagram.png b/dependency-injection/docs/autowired-type-demo-classdiagram.png deleted file mode 100644 index 5f3f341556..0000000000 Binary files a/dependency-injection/docs/autowired-type-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/autowired-type-demo-classdiagram.xml b/dependency-injection/docs/autowired-type-demo-classdiagram.xml deleted file mode 100644 index 71dc839457..0000000000 --- a/dependency-injection/docs/autowired-type-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -7Vjvb+I4EP1rkO4+7KkhhW0/8qt3J3V1Velq7z5VbmKIb50M55hS9q/fGXtMEgLXrprthwqEEH6ZOJ5573nAvXiSP/1uxCr7BKnUvf5Z+tSLp71+/6If4ycBWw8MBpceWBqVeiiqgLn6Jhk8Y3StUlk2Ai2AtmrVBBMoCpnYBiaMgU0zbAG6+dSVWIYnVsA8EbqNflGpzUJawwr/Q6plFp4cDTm/B5F8XRpYF/y8Xj9euJe/nIswFydaZiKFTQ2KZ1hWA4Az07f8aSI1lTaUzd93deTqbt1GFry2Z24I67DbkLtMsRQ8BGMzWEIh9KxCxy4/STOc4SizucavEX7Fh5rt34y7wT80+G3ghumImKFZV7K4y1Th0SuFK/K3/Cut3bIaxNoCQtUKrgFW/By/Zlro0bQZKmFtEo7CsROSMEvJUR93JUclS8glLhlDjNTCqsfm7II1tdzF8a2YlqC7QsAKVGHL2sw3BGAAuyO6HPgZ2Rz9yC0jcIRf/IxhVFtaBTkeD3PKeT4KveYMrpTU6QgLulFGplOZQ4v1cqNyLQqit0boAgobtEBjodUSaZsmWGdpEHiUxir0zYgvWOJonGRKp9diC2uqc2nRFGE0zsCobzitCM/Ay8Yy6WiwesSc7mRtGFlizE2gmO700LUoCaCYBLQWq1I97BacI9mqGIO1kHNQyJR0NwENmAYWINg0iIsSk4GwI/JqC4dvCO5mgmNmZFNtJfGAQ7LaNnJ5cVxpNXX8L/m88dbI/0AbIAlgKtF3qSwSXNYIwZF5UNYIs61d2JcF1sCRVkmitAa+ylC4ApxkFrVaMhSkouWCZjgslHIlElUsr13M9LxCbrkqBG0yZeUccVrTBvsNbQs430K73SRTKa7dbUtWWOG5J6LZh5jHYIxvLPiEtqIB5jXBMVIYxvimcGMnUGB+guwaTyUKayNJXC/ThGO5rYngcu4dz4kgxL1GBOctEbSI1Wrf657Y0O6c+3+Y1Ry5cC2CabxzW/YHN32D6rhNNUH7FGrxIPUNlMoqoPmNj92j9g3YG7zQwh04mJtDgzxMYd/D958+z+/ux7P70ee7v778eTub3k/AGPw1pNnfj4BTngz9syQxZPrfwtA8RU0TL9m8Tz29w54+PG829egje73GfxQ00ejqjL2Gf/8Dcb+ru93Re31uDZrs5PZXuN157Efa90G2u3A7C+vUvjtj70D7PsheB+2bDwJa7duC9+gvv54c+yacH+jPP82xEa+uxvqt/G+N/7bdOcAzDLued7SOVCo6DKG+uNeyX0I1e5h47aALRhfNLrj7q1ur8sEid9AEo/bBRjjleSfVHfJJ0O43xiWPa9UNley8uu2Tg3dW3eiCBRSqG/Nfre6ri8PqDNcf4VXn5PHsOw== \ No newline at end of file diff --git a/dependency-injection/docs/inject-demo-classdiagram.png b/dependency-injection/docs/inject-demo-classdiagram.png deleted file mode 100644 index 9996fdc733..0000000000 Binary files a/dependency-injection/docs/inject-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/inject-field-demo-classdiagram.png b/dependency-injection/docs/inject-field-demo-classdiagram.png deleted file mode 100644 index e63b6e5f42..0000000000 Binary files a/dependency-injection/docs/inject-field-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/inject-field-demo-classdiagram.xml b/dependency-injection/docs/inject-field-demo-classdiagram.xml deleted file mode 100644 index 147c545a2d..0000000000 --- a/dependency-injection/docs/inject-field-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -7Vhdb9s4EPw1fuwhtqK0eYw/ctdDeijqHO7uyWAkWmJLcX0UFcf99d2llpZkKUiKOHkobBiGOVx+zcxybY2iWfHwuxWb/BOkUo8mZ+nDKJqPJpMPkwg/CdjVQBxf1kBmVVpD4wZYqu+SwTNGK5XKshPoALRTmy6YgDEycR1MWAvbbtgadHfVjcjCig2wTITuo/+o1OXhWBcN/odUWR5WHl/w+e5E8i2zUBlebzSJ1v5VdxcizMUHLXORwrYFRQuk1QLgzPSteJhJTdQG2upx14/07vdtpeG9PTEg7MPtwtllilRwE6zLIQMj9KJBp/58kmY4w1buCo1fx/gVF7W7fxn3jf+o8Vvsm+kVKUOzbqS5zZWp0WuFO6qHfJXO7dgNonKAULODG4ANr1PvmTb66LEZKqGyCUdh2xtJ2Exy1Ps95ehkCYXELWOIlVo4dd+dXbCnsn1cwyt+YWqHaeal74WueNJrJXX60XxF985lAT0Vyq0qtDBEd4vgNRgXtKG20CpDGucJnltaBO6ldQp9fMUdjjibJrnS6Y3YQUXnLh2aNLSmOVj1HacVYQ3sto5FQMO3I5Y0krWyssSYz4FyGllDN6IkgGIS0FpsSnW333CB5CszBeeg4KBwUvLBDDTgMZCAkDZBbDqY5OvlMbn7QoYB7HK+jUJz26R2FDOWt9P6gsGXSM83YUv6d9TrlR/PJaZCKk2CO7tC+MreKWeF3bU6Dp2BNHjdGleUzsI3Gbgz4F2zbtHJUHCLlmuaYdgr5UYkymQ3PmZ+3iBfmBiCtrlycok47WmLJYAyFedba5/guUpx7/6mcMKJWn7SegPKOE9mPMU30juj2yHGc82wjSqGNr4p3LoZGDyfwHE4TKK3tpL89Txb+Lzr24J9EK7zp3wQ4l5ig/OeDXrCanWY7rWwoQL5C+CnVS1QC39rs4y3/hZ956fvSB31pSboUEIt7qT+DKVyCmh+W8ceSPsG6sXM4FPqfXi5ePGAeHiEszVd4k2qrj79vbxdTRerj3/9uZjdLuarZZUksizXldac4feAk55S+rVMEW7st0hpnqLliudc36fCfsTCHr/vVvaIk70l/76It+W/PEJh978de4XdX491qi+dxRw7JfsLkt2n2M/U70G1j5HsbKxT/T6aegP1e1C9I9Rv/nPeq98OOEdP+foWig8U51fL1zHvrqX5F/l/pbCUPUNhX/Ae5ZGooscTVBQP6vVzpOYMJl2PUALPw88bJvmS/3C2SB7k+AgVcNx/rBEeu/wi5EYHvy8u+hUnEHl0cvsPDn4xcuMD58avRi42m0eqvq/12Dpa/AA= \ No newline at end of file diff --git a/dependency-injection/docs/inject-name-demo-classdiagram.png b/dependency-injection/docs/inject-name-demo-classdiagram.png deleted file mode 100644 index 96a6a3425e..0000000000 Binary files a/dependency-injection/docs/inject-name-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/inject-name-demo-classdiagram.xml b/dependency-injection/docs/inject-name-demo-classdiagram.xml deleted file mode 100644 index 5a8bb9f8c4..0000000000 --- a/dependency-injection/docs/inject-name-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -7VhZbxs3EP41AtqHFDqydvOoy20KJwgiF2meDHp3pGXC5ahcyrLy6zPkDrWnYQVe5yGQIAjit8Njvm8OiYPJPHv4y4ht+g4TUIPxMHkYTBaD8fjP8YQ+HXAogCh6UwAbI5MCGpXASn4DBoeM7mQCec3QIiort3UwRq0htjVMGIP7utkaVX3XrdiEHUtgFQvVRj/JxKbBrYsS/xvkJg07jy7YvzsRf90Y3GnebzCerP2reJyJsBY7mqciwX0FmiyJVoNIK7tv2cMclKM20FbMu3rk6fHcBjSf7YkJ4Rz2EHyHhKjgIRqb4ga1UMsSnXn/wK0wpFFqM0VfR/SVNjWH/xj3g89u8Efkh8nUKeNW3YK+SaUu0CtJJyqmfAFrDxwNYmeRoPIE14hb3qc4szvoo24zlOPOxGxFYx9IwmyArS6PlFMkA2ZARyYTA0pYeV9fXXBMbY52Ja/0hantppm3vhdqx4teSVDJ7PBeZPBWf6EYXkCGLS3yvcyU0I70Cs1r1DYo5MZCyQ2RuYjJezAE3IOxkqJ5yg+sY24Wp1Il1+KAO+d9bilUw2iWopHfaFkR9qDHxrIUFPZVi5WbyYoZyMnmQyDezSyga5E7wNnEqJTY5vLueOCMJJB6htZixkbBUxcNc1RIbhABIXmC5M4x4CLzmOhtOUNVKiZwSQqRvy/ze3LJOqWV3H7Dds+Rn6thRf5XNNSkfbIASoYEdEzHmhI4NXfSGmEOlQfNqCAKvGZlROTW4FcIvGn0EbOuUMlQiBQFa7dCd5zkWxFLvbn2NovXJfKRWXHQPpUWVoS7M+2pCbhcpfXWyqd4KhM6u68VVlhRSO903qLU1lMZzehN5M5dfYjIrzmNScEwprczN3aOmvwTNI+mAcXVHlxsnRYSXtF2SHAQhIL+VBAEu+cEwetWELSEVbKZ6oWwoQf55P9hVTPSwtdtlvHG19FXfvma1JO21A5qSqjEHagPmEsr0a1vCtuGtD9BvYgZfEo9TvzniBd1iEcuNHP49t2/q5vb2fL27ft/lvOb5eJ2jsZQdVec3itriN1zRr9YTFycWNb7yGheohIUn8FONdoUzCl1/Nzde+zuUWjUob+P2rX9+LO71uC5Oz8nEvzvyFaD94XynPc95b2X80c6eafafeQ995NzJ+9NvY5O3qleD52c/6i3OrnFIkd/+/2csT9F845O/WIZO+LTVVT/CP/vJHWzExT2Pe9RHh1V7rLC9cVGyz5Fas5hp2sPXXDU7IIRp0yF5UB8jeQe/uWO2rcc4RbmF2E3umywe9FRt16K3fYlwi/G7njYYHfY0dP7YZeG5R2rf1a5x54svwM= \ No newline at end of file diff --git a/dependency-injection/docs/inject-qualifier-demo-classdiagram.png b/dependency-injection/docs/inject-qualifier-demo-classdiagram.png deleted file mode 100644 index 1ffe6453cb..0000000000 Binary files a/dependency-injection/docs/inject-qualifier-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml b/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml deleted file mode 100644 index ec122afe71..0000000000 --- a/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -7Vptb+I4EP41le4+bEUIUPZjeenenrqn3tLT3X6qTGIS7zox5zil7K/fcTLTvHbhFOAkBEKAx87EM88zL7G4cqfRywfN1uEn5XN51e/5L1fu7KrfH/dd+LSCbS4Y9VAQaOHnIqcQLMR3jsIeSlPh86Sy0CgljVhXhZ6KY+6ZioxprTbVZSslq3dds4DuWAgWHpNN6d/CNyGZNSrkv3ERhHRnZ/Q+n1ky71ugVRrj/a767ip75dMRI11oaBIyX21KIncObtVKgWb7K3qZcmldS27Lr7t7Y/Z135rHuLcdF9A+zJZs5z64AodKm1AFKmZyXkgnmX3caujBKDSRhJ8O/ISb6u0/KM8GX+zgepgN/VuLjNW65vFjKOJceidgR/klX7kxW2QDS40CUbGDe6XWeJ+mlWh4olLtoR0wznjDdMBx1U0ushaWLkPPfOAq4rBlWKC5ZEY8V8nAkFPB67rCr/ADXdvuZtzLM5MpKr0TXPp/pkyKleD6Y/wVaDzjkWrAkWxEJFls/V7y9ErFhkCyY9ATgD9nHniEaxA8c20EEPoWJ4x13sQLhfTv2Val1iOJAbbSaBIqLb6DWkb3gGltEA1gfnnFwl6JoGmewJoHAsNemYvuWWIFdo2npGTrRCxfNxwBLCKeKGNUhIvIUkuIqZIKzAAHUPz8BHVrK8fU8waiNIt0x7REw00R4+4NysJKfKOwCwcwA5Y48M5mSL5iqQToISZ8Hnuws1sQ3+qlMJrpbWmiP5IWJ188w8/A/gQFIxZZYONlkn2xiPs1XdUVP1EMBpR0N4gILs5oUpAwMVp94wRVrDKSrkrooYjIKfnKaminZrJmnoiD+2zNbFBIPiMOVrQJheELkNs9baD02AwB+lYySyyh8MGiLEMZZljONkuttRKxybAbTuANaE5tVhqCXVMYA2loDG+7XJupisE+BtfBZRyovOGWzi0spODezUKkHZWRXbQbDLqzDlWUWNcAVop6dsmBpcqX5Zv/jGoEWGTVAmF8zLL3u0x9BWq3CbUV1SGUbMnlg0qEEcrq1/naGrQnQI+Q2oXeuDt4DhLlDKvzsFmdHYTi9OUZN1MJEjCjB6VZltLp06e/Fo9Pk/nTxz9+n08f57OnRep5PElWqZTbX37NU/ezArWX5Lln+HUt4WPs6XZFo4vltwtNMBpLNGmtppcG7ngN3IgenKiDQ1hL8DujFvjfH6CBQ6bVGrisLuWRvzAaQu4S+/vGPsVTl8apFW1a1wVtLN+Xxulg6A3Rg7vQO0DjhKcxjYJuVB6jVKsvEXtkzAnfU0Ssg23cobvl6xuoMqWO2bnuuWMSPHAtYKe2ZGNf/dpIL6WyNfaYXbRDh6OlNhq5f/oumjZT7o9iZUKuL23Siduk4bjaJrmDZhz2e20nXSTsRITmceelU+r2lLQ/A95ulVoBP0jibR5tXnqljvi1NEut+B3ilKntjPDSLf0fUdvSLh0vapvPs5/5v6mAorYHxFnpe9OR1le2ubHlsVa598Eaw9gCe4BiOKgXw2Zotbakh6iEzafIM/XxsObj8Qmd3Hzao1b5TLzr0vEVpYnmoSc58tDOJR3n69xhzbkt6eFozm0+MZ0bc2u516FgPYV3m48h50ZdSqlE3eHRvAvD4l9J2Vzpn1/u/Ac= \ No newline at end of file diff --git a/dependency-injection/docs/resource-demo-classdiagram.png b/dependency-injection/docs/resource-demo-classdiagram.png deleted file mode 100644 index 1f0a41a19e..0000000000 Binary files a/dependency-injection/docs/resource-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/resource-field-demo-classdiagram.png b/dependency-injection/docs/resource-field-demo-classdiagram.png deleted file mode 100644 index 0d6207d09a..0000000000 Binary files a/dependency-injection/docs/resource-field-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/resource-field-demo-classdiagram.xml b/dependency-injection/docs/resource-field-demo-classdiagram.xml deleted file mode 100644 index 44c742f2bc..0000000000 --- a/dependency-injection/docs/resource-field-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -7Vhtb+I4EP41SHcftgICtP1YoN1bqXtalZ7u7lPlJiZx1/HkHANlf/3OOGOSEPpyonfaOxUhFD8ejz3zzItDL5rljx+tKLLPkEjdG/aTx1407w2HZ8MIfwnYVsB4fF4BqVVJBQ1qYKG+SQb7jK5UIsuWoAPQThVtMAZjZOxamLAWNm2xJej2roVIw441sIiF7qK/q8RlwaxJjf8iVZqFnQcTtu9exF9TCyvD+/WG0dJ/qulcBF1saJmJBDYNKLpEt1oA1ExP+eNManJtcFu17uqJ2d25rTR8tucX4BQtWAu9YtN7w4nGpdMCH1J6uFJSJzeyhJWN5SfzgP5WYOYyhyCK6nfSbJbbBleWG5VrYXA0zVyuERzg4xKMW7AQjYVWqcHnGM8tLQJraZ1CQi54wkGBaJwpnVyLLazIutKht8NomoFV31CtCHvgtHUcW6PzlsSCViLcR9TKEmW+BJfRygq6FiUBJBOD1qIo1f3uwLmwqTJTcA5yFgqWXimtZ6ABzUAHBP6Da5rcMF1kq+TU8RBz9VFCLp3dokiY5bDhtBpxmm3qGI1GLJI14/OUBQXnRbrTXMcGPnB4HA4VVtEIlQ+U4XIpVtqhzQheIPAg1uJEwYlH9oMBzfRU1YFQOgtfZXCXAR8oy4YHGQoBouWSNBwOj7IQsTLptZeZj2rkhn1B0CZTTi4QpzNtsHwhBqhvqX0iZipJJKqcWnDCiYpxorcAZZz333iKX3TzrH8y7o3RrhmOkbgwxi+JWzcDg/YJXIfLJIbTRlJIHYiEkIcvR0KgngvOS9RHXLKOYX50oEjsEavVfoZXxIbq6XP+b7OaIxe0Q6Dxllief/DqW1RHXaoJ2qdQi3upv0CpqIIhZivZPWr/BfbOxq9j7+x48ninFnloQr/QaFko6xfGkKvQK3eff1vc3l19+nV+N69T+6efq+ReA6p9T+p/KizOX1nPx4wdExennbh4tnL/GG0cL2A/SBvvkHqgsz/Zxk/77T4+CNfBBvGDyaF6wCF1DPHcON6reTNtX6DTJ8uTaRteC15ib8SN9KhbGJ+uwZZM8N2Fh2hoBikYoS9rFD2HLySSNJDfGrSigXb7B+N+8CcNsOLRMLmgVynSWkhzmykqoIhSYvCSB+nclnNTrBxQ1d2d4Bo8wbRPdWY66PMZg3b5ftS6cWL+p/J5IqzU2L3Wbe1Hubn7YnQj/1opLCmv6H++8DzZZSgiyVlUnPbq5msaIacNdb03KEXjvVeKwaQbzIdiOVSso5zcfaXoRvd/2rtR6NTh3te9tQdHvrlzu7f2/5lzJ6fszRC6I1bx9t7FYf2fjJ9r/O8VXX4H \ No newline at end of file diff --git a/dependency-injection/docs/resource-method-byname-demo-classdiagram.png b/dependency-injection/docs/resource-method-byname-demo-classdiagram.png deleted file mode 100644 index c5cd0c0fcb..0000000000 Binary files a/dependency-injection/docs/resource-method-byname-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/resource-method-demo-classdiagram.png b/dependency-injection/docs/resource-method-demo-classdiagram.png deleted file mode 100644 index 6be7dbbeea..0000000000 Binary files a/dependency-injection/docs/resource-method-demo-classdiagram.png and /dev/null differ diff --git a/dependency-injection/docs/resource-method-demo-classdiagram.xml b/dependency-injection/docs/resource-method-demo-classdiagram.xml deleted file mode 100644 index 94b39279fc..0000000000 --- a/dependency-injection/docs/resource-method-demo-classdiagram.xml +++ /dev/null @@ -1 +0,0 @@ -3Vhbb+I6EP41SN0HECGQbh8boNuutkerltXZ84QMcRL3OHFqHAr99R0749y4qCpdqV0eQvx5PJ755mJDxx0nm2+SZPGtCCjvDPrBpuNOOoPB14ELTw1sC2A0uiiASLKggJwKuGfPFME+ojkL6KohqITgimVNcCnSlC5VAyNSiqemWCh4c9eMRHbHCrhfEr6L/ssCFVu3vAq/piyK7c6Oh/4tyPL/SIo8xf06Azc0n2I6IVYXOrqKSSCeapA7BVqlEKBZvyWbMeWaWktbse7qwGxpt6Qp2nZ8ATq0UlvrOg2ACRwKqWIRiZTwaYX6xj2qFfRhFKuEw6sDr7Cn3P5G3Az+04PeyAyDSx0YrTWj6SxmaYFeMTCoWPJAldpiMpBcCYAqC34IkeE+hc3a0INeI7QSuVyiFKakIjKiKDUqGYdEpiKhYDKISMqJYuumdoIpFZVyFa3wgsweCAtGe014jlrv6GPOJOR4m39FN2BdnVaQYs9kYQQ0TZlgqTLWjPzOaAII4SwCOidL8J9KANZUKgbpfIkTCQsCEztOFpT7ZZKOBRcgD/vaNLXsag0Uy7lZbGhJlcN13k0+7TKKivo9DAK2he6wGL6acNT8UzNQqe2CeE2r01IgwnAFEW/HqzTvVSFEw2sR7Aw8riOVNeLnPea6dv0E0kyn+CXM9rMNPA210AE03lU6mfXcsDanQ9/FWOo5DGepE94i/DY7LyxwS6FKgjtapPtN+gBhYiKd0ERYWfCvFC/Xa90NBKTAnSYWg1QfMrDpH3B8yKw3EcJpCFIlI23dXX2Y0JDkXEHDAM1a8oGsSY+JnkHe2QMLaIwkECw/Xaz0l5VZZSTd6yhnKe3GeDpoM52ezpXWVjVn5re/7mdzfzq/+ef7dDybTuZjISWEkEPOl14V+zXtPNGGsy/F5FpAlh/faR+tO8CJ5hwh+6j/BQYlPqk4PavnxlvdbHXmdlM1NVz23iKBfQFSITfnXGhONj8UqcJDzYEOZsZXJGEQXXdyTfmaaq3Nln+wB++ccQd7rWPbM3ZFF4dP1X3G7SNmQ2PWnSN4yoFnDtaP2i0PtI2d9vhhm+En7N+vNflTl5xna8xeRIa7Ned4e2ru4h1K7nyn5Owd+MS7JVzEMXv0ghb3+wMErXXJ0mhmbuxwyXsXdodavsbuBTaZGrm25dW5tdgp3OKPu7+XW8/emW3men+MXBhWP2+Li3j1F4I7fQE= \ No newline at end of file diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml index 46f57e512e..667ea87402 100644 --- a/dependency-injection/pom.xml +++ b/dependency-injection/pom.xml @@ -1,81 +1,83 @@ - + - 4.0.0 + 4.0.0 - com.baeldung - dependency-injection - 0.0.1-SNAPSHOT - war + 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 + 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 - - + + + 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.6 - 1.6 - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*Demo.java - - - - - + + + + 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/ - - + + + 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/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java similarity index 79% rename from dependency-injection/src/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java rename to dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java index 27ba03f6e8..0e19523b7e 100644 --- a/dependency-injection/src/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java +++ b/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java @@ -1,5 +1,8 @@ package com.baeldung.dependency; +import org.springframework.stereotype.Component; + +@Component public class AnotherArbitraryDependency extends ArbitraryDependency { private final String label = "Another Arbitrary Dependency"; diff --git a/dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java similarity index 66% rename from dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java rename to dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java index bab289777c..3c90492d2c 100644 --- a/dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java +++ b/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java @@ -1,5 +1,8 @@ package com.baeldung.dependency; +import org.springframework.stereotype.Component; + +@Component(value = "autowiredFieldDependency") public class ArbitraryDependency { private final String label = "Arbitrary Dependency"; diff --git a/dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java similarity index 79% rename from dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java rename to dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java index 1f59500ec5..a88abd0924 100644 --- a/dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java +++ b/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java @@ -1,5 +1,8 @@ package com.baeldung.dependency; +import org.springframework.stereotype.Component; + +@Component public class YetAnotherArbitraryDependency extends ArbitraryDependency { private final String label = "Yet Another Arbitrary Dependency"; diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java similarity index 63% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java index c11ed5286a..cbdac68543 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java @@ -1,27 +1,29 @@ package com.baeldung.autowired; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - +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 com.baeldung.dependency.ArbitraryDependency; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Autowired-Name.xml"}) -public class FieldAutowiredNameDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredName.class) +public class FieldAutowiredNameTest { @Autowired private ArbitraryDependency autowiredFieldDependency; @Test - public void autowiredFieldDependency_MUST_BE_AUTOWIRED_Correctly() { + public void givenAutowiredAnnotation_WhenOnField_ThenDependencyValid() { assertNotNull(autowiredFieldDependency); assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString()); - } + } } diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java similarity index 63% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java index c71365097f..b736871f85 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java @@ -1,26 +1,28 @@ package com.baeldung.autowired; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - +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 com.baeldung.dependency.ArbitraryDependency; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Autowired-Type.xml"}) -public class FieldAutowiredDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredType.class) +public class FieldAutowiredTest { @Autowired private ArbitraryDependency fieldDependency; @Test - public void fieldDependency_MUST_BE_AUTOWIRED_Correctly() { + public void givenAutowired_WhenSetOnField_ThenDependencyResolved() { assertNotNull(fieldDependency); assertEquals("Arbitrary Dependency", fieldDependency.toString()); } diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java similarity index 68% rename from dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java rename to dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java index 5afce6ab6a..cbc3d56f67 100644 --- a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java @@ -1,21 +1,23 @@ package com.baeldung.autowired; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - +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 com.baeldung.dependency.ArbitraryDependency; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Autowired-Qualifier.xml"}) -public class FieldQualifierAutowiredDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestAutowiredQualifier.class) +public class FieldQualifierAutowiredTest { @Autowired @Qualifier("autowiredFieldDependency") @@ -26,13 +28,13 @@ public class FieldQualifierAutowiredDemo { private ArbitraryDependency fieldDependency2; @Test - public void fieldDependency1_MUST_BE_AUTOWIRED_Correctly() { + public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid() { assertNotNull(fieldDependency1); assertEquals("Arbitrary Dependency", fieldDependency1.toString()); } @Test - public void fieldDependency2_MUST_BE_AUTOWIRED_Correctly() { + public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid() { assertNotNull(fieldDependency2); assertEquals("Another Arbitrary Dependency", fieldDependency2.toString()); } diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java similarity index 66% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java rename to dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java index a670ee8313..665c9f1ddc 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java @@ -1,29 +1,31 @@ package com.baeldung.inject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import javax.inject.Inject; -import javax.inject.Named; - +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 com.baeldung.dependency.ArbitraryDependency; +import javax.inject.Inject; +import javax.inject.Named; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Inject-Name.xml"}) -public class FieldByNameInjectDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestInjectName.class) +public class FieldByNameInjectTest { @Inject @Named("yetAnotherFieldInjectDependency") private ArbitraryDependency yetAnotherFieldInjectDependency; @Test - public void yetAnotherFieldInjectDependency_MUST_BE_INJECTED_Correctly() { + 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/FieldInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectDemo.java deleted file mode 100644 index df40e516ba..0000000000 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectDemo.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.inject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import javax.inject.Inject; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.baeldung.dependency.ArbitraryDependency; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Inject-Type.xml"}) -public class FieldInjectDemo { - - @Inject - private ArbitraryDependency inject1Dependency; - - @Test - public void fieldDependency_MUST_BE_INJECTED_Successfully() { - assertNotNull(inject1Dependency); - assertEquals("Arbitrary Dependency", inject1Dependency.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/FieldQualifierInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java similarity index 67% rename from dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectDemo.java rename to dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java index 3cc9b643c7..7e5f7e7453 100644 --- a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java @@ -1,22 +1,23 @@ package com.baeldung.inject; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import javax.inject.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 com.baeldung.dependency.ArbitraryDependency; +import javax.inject.Inject; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Inject-Qualifier.xml"}) -public class FieldQualifierInjectDemo { +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestInjectQualifier.class) +public class FieldQualifierInjectTest { @Inject @Qualifier("defaultFile") @@ -27,13 +28,13 @@ public class FieldQualifierInjectDemo { private ArbitraryDependency namedDependency; @Test - public void defaultDependency_MUST_BE_INJECTED_Successfully() { + public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid() { assertNotNull(defaultDependency); assertEquals("Arbitrary Dependency", defaultDependency.toString()); } @Test - public void namedDependency_MUST_BE_INJECTED_Correctly() { + public void givenInjectQualifier_WhenOnField_ThenNamedFileValid() { assertNotNull(defaultDependency); assertEquals("Another Arbitrary Dependency", namedDependency.toString()); } diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java deleted file mode 100644 index fbb378d672..0000000000 --- a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.Resource; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Resource-NameType.xml"}) -public class FieldResourceInjectionDemo { - - @Resource(name="namedFile") - private File defaultFile; - - @Test - public void plainResourceAnnotation_MUST_FIND_DefaultFile() { - assertNotNull(defaultFile); - } -} 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/MethodByQualifierResourceDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceDemo.java deleted file mode 100644 index fcca34dc2f..0000000000 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceDemo.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.resource; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.Resource; - -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Resource-Qualifier.xml"}) -public class MethodByQualifierResourceDemo { - - private File arbDependency; - private File anotherArbDependency; - - @Test - public void dependencies_MUST_BE_INJECTED_Correctly() { - 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/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/SetterResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java similarity index 52% rename from dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionDemo.java rename to dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java index 25dd5bb9ff..ad9a9a4fb6 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java @@ -1,19 +1,23 @@ package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.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(locations={ - "/applicationContextTest-@Resource-NameType.xml"}) -public class SetterResourceInjectionDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class MethodByTypeResourceTest { private File defaultFile; @@ -23,7 +27,8 @@ public class SetterResourceInjectionDemo { } @Test - public void setter_MUST_INJECT_Resource() { + public void givenResourceAnnotation_WhenSetter_ThenValidDependency() { assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); } } diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java similarity index 50% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java rename to dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java index d746fd4d85..1622d8896c 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java @@ -1,29 +1,34 @@ package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.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(locations={ - "/applicationContextTest-@Resource-NameType.xml"}) -public class MethodResourceInjectionDemo { +@ContextConfiguration( + loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class MethodResourceInjectionTest { private File defaultFile; - @Resource(name="namedFile") + @Resource(name = "namedFile") protected void setDefaultFile(File defaultFile) { this.defaultFile = defaultFile; } @Test - public void defaultFile_MUST_BE_INJECTED_Correctly() { + 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 index 8b218dfe98..da104ecaae 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java @@ -1,27 +1,29 @@ package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; - -import javax.annotation.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(locations={ - "/applicationContextTest-@Resource-NameType.xml"}) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) public class NamedResourceTest { - @Resource(name="namedFile") + @Resource(name = "namedFile") private File testFile; @Test - public void namedResource_MUST_FIND_SPECIFIED_File() { + public void givenResourceAnnotation_WhenOnField_THEN_DEPENDENCY_Found() { assertNotNull(testFile); - assertTrue(testFile.getName().equals("namedFile.txt")); + assertEquals("namedFile.txt", testFile.getName()); } } diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java deleted file mode 100644 index 0aaa2085d5..0000000000 --- a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.Resource; - -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations={ - "/applicationContextTest-@Resource-Qualifier.xml"}) -public class QualifierResourceInjectionDemo { - - @Resource - private File defaultFile; - - @Resource - @Qualifier("namedFile") - private File namedFile; - - @Test - public void defaultFile_MUST_BE_Valid() { - assertNotNull(defaultFile); - } - - @Test - public void namedFile_MUST_BE_Valid() { - assertNotNull(namedFile); - } -} 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/MethodByTypeResourceDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java similarity index 52% rename from dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceDemo.java rename to dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java index af6a805bd9..aa7cfda975 100644 --- a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceDemo.java +++ b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java @@ -1,20 +1,22 @@ package com.baeldung.resource; -import static org.junit.Assert.assertNotNull; - -import java.io.File; - -import javax.annotation.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(locations={ - "/applicationContextTest-@Resource-NameType.xml"}) -public class MethodByTypeResourceDemo { +@ContextConfiguration(loader = AnnotationConfigContextLoader.class, + classes = ApplicationContextTestResourceNameType.class) +public class SetterResourceInjectionTest { private File defaultFile; @@ -24,7 +26,8 @@ public class MethodByTypeResourceDemo { } @Test - public void defaultFile_MUST_BE_INJECTED_Correctly() { + public void givenResourceAnnotation_WhenOnSetter_THEN_MUST_INJECT_Dependency() { assertNotNull(defaultFile); + assertEquals("namedFile.txt", defaultFile.getName()); } } diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml deleted file mode 100644 index d7fe3abcb3..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml deleted file mode 100644 index d7fe3abcb3..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml deleted file mode 100644 index c65b85ccf4..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml deleted file mode 100644 index 610e8687a7..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml deleted file mode 100644 index 627ec37914..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml deleted file mode 100644 index 405164e603..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml b/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml deleted file mode 100644 index 82cbe97157..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml deleted file mode 100644 index 1680a6f66a..0000000000 --- a/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - diff --git a/guava/src/test/java/org/baeldung/hamcrest/Animal.java b/guava/src/test/java/org/baeldung/hamcrest/Animal.java new file mode 100644 index 0000000000..1a0266f5a3 --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/Animal.java @@ -0,0 +1,33 @@ +package org.baeldung.hamcrest; + +public class Animal { + String name; + boolean wild; + String sound; + + public Animal(String name, boolean wild, String sound) { + super(); + this.name = name; + this.wild = wild; + this.sound = sound; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public boolean isWild() { + return wild; + } + public void setWild(boolean wild) { + this.wild = wild; + } + public String getSound() { + return sound; + } + public void setSound(String sound) { + this.sound = sound; + } + +} diff --git a/guava/src/test/java/org/baeldung/hamcrest/Cat.java b/guava/src/test/java/org/baeldung/hamcrest/Cat.java new file mode 100644 index 0000000000..892e5b6e30 --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/Cat.java @@ -0,0 +1,13 @@ +package org.baeldung.hamcrest; + +public class Cat extends Animal { + + public Cat() { + super("cat", false, "meow"); + } + + public String makeSound() { + return getSound(); + } + +} diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestMatcherTest.java b/guava/src/test/java/org/baeldung/hamcrest/HamcrestMatcherTest.java new file mode 100644 index 0000000000..b3756d609f --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/HamcrestMatcherTest.java @@ -0,0 +1,331 @@ +package org.baeldung.hamcrest; + +import org.junit.Test; + +import java.util.*; + +import static org.baeldung.hamcrest.IsPositiveInteger.isAPositiveInteger; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.beans.HasProperty.hasProperty; +import static org.hamcrest.beans.HasPropertyWithValue.hasProperty; +import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs; +import static org.hamcrest.collection.IsArrayContaining.hasItemInArray; +import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder; +import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining; +import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.hamcrest.collection.IsIn.isIn; +import static org.hamcrest.collection.IsIn.isOneOf; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.hamcrest.collection.IsMapContaining.hasValue; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.AnyOf.anyOf; +import static org.hamcrest.core.Every.everyItem; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsSame.sameInstance; +import static org.hamcrest.core.StringContains.containsString; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.hamcrest.object.HasToString.hasToString; +import static org.hamcrest.object.IsCompatibleType.typeCompatibleWith; +import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString; +import static org.hamcrest.text.IsEmptyString.isEmptyString; +import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; +import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace; +import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder; + +public class HamcrestMatcherTest { + @Test + public void given2Strings_whenEqual_thenCorrect() { + String a = "foo"; + String b = "FOO"; + assertThat(a, equalToIgnoringCase(b)); + } + + @Test + public void givenBean_whenHasValue_thenCorrect() { + Person person = new Person("Baeldung", "New York"); + assertThat(person, hasProperty("name")); + } + + @Test + public void givenBean_whenHasCorrectValue_thenCorrect() { + Person person = new Person("Baeldung", "New York"); + assertThat(person, hasProperty("address", equalTo("New York"))); + } + + @Test + public void given2Beans_whenHavingSameValues_thenCorrect() { + Person person1 = new Person("Baeldung", "New York"); + Person person2 = new Person("Baeldung", "New York"); + assertThat(person1, samePropertyValuesAs(person2)); + } + + @Test + public void givenAList_whenChecksSize_thenCorrect() { + List hamcrestMatchers = Arrays.asList("collections", "beans", + "text", "number"); + assertThat(hamcrestMatchers, hasSize(4)); + } + + @Test + public void givenArray_whenChecksSize_thenCorrect() { + String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; + assertThat(hamcrestMatchers, arrayWithSize(4)); + } + + @Test + public void givenAListAndValues_whenChecksListForGivenValues_thenCorrect() { + List hamcrestMatchers = Arrays.asList("collections", "beans", + "text", "number"); + assertThat(hamcrestMatchers, + containsInAnyOrder("beans", "text", "collections", "number")); + } + + @Test + public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() { + List hamcrestMatchers = Arrays.asList("collections", "beans", + "text", "number"); + assertThat(hamcrestMatchers, + contains("collections", "beans", "text", "number")); + } + + @Test + public void givenArrayAndValue_whenValueFoundInArray_thenCorrect() { + String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; + assertThat(hamcrestMatchers, hasItemInArray("text")); + + } + + @Test + public void givenValueAndArray_whenValueIsOneOfArrayElements_thenCorrect() { + String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; + assertThat("text", isOneOf(hamcrestMatchers)); + + } + + @Test + public void givenArrayAndValues_whenValuesFoundInArray_thenCorrect() { + String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; + assertThat( + hamcrestMatchers, + arrayContainingInAnyOrder("beans", "collections", "number", + "text")); + + } + + @Test + public void givenArrayAndValues_whenValuesFoundInArrayInOrder_thenCorrect() { + String[] hamcrestMatchers = { "collections", "beans", "text", "number" }; + assertThat(hamcrestMatchers, + arrayContaining("collections", "beans", "text", "number")); + + } + + @Test + public void givenCollection_whenEmpty_thenCorrect() { + List emptyList = new ArrayList<>(); + assertThat(emptyList, empty()); + + } + + @Test + public void givenValueAndArray_whenValueFoundInArray_thenCorrect() { + String[] array = new String[] { "collections", "beans", "text", + "number" }; + assertThat("beans", isIn(array)); + + } + + @Test + public void givenMapAndKey_whenKeyFoundInMap_thenCorrect() { + Map map = new HashMap<>(); + map.put("blogname", "baeldung"); + assertThat(map, hasKey("blogname")); + } + + @Test + public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() { + Map map = new HashMap<>(); + map.put("blogname", "baeldung"); + assertThat(map, hasEntry("blogname", "baeldung")); + } + + @Test + public void givenMapAndValue_whenValueFoundInMap_thenCorrect() { + Map map = new HashMap<>(); + map.put("blogname", "baeldung"); + assertThat(map, hasValue("baeldung")); + } + + @Test + public void givenString_whenEmpty_thenCorrect() { + String str = ""; + assertThat(str, isEmptyString()); + } + + @Test + public void givenString_whenEmptyOrNull_thenCorrect() { + String str = null; + assertThat(str, isEmptyOrNullString()); + } + + @Test + public void given2Strings_whenEqualRegardlessWhiteSpace_thenCorrect() { + String str1 = "text"; + String str2 = " text "; + assertThat(str1, equalToIgnoringWhiteSpace(str2)); + } + + @Test + public void givenString_whenContainsGivenSubstring_thenCorrect() { + String str = "calligraphy"; + assertThat(str, stringContainsInOrder(Arrays.asList("call", "graph"))); + } + + @Test + public void givenBean_whenToStringReturnsRequiredString_thenCorrect() { + Person person = new Person("Barrack", "Washington"); + String str = person.toString(); + assertThat(person, hasToString(str)); + } + + @Test + public void given2Classes_whenOneInheritsFromOther_thenCorrect() { + assertThat(Cat.class, typeCompatibleWith(Animal.class)); + } + + + @Test + public void given2Strings_whenIsEqualRegardlessWhiteSpace_thenCorrect() { + String str1 = "text"; + String str2 = " text "; + assertThat(str1, is(equalToIgnoringWhiteSpace(str2))); + } + + @Test + public void given2Strings_whenIsNotEqualRegardlessWhiteSpace_thenCorrect() { + String str1 = "text"; + String str2 = " texts "; + assertThat(str1, not(equalToIgnoringWhiteSpace(str2))); + } + + @Test + public void given2Strings_whenNotEqual_thenCorrect() { + String str1 = "text"; + String str2 = "texts"; + assertThat(str1, not(str2)); + } + + @Test + public void given2Strings_whenIsEqual_thenCorrect() { + String str1 = "text"; + String str2 = "text"; + assertThat(str1, is(str2)); + } + + @Test + public void givenAStrings_whenContainsAnotherGivenString_thenCorrect() { + String str1 = "calligraphy"; + String str2 = "call"; + assertThat(str1, containsString(str2)); + } + + @Test + public void givenAString_whenEndsWithAnotherGivenString_thenCorrect() { + String str1 = "calligraphy"; + String str2 = "phy"; + assertThat(str1, endsWith(str2)); + } + + @Test + public void givenAString_whenStartsWithAnotherGivenString_thenCorrect() { + String str1 = "calligraphy"; + String str2 = "call"; + assertThat(str1, startsWith(str2)); + } + + @Test + public void given2Objects_whenSameInstance_thenCorrect() { + Cat cat = new Cat(); + assertThat(cat, sameInstance(cat)); + } + + @Test + public void givenAnObject_whenInstanceOfGivenClass_thenCorrect() { + Cat cat = new Cat(); + assertThat(cat, instanceOf(Cat.class)); + } + + @Test + public void givenList_whenEachElementGreaterThan0_thenCorrect() { + List list = Arrays.asList(1, 2, 3); + int baseCase = 0; + assertThat(list, everyItem(greaterThan(baseCase))); + } + + @Test + public void givenString_whenNotNull_thenCorrect() { + String str = "notnull"; + assertThat(str, notNullValue()); + } + + @Test + public void givenString_whenMeetsAnyOfGivenConditions_thenCorrect() { + String str = "calligraphy"; + String start = "call"; + String end = "foo"; + assertThat(str, anyOf(startsWith(start), containsString(end))); + } + + @Test + public void givenString_whenMeetsAllOfGivenConditions_thenCorrect() { + String str = "calligraphy"; + String start = "call"; + String end = "phy"; + assertThat(str, allOf(startsWith(start), endsWith(end))); + } + + @Test + public void givenInteger_whenAPositiveValue_thenCorrect() { + int num = 1; + assertThat(num, isAPositiveInteger()); + } + + @Test + public void givenAnInteger_whenGreaterThan0_thenCorrect() { + int num = 1; + assertThat(num, greaterThan(0)); + } + + @Test + public void givenAnInteger_whenGreaterThanOrEqTo5_thenCorrect() { + int num = 5; + assertThat(num, greaterThanOrEqualTo(5)); + } + + @Test + public void givenAnInteger_whenLessThan0_thenCorrect() { + int num = -1; + assertThat(num, lessThan(0)); + } + + @Test + public void givenAnInteger_whenLessThanOrEqTo5_thenCorrect() { + assertThat(-1, lessThanOrEqualTo(5)); + } + + @Test + public void givenADouble_whenCloseTo_thenCorrect() { + assertThat(1.2, closeTo(1, 0.5)); + } + +} diff --git a/guava/src/test/java/org/baeldung/hamcrest/IsPositiveInteger.java b/guava/src/test/java/org/baeldung/hamcrest/IsPositiveInteger.java new file mode 100644 index 0000000000..0d8d262538 --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/IsPositiveInteger.java @@ -0,0 +1,24 @@ +package org.baeldung.hamcrest; + +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; + +public class IsPositiveInteger extends TypeSafeMatcher { + + public void describeTo(Description description) { + description.appendText("a positive integer"); + } + + @Factory + public static Matcher isAPositiveInteger() { + return new IsPositiveInteger(); + } + + @Override + protected boolean matchesSafely(Integer integer) { + return integer > 0; + } + +} diff --git a/guava/src/test/java/org/baeldung/hamcrest/Person.java b/guava/src/test/java/org/baeldung/hamcrest/Person.java new file mode 100644 index 0000000000..0053c98043 --- /dev/null +++ b/guava/src/test/java/org/baeldung/hamcrest/Person.java @@ -0,0 +1,37 @@ +package org.baeldung.hamcrest; + +public class Person { + String name; + String address; + + public Person(String personName, String personAddress) { + name = personName; + address = personAddress; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + @Override + public String toString() { + String str="[address:"+address+",name:"+name+"]"; + return str; + } + + + + +} 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 index 514611d1f9..dc1a206f0d 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java @@ -108,7 +108,7 @@ public class SandboxTest { // 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"); @@ -127,6 +127,7 @@ public class SandboxTest { try { System.out.println("----------------------------------------"); + System.out.println(responseGood.getStatusLine()); assertEquals(200, responseGood.getStatusLine().getStatusCode()); } finally { responseGood.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/jooq-spring/pom.xml b/jooq-spring/pom.xml index 7a3ec0ac24..e77ff0cbfd 100644 --- a/jooq-spring/pom.xml +++ b/jooq-spring/pom.xml @@ -5,22 +5,13 @@ 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.3.RELEASE + 1.3.5.RELEASE pom import @@ -46,30 +37,25 @@ org.springframework spring-context - ${org.springframework.version} org.springframework spring-jdbc - ${org.springframework.version} org.springframework.boot spring-boot-starter-jooq - 1.3.3.RELEASE org.slf4j slf4j-api - ${org.slf4j.version} runtime ch.qos.logback logback-classic - ${ch.qos.logback.version} runtime @@ -77,15 +63,13 @@ junit junit - ${junit.version} test org.springframework spring-test - ${org.springframework.version} test - + @@ -166,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/jsf/pom.xml b/jsf/pom.xml index c4801996de..b5fbae4cf0 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -25,6 +25,12 @@ jsf-impl ${com.sun.faces.version} + + javax.el + el-api + ${javax.el.version} + + @@ -114,6 +120,7 @@ 2.1.7 + 2.2 1.7.13 diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java new file mode 100644 index 0000000000..a13f0890b5 --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java @@ -0,0 +1,110 @@ +package com.baeldung.springintegration.controllers; + +import java.util.Random; +import javax.annotation.PostConstruct; +import javax.faces.application.Application; +import javax.faces.application.FacesMessage; +import javax.faces.bean.ManagedBean; +import javax.faces.bean.ViewScoped; +import javax.faces.component.html.HtmlInputText; +import javax.faces.context.FacesContext; + +@ManagedBean(name = "ELBean") +@ViewScoped +public class ELSampleBean { + + private String firstName; + private String lastName; + private String pageDescription = "This page demos JSF EL Basics"; + private int pageCounter; + private Random randomIntGen = new Random(); + + @PostConstruct + public void init() { + pageCounter = randomIntGen.nextInt(); + } + + public void save() { + + } + + public void saveFirstName(String firstName) { + this.firstName = firstName; + } + + + public void saveByELEvaluation() { + firstName = (String) evaluateEL("#{firstName.value}", String.class); + FacesContext ctx = FacesContext.getCurrentInstance(); + FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName); + theMessage.setSeverity(FacesMessage.SEVERITY_INFO); + ctx.addMessage(null, theMessage); + + } + + private Object evaluateEL(String elExpression, Class clazz) { + Object toReturn = null; + FacesContext ctx = FacesContext.getCurrentInstance(); + Application app = ctx.getApplication(); + toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz); + + return toReturn; + + } + + /** + * @return the firstName + */ + public String getFirstName() { + return firstName; + } + + /** + * @param firstName the firstName to set + */ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + * @return the lastName + */ + public String getLastName() { + return lastName; + } + + /** + * @param lastName the lastName to set + */ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + * @return the pageDescription + */ + public String getPageDescription() { + return pageDescription; + } + + /** + * @param pageDescription the pageDescription to set + */ + public void setPageDescription(String pageDescription) { + this.pageDescription = pageDescription; + } + + /** + * @return the pageCounter + */ + public int getPageCounter() { + return pageCounter; + } + + /** + * @param pageCounter the pageCounter to set + */ + public void setPageCounter(int pageCounter) { + this.pageCounter = pageCounter; + } +} diff --git a/jsf/src/main/webapp/el_intro.xhtml b/jsf/src/main/webapp/el_intro.xhtml new file mode 100644 index 0000000000..3b58d6288d --- /dev/null +++ b/jsf/src/main/webapp/el_intro.xhtml @@ -0,0 +1,38 @@ + + + + + Baeldung | The EL Intro + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/json/pom.xml b/json/pom.xml new file mode 100644 index 0000000000..47f1f25aa2 --- /dev/null +++ b/json/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + org.baeldung + json + 0.0.1-SNAPSHOT + + + + + org.everit.json + org.everit.json.schema + 1.3.0 + + + + junit + junit + 4.12 + test + + + + + diff --git a/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java b/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java new file mode 100644 index 0000000000..273fd48bac --- /dev/null +++ b/json/src/test/java/org/baeldung/json/schema/JSONSchemaTest.java @@ -0,0 +1,31 @@ +package org.baeldung.json.schema; + +import org.everit.json.schema.Schema; +import org.everit.json.schema.loader.SchemaLoader; + +import org.json.JSONObject; +import org.json.JSONTokener; +import org.junit.Test; + +public class JSONSchemaTest { + + @Test + public void givenInvalidInput_whenValidating_thenInvalid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_invalid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } + + @Test + public void givenValidInput_whenValidating_thenValid() { + + JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/schema.json"))); + JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaTest.class.getResourceAsStream("/product_valid.json"))); + + Schema schema = SchemaLoader.load(jsonSchema); + schema.validate(jsonSubject); + } +} diff --git a/json/src/test/resources/product_invalid.json b/json/src/test/resources/product_invalid.json new file mode 100644 index 0000000000..7c55d8c7a5 --- /dev/null +++ b/json/src/test/resources/product_invalid.json @@ -0,0 +1,5 @@ +{ + "id": 1, + "name": "Lampshade", + "price": 0 +} diff --git a/json/src/test/resources/product_valid.json b/json/src/test/resources/product_valid.json new file mode 100644 index 0000000000..e0697dc4c2 --- /dev/null +++ b/json/src/test/resources/product_valid.json @@ -0,0 +1,5 @@ +{ + "id": 1, + "name": "Lampshade", + "price": 10 +} diff --git a/json/src/test/resources/schema.json b/json/src/test/resources/schema.json new file mode 100644 index 0000000000..7cf99d76e0 --- /dev/null +++ b/json/src/test/resources/schema.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Product", + "description": "A product from the catalog", + "type": "object", + "properties": { + "id": { + "description": "The unique identifier for a product", + "type": "integer" + }, + "name": { + "description": "Name of the product", + "type": "string" + }, + "price": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + } + }, + "required": ["id", "name", "price"] +} diff --git a/log4j/pom.xml b/log4j/pom.xml new file mode 100644 index 0000000000..76c05b36c1 --- /dev/null +++ b/log4j/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + com.baeldung + log4j + 1.0-SNAPSHOT + + + + + log4j + log4j + 1.2.17 + + + + + + org.apache.logging.log4j + log4j-api + 2.6 + + + org.apache.logging.log4j + log4j-core + 2.6 + + + + + com.lmax + disruptor + 3.3.4 + + + + + + + ch.qos.logback + logback-classic + 1.1.7 + + + + + + maven-compiler-plugin + 3.3 + + true + true + 1.8 + 1.8 + UTF-8 + true + true + + + + + + \ No newline at end of file diff --git a/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java b/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java new file mode 100644 index 0000000000..e53fdd4881 --- /dev/null +++ b/log4j/src/main/java/com/baeldung/log4j/Log4jExample.java @@ -0,0 +1,17 @@ +package com.baeldung.log4j; + + +import org.apache.log4j.Logger; + +public class Log4jExample { + + private final static Logger logger = Logger.getLogger(Log4jExample.class); + + public static void main(String[] args) { + logger.trace("Trace log message"); + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } + +} diff --git a/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java b/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java new file mode 100644 index 0000000000..60acc3a774 --- /dev/null +++ b/log4j/src/main/java/com/baeldung/log4j2/Log4j2Example.java @@ -0,0 +1,16 @@ +package com.baeldung.log4j2; + +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; + +public class Log4j2Example { + + private static final Logger logger = LogManager.getLogger(Log4j2Example.class); + + public static void main(String[] args) { + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } + +} diff --git a/log4j/src/main/java/com/baeldung/logback/LogbackExample.java b/log4j/src/main/java/com/baeldung/logback/LogbackExample.java new file mode 100644 index 0000000000..536aa78ec9 --- /dev/null +++ b/log4j/src/main/java/com/baeldung/logback/LogbackExample.java @@ -0,0 +1,16 @@ +package com.baeldung.logback; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LogbackExample { + + private static final Logger logger = LoggerFactory.getLogger(LogbackExample.class); + + public static void main(String[] args) { + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } + +} diff --git a/log4j/src/main/resources/log4j.xml b/log4j/src/main/resources/log4j.xml new file mode 100644 index 0000000000..58a924f970 --- /dev/null +++ b/log4j/src/main/resources/log4j.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/log4j/src/main/resources/log4j2.xml b/log4j/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..76a20bcd61 --- /dev/null +++ b/log4j/src/main/resources/log4j2.xml @@ -0,0 +1,26 @@ + + + + # Console appender + + # Pattern of log message for console appender + + + + # File appender + + # Pattern of log message for file appender + + + + + + # Override log level for specified package + + + + + + + + \ No newline at end of file diff --git a/log4j/src/main/resources/logback.xml b/log4j/src/main/resources/logback.xml new file mode 100644 index 0000000000..fc66d560aa --- /dev/null +++ b/log4j/src/main/resources/logback.xml @@ -0,0 +1,28 @@ + + # Console appender + + + # Pattern of log message for console appender + %d{yyyy-MM-dd HH:mm:ss} %p %m%n + + + + # File appender + + # Name of a log file + log4j/target/baeldung-logback.log + false + + # Pattern of log message for file appender + %d{yyyy-MM-dd HH:mm:ss} %p %m%n + + + + # Override log level for specified package + + + + + + + \ No newline at end of file diff --git a/mocks/jmockit/README.md b/mocks/jmockit/README.md new file mode 100644 index 0000000000..c310463c26 --- /dev/null +++ b/mocks/jmockit/README.md @@ -0,0 +1,7 @@ +========= + +## JMockit related tutorials + + +### Relevant Articles: +- [JMockit 101](http://www.baeldung.com/jmockit-101) diff --git a/mocks/jmockit/pom.xml b/mocks/jmockit/pom.xml new file mode 100644 index 0000000000..8b03313a51 --- /dev/null +++ b/mocks/jmockit/pom.xml @@ -0,0 +1,68 @@ + + 4.0.0 + + + com.baeldung + mocks + 1.0.0-SNAPSHOT + ../pom.xml + + + jmockit + jmockit + + + 4.12 + 1.24 + + + 3.3 + 2.18.1 + + + + + junit + junit + ${junit.version} + test + + + + org.jmockit + jmockit + ${jmockit.version} + test + + + + + jmockit + + + 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/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java new file mode 100644 index 0000000000..ef271b9aff --- /dev/null +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Collaborator.java @@ -0,0 +1,10 @@ +package org.baeldung.mocks.jmockit; + +public class Collaborator { + public boolean collaborate(String string){ + return false; + } + public void receive(boolean bool){ + //NOOP + } +} diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java new file mode 100644 index 0000000000..54249dcd1d --- /dev/null +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Model.java @@ -0,0 +1,7 @@ +package org.baeldung.mocks.jmockit; + +public class Model { + public String getInfo(){ + return "info"; + } +} diff --git a/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java new file mode 100644 index 0000000000..4f8e8adb24 --- /dev/null +++ b/mocks/jmockit/src/main/java/org/baeldung/mocks/jmockit/Performer.java @@ -0,0 +1,10 @@ +package org.baeldung.mocks.jmockit; + +public class Performer { + private Collaborator collaborator; + + public void perform(Model model){ + boolean value = collaborator.collaborate(model.getInfo()); + collaborator.receive(value); + } +} diff --git a/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java new file mode 100644 index 0000000000..c99ae844c3 --- /dev/null +++ b/mocks/jmockit/src/test/java/org/baeldung/mocks/jmockit/PerformerTest.java @@ -0,0 +1,30 @@ +package org.baeldung.mocks.jmockit; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.*; +import mockit.integration.junit4.JMockit; + +@RunWith(JMockit.class) +public class PerformerTest { + + @Injectable + private Collaborator collaborator; + + @Tested + private Performer performer; + + @Test + public void testThePerformMethod(@Mocked Model model) { + new Expectations() {{ + model.getInfo();result = "bar"; + collaborator.collaborate("bar"); result = true; + }}; + performer.perform(model); + new Verifications() {{ + collaborator.receive(true); + }}; + } + +} diff --git a/mocks/mock-comparisons/README.md b/mocks/mock-comparisons/README.md new file mode 100644 index 0000000000..7795487b77 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml new file mode 100644 index 0000000000..692bfffd53 --- /dev/null +++ b/mocks/mock-comparisons/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + + + com.baeldung + mocks + 1.0.0-SNAPSHOT + ../pom.xml + + + mock-comparisons + mock-comparisons + + + 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/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java b/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java new file mode 100644 index 0000000000..914b0034d2 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java b/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java new file mode 100644 index 0000000000..2cbff6c9d4 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java b/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java new file mode 100644 index 0000000000..d6a31a8047 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java b/mocks/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java new file mode 100644 index 0000000000..14136d0f31 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerTest.java new file mode 100644 index 0000000000..25d2b91ede --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerTest.java new file mode 100644 index 0000000000..621342fed2 --- /dev/null +++ b/mocks/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/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerTest.java new file mode 100644 index 0000000000..59b28a2cb4 --- /dev/null +++ b/mocks/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/mocks/pom.xml b/mocks/pom.xml new file mode 100644 index 0000000000..ec02c255ef --- /dev/null +++ b/mocks/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../pom.xml + + + mocks + mocks + pom + + + mock-comparisons + jmockit + + + diff --git a/pom.xml b/pom.xml index 85861685ba..fa4777860d 100644 --- a/pom.xml +++ b/pom.xml @@ -7,8 +7,14 @@ parent-modules pom + + + UTF-8 + + - apache-fop + assertj + core-java core-java-8 gson @@ -23,12 +29,14 @@ jooq-spring json-path mockito + mocks jee7schedule querydsl rest-testing resteasy + log4j spring-all spring-apache-camel @@ -49,6 +57,7 @@ spring-mvc-no-xml spring-mvc-xml spring-openid + spring-protobuf spring-quartz spring-rest diff --git a/querydsl/pom.xml b/querydsl/pom.xml index cf50144d3f..bed0cf90e5 100644 --- a/querydsl/pom.xml +++ b/querydsl/pom.xml @@ -14,30 +14,25 @@ UTF-8 - 1.6 - 4.10 - 3.1.0.RELEASE - 4.3.11.Final - 2.5.0 - 1.5.10 + 1.8 + 4.12 + 4.3.1.RELEASE + 5.2.1.Final + 4.1.3 + 1.7.21 - - com.mysema.querydsl - querydsl-core - ${querydsl.version} - - com.mysema.querydsl + com.querydsl querydsl-jpa ${querydsl.version} - com.mysema.querydsl + com.querydsl querydsl-apt ${querydsl.version} provided @@ -53,7 +48,7 @@ org.hibernate.javax.persistence - hibernate-jpa-2.0-api + hibernate-jpa-2.1-api 1.0.0.Final compile @@ -69,7 +64,7 @@ commons-pool commons-pool - 1.5.5 + 1.6 jar compile @@ -77,8 +72,8 @@ org.hsqldb - hsqldb-j5 - 2.2.4 + hsqldb + 2.3.4 @@ -118,9 +113,9 @@ - org.slf4j - slf4j-api - ${slf4j.version} + ch.qos.logback + logback-classic + 1.1.7 org.slf4j @@ -128,17 +123,6 @@ ${slf4j.version} runtime - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - runtime - - - log4j - log4j - 1.2.16 - @@ -157,7 +141,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.5.1 ${java.version} ${java.version} @@ -168,16 +152,16 @@ com.mysema.maven - maven-apt-plugin - 1.0.3 + apt-maven-plugin + 1.1.3 process - target/metamodel - com.mysema.query.apt.jpa.JPAAnnotationProcessor + target/generated-sources/java + com.querydsl.apt.jpa.JPAAnnotationProcessor diff --git a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java index 555ec226ce..9acaf1dd18 100644 --- a/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java +++ b/querydsl/src/main/java/org/baeldung/dao/PersonDaoImpl.java @@ -10,8 +10,8 @@ import org.baeldung.entity.Person; import org.baeldung.entity.QPerson; import org.springframework.stereotype.Repository; -import com.mysema.query.group.GroupBy; -import com.mysema.query.jpa.impl.JPAQuery; +import com.querydsl.core.group.GroupBy; +import com.querydsl.jpa.impl.JPAQuery; @Repository public class PersonDaoImpl implements PersonDao { @@ -27,39 +27,39 @@ public class PersonDaoImpl implements PersonDao { @Override public List findPersonsByFirstnameQueryDSL(final String firstname) { - final JPAQuery query = new JPAQuery(em); + final JPAQuery query = new JPAQuery<>(em); final QPerson person = QPerson.person; - return query.from(person).where(person.firstname.eq(firstname)).list(person); + return query.from(person).where(person.firstname.eq(firstname)).fetch(); } @Override public List findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) { - final JPAQuery query = new JPAQuery(em); + final JPAQuery query = new JPAQuery<>(em); final QPerson person = QPerson.person; - return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person); + return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch(); } @Override public List findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) { - final JPAQuery query = new JPAQuery(em); + final JPAQuery query = new JPAQuery<>(em); final QPerson person = QPerson.person; - return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person); + return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch(); } @Override public int findMaxAge() { - final JPAQuery query = new JPAQuery(em); + final JPAQuery query = new JPAQuery<>(em); final QPerson person = QPerson.person; - return query.from(person).list(person.age.max()).get(0); + return query.from(person).select(person.age.max()).fetchFirst(); } @Override public Map findMaxAgeByName() { - final JPAQuery query = new JPAQuery(em); + final JPAQuery query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java b/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java new file mode 100644 index 0000000000..241bc50b03 --- /dev/null +++ b/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/BlogPost.java @@ -0,0 +1,56 @@ +/* + * (c) Центр ИТ, 2016. Ð’Ñе права защищены. + */ +package org.baeldung.querydsl.intro.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class BlogPost { + + @Id + @GeneratedValue + private Long id; + + private String title; + + private String body; + + @ManyToOne + private User user; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String code) { + this.title = code; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java b/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java new file mode 100644 index 0000000000..c0681e15d1 --- /dev/null +++ b/querydsl/src/main/java/org/baeldung/querydsl/intro/entities/User.java @@ -0,0 +1,55 @@ +/* + * (c) Центр ИТ, 2016. Ð’Ñе права защищены. + */ +package org.baeldung.querydsl.intro.entities; + +import java.util.HashSet; +import java.util.Set; +import javax.persistence.*; + +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + + private String login; + + private Boolean disabled; + + @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "user") + private Set blogPosts = new HashSet<>(0); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String name) { + this.login = name; + } + + public Set getBlogPosts() { + return blogPosts; + } + + public void setBlogPosts(Set blogPosts) { + this.blogPosts = blogPosts; + } + + public Boolean getDisabled() { + return disabled; + } + + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } +} diff --git a/querydsl/src/main/resources/META-INF/persistence.xml b/querydsl/src/main/resources/META-INF/persistence.xml index 111d7933c3..2964382d48 100644 --- a/querydsl/src/main/resources/META-INF/persistence.xml +++ b/querydsl/src/main/resources/META-INF/persistence.xml @@ -16,4 +16,17 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + + + + + + + + + + \ No newline at end of file diff --git a/querydsl/src/main/resources/log4j.xml b/querydsl/src/main/resources/logback.xml similarity index 53% rename from querydsl/src/main/resources/log4j.xml rename to querydsl/src/main/resources/logback.xml index a7f96b38a4..d0a1dc06ac 100644 --- a/querydsl/src/main/resources/log4j.xml +++ b/querydsl/src/main/resources/logback.xml @@ -1,12 +1,9 @@ - - + - - - - - + + + %d{yyyy-MM-dd HH:mm:ss} [%t] %-5p: %c - %m%n @@ -33,10 +30,8 @@ - - - - + + - \ No newline at end of file + \ No newline at end of file diff --git a/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLTest.java b/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLTest.java new file mode 100644 index 0000000000..682fa2c245 --- /dev/null +++ b/querydsl/src/test/java/org/baeldung/querydsl/intro/QueryDSLTest.java @@ -0,0 +1,215 @@ +/* + * (c) Центр ИТ, 2016. Ð’Ñе права защищены. + */ +package org.baeldung.querydsl.intro; + +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.baeldung.querydsl.intro.entities.BlogPost; +import org.baeldung.querydsl.intro.entities.QBlogPost; +import org.baeldung.querydsl.intro.entities.QUser; +import org.baeldung.querydsl.intro.entities.User; +import com.querydsl.core.Tuple; +import com.querydsl.core.types.dsl.Expressions; +import com.querydsl.core.types.dsl.NumberPath; +import com.querydsl.jpa.JPAExpressions; +import com.querydsl.jpa.impl.JPAQueryFactory; +import org.junit.*; + +import static org.junit.Assert.*; + +public class QueryDSLTest { + + private static EntityManagerFactory emf; + + private EntityManager em; + + private JPAQueryFactory queryFactory; + + @BeforeClass + public static void populateDatabase() { + emf = Persistence.createEntityManagerFactory("org.baeldung.querydsl.intro"); + EntityManager em = emf.createEntityManager(); + + em.getTransaction().begin(); + User user1 = new User(); + user1.setLogin("David"); + em.persist(user1); + + User user2 = new User(); + user2.setLogin("Ash"); + em.persist(user2); + + User user3 = new User(); + user3.setLogin("Call"); + em.persist(user3); + + User user4 = new User(); + user4.setLogin("Bishop"); + em.persist(user4); + + BlogPost blogPost1 = new BlogPost(); + blogPost1.setTitle("Hello World!"); + blogPost1.setUser(user1); + em.persist(blogPost1); + + BlogPost blogPost2 = new BlogPost(); + blogPost2.setTitle("My Second Post"); + blogPost2.setUser(user1); + em.persist(blogPost2); + + BlogPost blogPost3 = new BlogPost(); + blogPost3.setTitle("Hello World!"); + blogPost3.setUser(user3); + em.persist(blogPost3); + + em.getTransaction().commit(); + + em.close(); + + } + + @Before + public void setUp() { + em = emf.createEntityManager(); + em.getTransaction().begin(); + queryFactory = new JPAQueryFactory(em); + } + + @Test + public void whenFindByLogin_thenShouldReturnUser() { + + QUser user = QUser.user; + User aUser = queryFactory.selectFrom(user) + .where(user.login.eq("David")) + .fetchOne(); + + assertNotNull(aUser); + assertEquals(aUser.getLogin(), "David"); + + } + + @Test + public void whenUsingOrderBy_thenResultsShouldBeOrdered() { + + QUser user = QUser.user; + List users = queryFactory.selectFrom(user) + .orderBy(user.login.asc()) + .fetch(); + + assertEquals(users.size(), 4); + assertEquals(users.get(0).getLogin(), "Ash"); + assertEquals(users.get(1).getLogin(), "Bishop"); + assertEquals(users.get(2).getLogin(), "Call"); + assertEquals(users.get(3).getLogin(), "David"); + + } + + @Test + public void whenGroupingByTitle_thenReturnsTuples() { + + QBlogPost blogPost = QBlogPost.blogPost; + + NumberPath count = Expressions.numberPath(Long.class, "c"); + + List userTitleCounts = queryFactory.select(blogPost.title, blogPost.id.count().as(count)) + .from(blogPost) + .groupBy(blogPost.title) + .orderBy(count.desc()) + .fetch(); + + assertEquals("Hello World!", userTitleCounts.get(0).get(blogPost.title)); + assertEquals(new Long(2), userTitleCounts.get(0).get(count)); + + assertEquals("My Second Post", userTitleCounts.get(1).get(blogPost.title)); + assertEquals(new Long(1), userTitleCounts.get(1).get(count)); + + } + + @Test + public void whenJoiningWithCondition_thenResultCountShouldMatch() { + + QUser user = QUser.user; + QBlogPost blogPost = QBlogPost.blogPost; + + List users = queryFactory.selectFrom(user) + .innerJoin(user.blogPosts, blogPost) + .on(blogPost.title.eq("Hello World!")) + .fetch(); + + assertEquals(2, users.size()); + } + + @Test + public void whenRefiningWithSubquery_thenResultCountShouldMatch() { + + QUser user = QUser.user; + QBlogPost blogPost = QBlogPost.blogPost; + + List users = queryFactory.selectFrom(user) + .where(user.id.in( + JPAExpressions.select(blogPost.user.id) + .from(blogPost) + .where(blogPost.title.eq("Hello World!")))) + .fetch(); + + assertEquals(2, users.size()); + } + + @Test + public void whenUpdating_thenTheRecordShouldChange() { + + QUser user = QUser.user; + + queryFactory.update(user) + .where(user.login.eq("Ash")) + .set(user.login, "Ash2") + .set(user.disabled, true) + .execute(); + + em.getTransaction().commit(); + + em.getTransaction().begin(); + + assertEquals(Boolean.TRUE, + queryFactory.select(user.disabled) + .from(user) + .where(user.login.eq("Ash2")) + .fetchOne()); + + } + + @Test + public void whenDeleting_thenTheRecordShouldBeAbsent() { + + QUser user = QUser.user; + + queryFactory.delete(user) + .where(user.login.eq("Bishop")) + .execute(); + + em.getTransaction().commit(); + + em.getTransaction().begin(); + + assertNull(queryFactory.selectFrom(user) + .where(user.login.eq("Bishop")) + .fetchOne()); + + } + + @After + public void tearDown() { + em.getTransaction().commit(); + em.close(); + } + + @AfterClass + public static void afterClass() { + emf.close(); + } + +} 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/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/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-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java new file mode 100644 index 0000000000..f96184a8a3 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/properties/spring/PropertiesWithPlaceHolderConfigurer.java @@ -0,0 +1,22 @@ +package org.baeldung.properties.spring; + +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class PropertiesWithPlaceHolderConfigurer { + + public PropertiesWithPlaceHolderConfigurer() { + super(); + } + + + @Bean + public PropertyPlaceholderConfigurer propertyConfigurer() { + final PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer(); + props.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK); + return props; + } + +} \ No newline at end of file diff --git a/spring-boot/.classpath b/spring-boot/.classpath deleted file mode 100644 index 26981b6dd7..0000000000 --- a/spring-boot/.classpath +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-boot/.gitignore b/spring-boot/.gitignore index 24d64373c4..e26d6af438 100644 --- a/spring-boot/.gitignore +++ b/spring-boot/.gitignore @@ -1 +1,4 @@ /target/ +.settings/ +.classpath +.project diff --git a/spring-boot/.project b/spring-boot/.project deleted file mode 100644 index e748dc5713..0000000000 --- a/spring-boot/.project +++ /dev/null @@ -1,48 +0,0 @@ - - - spring-boot - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - org.springframework.ide.eclipse.core.springbuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.springframework.ide.eclipse.core.springnature - 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 - org.eclipse.wst.jsdt.core.jsNature - - 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-boot/pom.xml b/spring-boot/pom.xml index d0a66197bf..368dfa19c1 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung spring-boot @@ -11,15 +12,29 @@ org.springframework.boot spring-boot-starter-parent - 1.3.3.RELEASE + 1.3.6.RELEASE + + + + org.baeldung.boot.DemoApplication + UTF-8 + 1.8 + + + org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + org.springframework.boot spring-boot-starter-actuator @@ -34,6 +49,17 @@ io.dropwizard.metrics metrics-core + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-test + test + @@ -70,4 +96,4 @@ - \ No newline at end of file + diff --git a/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java new file mode 100644 index 0000000000..e61d140396 --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/DemoApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + System.setProperty("spring.config.name", "demo"); + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java new file mode 100644 index 0000000000..6a36459e3c --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/model/Foo.java @@ -0,0 +1,39 @@ +package org.baeldung.boot.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Foo implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue + private Integer id; + private String name; + + public Foo() { + } + + public Foo(String name) { + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java b/spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java new file mode 100644 index 0000000000..09d6975dba --- /dev/null +++ b/spring-boot/src/main/java/org/baeldung/boot/repository/FooRepository.java @@ -0,0 +1,8 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.model.Foo; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FooRepository extends JpaRepository { + public Foo findByName(String name); +} diff --git a/spring-boot/src/main/resources/demo.properties b/spring-boot/src/main/resources/demo.properties new file mode 100644 index 0000000000..649b64f59b --- /dev/null +++ b/spring-boot/src/main/resources/demo.properties @@ -0,0 +1,6 @@ +spring.output.ansi.enabled=never +server.port=7070 + +# Security +security.user.name=admin +security.user.password=password \ No newline at end of file diff --git a/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java new file mode 100644 index 0000000000..41c5a545cc --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationTests.java @@ -0,0 +1,17 @@ +package org.baeldung.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = DemoApplication.class) +@WebAppConfiguration +public class DemoApplicationTests { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java new file mode 100644 index 0000000000..9de7790a75 --- /dev/null +++ b/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryTest.java @@ -0,0 +1,34 @@ +package org.baeldung.boot.repository; + +import static org.junit.Assert.assertThat; + +import org.baeldung.boot.DemoApplicationTests; +import org.baeldung.boot.model.Foo; + +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.is; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class FooRepositoryTest extends DemoApplicationTests { + @Autowired + private FooRepository fooRepository; + + @Before + public void setUp() { + fooRepository.save(new Foo("Foo")); + fooRepository.save(new Foo("Bar")); + } + + @Test + public void testFindByName() { + Foo foo = fooRepository.findByName("Bar"); + assertThat(foo, notNullValue()); + assertThat(foo.getId(), is(2)); + } + +} 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> graph(@Param("limit") int limit); +} + + diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java new file mode 100644 index 0000000000..4c287f99a4 --- /dev/null +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/PersonRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.data.neo4j.repostory; + +import com.baeldung.spring.data.neo4j.domain.Person; +import org.springframework.data.neo4j.repository.GraphRepository; +import org.springframework.stereotype.Repository; + + +@Repository +public interface PersonRepository extends GraphRepository { + +} diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java new file mode 100644 index 0000000000..532cc79091 --- /dev/null +++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/services/MovieService.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.data.neo4j.services; + +import com.baeldung.spring.data.neo4j.repostory.MovieRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; + +@Service +@Transactional +public class MovieService { + + @Autowired + MovieRepository movieRepository; + + private Map toD3Format(Iterator> result) { + List> nodes = new ArrayList>(); + List> rels= new ArrayList>(); + int i=0; + while (result.hasNext()) { + Map row = result.next(); + nodes.add(map("title",row.get("movie"),"label","movie")); + int target=i; + i++; + for (Object name : (Collection) row.get("cast")) { + Map actor = map("title", name,"label","actor"); + int source = nodes.indexOf(actor); + if (source == -1) { + nodes.add(actor); + source = i++; + } + rels.add(map("source",source,"target",target)); + } + } + return map("nodes", nodes, "links", rels); + } + + private Map map(String key1, Object value1, String key2, Object value2) { + Map result = new HashMap(2); + result.put(key1,value1); + result.put(key2,value2); + return result; + } + + public Map graph(int limit) { + Iterator> result = movieRepository.graph(limit).iterator(); + return toD3Format(result); + } +} diff --git a/spring-data-neo4j/src/main/resources/logback.xml b/spring-data-neo4j/src/main/resources/logback.xml new file mode 100644 index 0000000000..215eeede64 --- /dev/null +++ b/spring-data-neo4j/src/main/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-data-neo4j/src/main/resources/test.png b/spring-data-neo4j/src/main/resources/test.png new file mode 100644 index 0000000000..c3b5e80276 Binary files /dev/null and b/spring-data-neo4j/src/main/resources/test.png differ diff --git a/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java new file mode 100644 index 0000000000..8061b3c2a7 --- /dev/null +++ b/spring-data-neo4j/src/test/java/com/baeldung/spring/data/neo4j/MovieRepositoryTest.java @@ -0,0 +1,133 @@ +package com.baeldung.spring.data.neo4j; + +import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration; +import com.baeldung.spring.data.neo4j.domain.Movie; +import com.baeldung.spring.data.neo4j.domain.Person; +import com.baeldung.spring.data.neo4j.domain.Role; +import com.baeldung.spring.data.neo4j.repostory.MovieRepository; +import com.baeldung.spring.data.neo4j.repostory.PersonRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.*; + +import static junit.framework.TestCase.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class) +@ActiveProfiles(profiles = "test") +public class MovieRepositoryTest { + + @Autowired + private MovieRepository movieRepository; + + @Autowired + private PersonRepository personRepository; + + public MovieRepositoryTest() { + } + + @Before + public void initializeDatabase() { + System.out.println("seeding embedded database"); + Movie italianJob = new Movie(); + italianJob.setTitle("The Italian Job"); + italianJob.setReleased(1999); + movieRepository.save(italianJob); + + Person mark = new Person(); + mark.setName("Mark Wahlberg"); + personRepository.save(mark); + + Role charlie = new Role(); + charlie.setMovie(italianJob); + charlie.setPerson(mark); + Collection roleNames = new HashSet(); + roleNames.add("Charlie Croker"); + charlie.setRoles(roleNames); + List roles = new ArrayList(); + roles.add(charlie); + italianJob.setRoles(roles); + movieRepository.save(italianJob); + } + + @Test + @DirtiesContext + public void testFindByTitle() { + System.out.println("findByTitle"); + String title = "The Italian Job"; + Movie result = movieRepository.findByTitle(title); + assertNotNull(result); + assertEquals(1999, result.getReleased()); + } + + @Test + @DirtiesContext + public void testCount() { + System.out.println("count"); + long movieCount = movieRepository.count(); + assertNotNull(movieCount); + assertEquals(1, movieCount); + } + + @Test + @DirtiesContext + public void testFindAll() { + System.out.println("findAll"); + Collection result = + (Collection) movieRepository.findAll(); + assertNotNull(result); + assertEquals(1, result.size()); + } + + @Test + @DirtiesContext + public void testFindByTitleContaining() { + System.out.println("findByTitleContaining"); + String title = "Italian"; + Collection result = + movieRepository.findByTitleContaining(title); + assertNotNull(result); + assertEquals(1, result.size()); + } + + @Test + @DirtiesContext + public void testGraph() { + System.out.println("graph"); + List> graph = movieRepository.graph(5); + assertEquals(1, graph.size()); + Map map = graph.get(0); + assertEquals(2, map.size()); + String[] cast = (String[]) map.get("cast"); + String movie = (String) map.get("movie"); + assertEquals("The Italian Job", movie); + assertEquals("Mark Wahlberg", cast[0]); + } + + @Test + @DirtiesContext + public void testDeleteMovie() { + System.out.println("deleteMovie"); + movieRepository.delete(movieRepository.findByTitle("The Italian Job")); + assertNull(movieRepository.findByTitle("The Italian Job")); + } + + @Test + @DirtiesContext + public void testDeleteAll() { + System.out.println("deleteAll"); + movieRepository.deleteAll(); + Collection result = + (Collection) movieRepository.findAll(); + assertEquals(0, result.size()); + } +} diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index d9be83113b..7dc439206b 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -1,3 +1,6 @@ +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + # About this project This project contains examples from the [Introduction to Spring Data REST](http://www.baeldung.com/spring-data-rest-intro) article from Baeldung. diff --git a/spring-hibernate4/README.md b/spring-hibernate4/README.md index 4c0c6706d6..4b48fe7064 100644 --- a/spring-hibernate4/README.md +++ b/spring-hibernate4/README.md @@ -8,7 +8,7 @@ - [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort) - [Auditing with JPA, Hibernate, and Spring Data JPA](http://www.baeldung.com/database-auditing-jpa) - +- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial) ### Quick Start diff --git a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java index 6b48c1fa66..bdd48d6aa6 100644 --- a/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/spring-hibernate4/src/main/java/com/baeldung/persistence/model/Foo.java @@ -11,93 +11,97 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; import org.hibernate.envers.Audited; +@NamedNativeQueries({ + @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), + @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) }) @Entity @Audited // @Proxy(lazy = false) public class Foo implements Serializable { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); - public Foo() { - super(); - } + public Foo() { + super(); + } - public Foo(final String name) { - super(); - this.name = name; - } + public Foo(final String name) { + super(); + this.name = name; + } - // + // - public Bar getBar() { - return bar; - } + public Bar getBar() { + return bar; + } - public void setBar(final Bar bar) { - this.bar = bar; - } + public void setBar(final Bar bar) { + this.bar = bar; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(final long id) { - this.id = id; - } + public void setId(final long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(final String name) { - this.name = name; - } + public void setName(final String name) { + this.name = name; + } - // + // - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } } diff --git a/spring-hibernate4/src/main/resources/stored_procedure.sql b/spring-hibernate4/src/main/resources/stored_procedure.sql new file mode 100644 index 0000000000..8e1bdf57dd --- /dev/null +++ b/spring-hibernate4/src/main/resources/stored_procedure.sql @@ -0,0 +1,20 @@ +DELIMITER // + CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255)) + LANGUAGE SQL + DETERMINISTIC + SQL SECURITY DEFINER + BEGIN + SELECT * FROM foo WHERE name = fooName; + END // +DELIMITER ; + + +DELIMITER // + CREATE PROCEDURE GetAllFoos() + LANGUAGE SQL + DETERMINISTIC + SQL SECURITY DEFINER + BEGIN + SELECT * FROM foo; + END // +DELIMITER ; \ No newline at end of file diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java new file mode 100644 index 0000000000..238b228101 --- /dev/null +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/service/FooStoredProceduresIntegrationTest.java @@ -0,0 +1,126 @@ +package com.baeldung.persistence.service; + +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.exception.SQLGrammarException; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 com.baeldung.persistence.model.Foo; +import com.baeldung.spring.PersistenceConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersistenceConfig.class}, loader = AnnotationConfigContextLoader.class) +public class FooStoredProceduresIntegrationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresIntegrationTest.class); + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + private IFooService fooService; + + private Session session; + + @Before + public final void before() { + session = sessionFactory.openSession(); + Assume.assumeTrue(getAllFoosExists()); + Assume.assumeTrue(getFoosByNameExists()); + } + + private boolean getFoosByNameExists() { + try { + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") + .addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); + return false; + } + } + + private boolean getAllFoosExists() { + try { + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()") + .addEntity(Foo.class); + sqlQuery.list(); + return true; + } catch (SQLGrammarException e) { + LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); + return false; + } + } + + @After + public final void after() { + session.close(); + } + + @Test + public final void getAllFoosUsingStoredProcedures() { + + fooService.create(new Foo(randomAlphabetic(6))); + + // Stored procedure getAllFoos using createSQLQuery + Query sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity( + Foo.class); + @SuppressWarnings("unchecked") + List allFoos = sqlQuery.list(); + for (Foo foo : allFoos) { + LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); + } + assertEquals(allFoos.size(), fooService.findAll().size()); + + // Stored procedure getAllFoos using a Named Query + Query namedQuery = session.getNamedQuery("callGetAllFoos"); + @SuppressWarnings("unchecked") + List allFoos2 = namedQuery.list(); + for (Foo foo : allFoos2) { + LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); + } + assertEquals(allFoos2.size(), fooService.findAll().size()); + } + + @Test + public final void getFoosByNameUsingStoredProcedures() { + + fooService.create(new Foo("NewFooName")); + + // Stored procedure getFoosByName using createSQLQuery() + Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)") + .addEntity(Foo.class).setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName = sqlQuery.list(); + for (Foo foo : allFoosByName) { + LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); + } + + // Stored procedure getFoosByName using getNamedQuery() + Query namedQuery = session.getNamedQuery("callGetFoosByName") + .setParameter("fooName", "NewFooName"); + @SuppressWarnings("unchecked") + List allFoosByName2 = namedQuery.list(); + for (Foo foo : allFoosByName2) { + LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); + } + + } +} diff --git a/spring-katharsis/README.md b/spring-katharsis/README.md index ec0141f41a..cf2a001760 100644 --- a/spring-katharsis/README.md +++ b/spring-katharsis/README.md @@ -2,5 +2,8 @@ ## Java Web Application +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + ### Relevant Articles: - [JSON API in a Java Web Application](http://www.baeldung.com/json-api-java-spring-web-app) diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index e5264b0370..951d80033e 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -2,6 +2,8 @@ ## Spring MVC with Java Configuration Example Project +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring Bean Annotations](http://www.baeldung.com/spring-bean-annotations) diff --git a/spring-mvc-no-xml/README.md b/spring-mvc-no-xml/README.md index 5ffe2385b5..208cb35f78 100644 --- a/spring-mvc-no-xml/README.md +++ b/spring-mvc-no-xml/README.md @@ -2,6 +2,8 @@ ## Spring MVC with NO XML Configuration Example Project +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: -- \ No newline at end of file +- diff --git a/spring-mvc-xml/README.md b/spring-mvc-xml/README.md index 2409ec8174..ce823a9682 100644 --- a/spring-mvc-xml/README.md +++ b/spring-mvc-xml/README.md @@ -1,5 +1,8 @@ ========= +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + ## Spring MVC with XML Configuration Example Project - access a sample jsp page at: `http://localhost:8080/spring-mvc-xml/sample.html` diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml new file mode 100644 index 0000000000..1275d72edf --- /dev/null +++ b/spring-protobuf/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + com.baeldung + spring-protobuf + 0.1-SNAPSHOT + spring-protobuf + + + org.springframework.boot + spring-boot-starter-parent + 1.2.4.RELEASE + + + + + com.google.protobuf + protobuf-java + 3.0.0-beta-3 + + + com.googlecode.protobuf-java-format + protobuf-java-format + 1.4 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + + diff --git a/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java b/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java new file mode 100644 index 0000000000..76f0e45244 --- /dev/null +++ b/spring-protobuf/src/main/java/com/baeldung/protobuf/Application.java @@ -0,0 +1,66 @@ +package com.baeldung.protobuf; + +import com.baeldung.protobuf.BaeldungTraining.Course; +import com.baeldung.protobuf.BaeldungTraining.Student; +import com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber; +import com.baeldung.protobuf.BaeldungTraining.Student.PhoneType; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@SpringBootApplication +public class Application { + + @Bean + RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) { + return new RestTemplate(Arrays.asList(hmc)); + } + + @Bean + ProtobufHttpMessageConverter protobufHttpMessageConverter() { + return new ProtobufHttpMessageConverter(); + } + + @Bean + public CourseRepository createTestCourses() { + Map courses = new HashMap<>(); + + Course course1 = Course.newBuilder().setId(1).setCourseName("REST with Spring").addAllStudent(createTestStudents()).build(); + + Course course2 = Course.newBuilder().setId(2).setCourseName("Learn Spring Security").addAllStudent(new ArrayList<>()).build(); + + courses.put(course1.getId(), course1); + courses.put(course2.getId(), course2); + + return new CourseRepository(courses); + } + + private List createTestStudents() { + PhoneNumber phone1 = createPhone("123456", PhoneType.MOBILE); + Student student1 = createStudent(1, "John", "Doe", "john.doe@baeldung.com", Arrays.asList(phone1)); + + PhoneNumber phone2 = createPhone("234567", PhoneType.LANDLINE); + Student student2 = createStudent(2, "Richard", "Roe", "richard.roe@baeldung.com", Arrays.asList(phone2)); + + PhoneNumber phone3_1 = createPhone("345678", PhoneType.MOBILE); + PhoneNumber phone3_2 = createPhone("456789", PhoneType.LANDLINE); + Student student3 = createStudent(3, "Jane", "Doe", "jane.doe@baeldung.com", Arrays.asList(phone3_1, phone3_2)); + + return Arrays.asList(student1, student2, student3); + } + + private Student createStudent(int id, String firstName, String lastName, String email, List phones) { + return Student.newBuilder().setId(id).setFirstName(firstName).setLastName(lastName).setEmail(email).addAllPhone(phones).build(); + } + + private PhoneNumber createPhone(String number, PhoneType type) { + return PhoneNumber.newBuilder().setNumber(number).setType(type).build(); + } +} \ No newline at end of file diff --git a/spring-protobuf/src/main/java/com/baeldung/protobuf/BaeldungTraining.java b/spring-protobuf/src/main/java/com/baeldung/protobuf/BaeldungTraining.java new file mode 100644 index 0000000000..5cab2ae908 --- /dev/null +++ b/spring-protobuf/src/main/java/com/baeldung/protobuf/BaeldungTraining.java @@ -0,0 +1,2589 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: resources/baeldung.proto + +package com.baeldung.protobuf; + +public final class BaeldungTraining { + private BaeldungTraining() { + } + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + } + + public interface CourseOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Course) + com.google.protobuf.MessageOrBuilder { + + /** + * optional int32 id = 1; + */ + int getId(); + + /** + * optional string course_name = 2; + */ + java.lang.String getCourseName(); + + /** + * optional string course_name = 2; + */ + com.google.protobuf.ByteString getCourseNameBytes(); + + /** + * repeated .baeldung.Student student = 3; + */ + java.util.List getStudentList(); + + /** + * repeated .baeldung.Student student = 3; + */ + com.baeldung.protobuf.BaeldungTraining.Student getStudent(int index); + + /** + * repeated .baeldung.Student student = 3; + */ + int getStudentCount(); + + /** + * repeated .baeldung.Student student = 3; + */ + java.util.List getStudentOrBuilderList(); + + /** + * repeated .baeldung.Student student = 3; + */ + com.baeldung.protobuf.BaeldungTraining.StudentOrBuilder getStudentOrBuilder(int index); + } + + /** + * Protobuf type {@code baeldung.Course} + */ + public static final class Course extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Course) + CourseOrBuilder { + // Use Course.newBuilder() to construct. + private Course(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + } + + private Course() { + id_ = 0; + courseName_ = ""; + student_ = java.util.Collections.emptyList(); + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); + } + + private Course(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!input.skipField(tag)) { + done = true; + } + break; + } + case 8: { + + id_ = input.readInt32(); + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + + courseName_ = s; + break; + } + case 26: { + if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + student_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000004; + } + student_.add(input.readMessage(com.baeldung.protobuf.BaeldungTraining.Student.parser(), extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + student_ = java.util.Collections.unmodifiableList(student_); + } + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Course_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Course_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Course.class, com.baeldung.protobuf.BaeldungTraining.Course.Builder.class); + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private int id_; + + /** + * optional int32 id = 1; + */ + public int getId() { + return id_; + } + + public static final int COURSE_NAME_FIELD_NUMBER = 2; + private volatile java.lang.Object courseName_; + + /** + * optional string course_name = 2; + */ + public java.lang.String getCourseName() { + java.lang.Object ref = courseName_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + courseName_ = s; + return s; + } + } + + /** + * optional string course_name = 2; + */ + public com.google.protobuf.ByteString getCourseNameBytes() { + java.lang.Object ref = courseName_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + courseName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int STUDENT_FIELD_NUMBER = 3; + private java.util.List student_; + + /** + * repeated .baeldung.Student student = 3; + */ + public java.util.List getStudentList() { + return student_; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public java.util.List getStudentOrBuilderList() { + return student_; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public int getStudentCount() { + return student_.size(); + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.Student getStudent(int index) { + return student_.get(index); + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.StudentOrBuilder getStudentOrBuilder(int index) { + return student_.get(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (id_ != 0) { + output.writeInt32(1, id_); + } + if (!getCourseNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessage.writeString(output, 2, courseName_); + } + for (int i = 0; i < student_.size(); i++) { + output.writeMessage(3, student_.get(i)); + } + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) + return size; + + size = 0; + if (id_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, id_); + } + if (!getCourseNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessage.computeStringSize(2, courseName_); + } + for (int i = 0; i < student_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, student_.get(i)); + } + memoizedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(com.baeldung.protobuf.BaeldungTraining.Course prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Course} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Course) + com.baeldung.protobuf.BaeldungTraining.CourseOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Course_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Course_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Course.class, com.baeldung.protobuf.BaeldungTraining.Course.Builder.class); + } + + // Construct using com.baeldung.protobuf.BaeldungTraining.Course.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getStudentFieldBuilder(); + } + } + + public Builder clear() { + super.clear(); + id_ = 0; + + courseName_ = ""; + + if (studentBuilder_ == null) { + student_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + } else { + studentBuilder_.clear(); + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Course_descriptor; + } + + public com.baeldung.protobuf.BaeldungTraining.Course getDefaultInstanceForType() { + return com.baeldung.protobuf.BaeldungTraining.Course.getDefaultInstance(); + } + + public com.baeldung.protobuf.BaeldungTraining.Course build() { + com.baeldung.protobuf.BaeldungTraining.Course result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public com.baeldung.protobuf.BaeldungTraining.Course buildPartial() { + com.baeldung.protobuf.BaeldungTraining.Course result = new com.baeldung.protobuf.BaeldungTraining.Course(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.id_ = id_; + result.courseName_ = courseName_; + if (studentBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004)) { + student_ = java.util.Collections.unmodifiableList(student_); + bitField0_ = (bitField0_ & ~0x00000004); + } + result.student_ = student_; + } else { + result.student_ = studentBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.baeldung.protobuf.BaeldungTraining.Course) { + return mergeFrom((com.baeldung.protobuf.BaeldungTraining.Course) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.baeldung.protobuf.BaeldungTraining.Course other) { + if (other == com.baeldung.protobuf.BaeldungTraining.Course.getDefaultInstance()) + return this; + if (other.getId() != 0) { + setId(other.getId()); + } + if (!other.getCourseName().isEmpty()) { + courseName_ = other.courseName_; + onChanged(); + } + if (studentBuilder_ == null) { + if (!other.student_.isEmpty()) { + if (student_.isEmpty()) { + student_ = other.student_; + bitField0_ = (bitField0_ & ~0x00000004); + } else { + ensureStudentIsMutable(); + student_.addAll(other.student_); + } + onChanged(); + } + } else { + if (!other.student_.isEmpty()) { + if (studentBuilder_.isEmpty()) { + studentBuilder_.dispose(); + studentBuilder_ = null; + student_ = other.student_; + bitField0_ = (bitField0_ & ~0x00000004); + studentBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getStudentFieldBuilder() : null; + } else { + studentBuilder_.addAllMessages(other.student_); + } + } + } + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + com.baeldung.protobuf.BaeldungTraining.Course parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (com.baeldung.protobuf.BaeldungTraining.Course) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private int id_; + + /** + * optional int32 id = 1; + */ + public int getId() { + return id_; + } + + /** + * optional int32 id = 1; + */ + public Builder setId(int value) { + + id_ = value; + onChanged(); + return this; + } + + /** + * optional int32 id = 1; + */ + public Builder clearId() { + + id_ = 0; + onChanged(); + return this; + } + + private java.lang.Object courseName_ = ""; + + /** + * optional string course_name = 2; + */ + public java.lang.String getCourseName() { + java.lang.Object ref = courseName_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + courseName_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * optional string course_name = 2; + */ + public com.google.protobuf.ByteString getCourseNameBytes() { + java.lang.Object ref = courseName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + courseName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * optional string course_name = 2; + */ + public Builder setCourseName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + courseName_ = value; + onChanged(); + return this; + } + + /** + * optional string course_name = 2; + */ + public Builder clearCourseName() { + + courseName_ = getDefaultInstance().getCourseName(); + onChanged(); + return this; + } + + /** + * optional string course_name = 2; + */ + public Builder setCourseNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + courseName_ = value; + onChanged(); + return this; + } + + private java.util.List student_ = java.util.Collections.emptyList(); + + private void ensureStudentIsMutable() { + if (!((bitField0_ & 0x00000004) == 0x00000004)) { + student_ = new java.util.ArrayList(student_); + bitField0_ |= 0x00000004; + } + } + + private com.google.protobuf.RepeatedFieldBuilder studentBuilder_; + + /** + * repeated .baeldung.Student student = 3; + */ + public java.util.List getStudentList() { + if (studentBuilder_ == null) { + return java.util.Collections.unmodifiableList(student_); + } else { + return studentBuilder_.getMessageList(); + } + } + + /** + * repeated .baeldung.Student student = 3; + */ + public int getStudentCount() { + if (studentBuilder_ == null) { + return student_.size(); + } else { + return studentBuilder_.getCount(); + } + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.Student getStudent(int index) { + if (studentBuilder_ == null) { + return student_.get(index); + } else { + return studentBuilder_.getMessage(index); + } + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder setStudent(int index, com.baeldung.protobuf.BaeldungTraining.Student value) { + if (studentBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureStudentIsMutable(); + student_.set(index, value); + onChanged(); + } else { + studentBuilder_.setMessage(index, value); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder setStudent(int index, com.baeldung.protobuf.BaeldungTraining.Student.Builder builderForValue) { + if (studentBuilder_ == null) { + ensureStudentIsMutable(); + student_.set(index, builderForValue.build()); + onChanged(); + } else { + studentBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder addStudent(com.baeldung.protobuf.BaeldungTraining.Student value) { + if (studentBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureStudentIsMutable(); + student_.add(value); + onChanged(); + } else { + studentBuilder_.addMessage(value); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder addStudent(int index, com.baeldung.protobuf.BaeldungTraining.Student value) { + if (studentBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureStudentIsMutable(); + student_.add(index, value); + onChanged(); + } else { + studentBuilder_.addMessage(index, value); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder addStudent(com.baeldung.protobuf.BaeldungTraining.Student.Builder builderForValue) { + if (studentBuilder_ == null) { + ensureStudentIsMutable(); + student_.add(builderForValue.build()); + onChanged(); + } else { + studentBuilder_.addMessage(builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder addStudent(int index, com.baeldung.protobuf.BaeldungTraining.Student.Builder builderForValue) { + if (studentBuilder_ == null) { + ensureStudentIsMutable(); + student_.add(index, builderForValue.build()); + onChanged(); + } else { + studentBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder addAllStudent(java.lang.Iterable values) { + if (studentBuilder_ == null) { + ensureStudentIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, student_); + onChanged(); + } else { + studentBuilder_.addAllMessages(values); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder clearStudent() { + if (studentBuilder_ == null) { + student_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000004); + onChanged(); + } else { + studentBuilder_.clear(); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public Builder removeStudent(int index) { + if (studentBuilder_ == null) { + ensureStudentIsMutable(); + student_.remove(index); + onChanged(); + } else { + studentBuilder_.remove(index); + } + return this; + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.Builder getStudentBuilder(int index) { + return getStudentFieldBuilder().getBuilder(index); + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.StudentOrBuilder getStudentOrBuilder(int index) { + if (studentBuilder_ == null) { + return student_.get(index); + } else { + return studentBuilder_.getMessageOrBuilder(index); + } + } + + /** + * repeated .baeldung.Student student = 3; + */ + public java.util.List getStudentOrBuilderList() { + if (studentBuilder_ != null) { + return studentBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(student_); + } + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.Builder addStudentBuilder() { + return getStudentFieldBuilder().addBuilder(com.baeldung.protobuf.BaeldungTraining.Student.getDefaultInstance()); + } + + /** + * repeated .baeldung.Student student = 3; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.Builder addStudentBuilder(int index) { + return getStudentFieldBuilder().addBuilder(index, com.baeldung.protobuf.BaeldungTraining.Student.getDefaultInstance()); + } + + /** + * repeated .baeldung.Student student = 3; + */ + public java.util.List getStudentBuilderList() { + return getStudentFieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilder getStudentFieldBuilder() { + if (studentBuilder_ == null) { + studentBuilder_ = new com.google.protobuf.RepeatedFieldBuilder(student_, + ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); + student_ = null; + } + return studentBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Course) + } + + // @@protoc_insertion_point(class_scope:baeldung.Course) + private static final com.baeldung.protobuf.BaeldungTraining.Course DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new com.baeldung.protobuf.BaeldungTraining.Course(); + } + + public static com.baeldung.protobuf.BaeldungTraining.Course getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Course parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Course(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.baeldung.protobuf.BaeldungTraining.Course getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface StudentOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Student) + com.google.protobuf.MessageOrBuilder { + + /** + * optional int32 id = 1; + */ + int getId(); + + /** + * optional string first_name = 2; + */ + java.lang.String getFirstName(); + + /** + * optional string first_name = 2; + */ + com.google.protobuf.ByteString getFirstNameBytes(); + + /** + * optional string last_name = 3; + */ + java.lang.String getLastName(); + + /** + * optional string last_name = 3; + */ + com.google.protobuf.ByteString getLastNameBytes(); + + /** + * optional string email = 4; + */ + java.lang.String getEmail(); + + /** + * optional string email = 4; + */ + com.google.protobuf.ByteString getEmailBytes(); + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + java.util.List getPhoneList(); + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getPhone(int index); + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + int getPhoneCount(); + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + java.util.List getPhoneOrBuilderList(); + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumberOrBuilder getPhoneOrBuilder(int index); + } + + /** + * Protobuf type {@code baeldung.Student} + */ + public static final class Student extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Student) + StudentOrBuilder { + // Use Student.newBuilder() to construct. + private Student(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + } + + private Student() { + id_ = 0; + firstName_ = ""; + lastName_ = ""; + email_ = ""; + phone_ = java.util.Collections.emptyList(); + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); + } + + private Student(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!input.skipField(tag)) { + done = true; + } + break; + } + case 8: { + + id_ = input.readInt32(); + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + + firstName_ = s; + break; + } + case 26: { + java.lang.String s = input.readStringRequireUtf8(); + + lastName_ = s; + break; + } + case 34: { + java.lang.String s = input.readStringRequireUtf8(); + + email_ = s; + break; + } + case 42: { + if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { + phone_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000010; + } + phone_.add(input.readMessage(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.parser(), extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + } + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Student.class, com.baeldung.protobuf.BaeldungTraining.Student.Builder.class); + } + + /** + * Protobuf enum {@code baeldung.Student.PhoneType} + */ + public enum PhoneType implements com.google.protobuf.ProtocolMessageEnum { + /** + * MOBILE = 0; + */ + MOBILE(0), + /** + * LANDLINE = 1; + */ + LANDLINE(1), UNRECOGNIZED(-1),; + + /** + * MOBILE = 0; + */ + public static final int MOBILE_VALUE = 0; + /** + * LANDLINE = 1; + */ + public static final int LANDLINE_VALUE = 1; + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException("Can't get the number of an unknown enum value."); + } + return value; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static PhoneType valueOf(int value) { + return forNumber(value); + } + + public static PhoneType forNumber(int value) { + switch (value) { + case 0: + return MOBILE; + case 1: + return LANDLINE; + default: + return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { + return internalValueMap; + } + + private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { + public PhoneType findValueByNumber(int number) { + return PhoneType.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } + + public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { + return getDescriptor(); + } + + public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.Student.getDescriptor().getEnumTypes().get(0); + } + + private static final PhoneType[] VALUES = values(); + + public static PhoneType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); + } + if (desc.getIndex() == -1) { + return UNRECOGNIZED; + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private PhoneType(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:baeldung.Student.PhoneType) + } + + public interface PhoneNumberOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Student.PhoneNumber) + com.google.protobuf.MessageOrBuilder { + + /** + * optional string number = 1; + */ + java.lang.String getNumber(); + + /** + * optional string number = 1; + */ + com.google.protobuf.ByteString getNumberBytes(); + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + int getTypeValue(); + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + com.baeldung.protobuf.BaeldungTraining.Student.PhoneType getType(); + } + + /** + * Protobuf type {@code baeldung.Student.PhoneNumber} + */ + public static final class PhoneNumber extends com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Student.PhoneNumber) + PhoneNumberOrBuilder { + // Use PhoneNumber.newBuilder() to construct. + private PhoneNumber(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + } + + private PhoneNumber() { + number_ = ""; + type_ = 0; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); + } + + private PhoneNumber(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + this(); + int mutable_bitField0_ = 0; + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!input.skipField(tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + + number_ = s; + break; + } + case 16: { + int rawValue = input.readEnum(); + + type_ = rawValue; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_PhoneNumber_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_PhoneNumber_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.class, + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder.class); + } + + public static final int NUMBER_FIELD_NUMBER = 1; + private volatile java.lang.Object number_; + + /** + * optional string number = 1; + */ + public java.lang.String getNumber() { + java.lang.Object ref = number_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + number_ = s; + return s; + } + } + + /** + * optional string number = 1; + */ + public com.google.protobuf.ByteString getNumberBytes() { + java.lang.Object ref = number_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int TYPE_FIELD_NUMBER = 2; + private int type_; + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public int getTypeValue() { + return type_; + } + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneType getType() { + com.baeldung.protobuf.BaeldungTraining.Student.PhoneType result = com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.forNumber(type_); + return result == null ? com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.UNRECOGNIZED : result; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getNumberBytes().isEmpty()) { + com.google.protobuf.GeneratedMessage.writeString(output, 1, number_); + } + if (type_ != com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.MOBILE.getNumber()) { + output.writeEnum(2, type_); + } + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) + return size; + + size = 0; + if (!getNumberBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessage.computeStringSize(1, number_); + } + if (type_ != com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.MOBILE.getNumber()) { + size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, type_); + } + memoizedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Student.PhoneNumber} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Student.PhoneNumber) + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumberOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_PhoneNumber_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_PhoneNumber_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.class, + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder.class); + } + + // Construct using com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + + public Builder clear() { + super.clear(); + number_ = ""; + + type_ = 0; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_PhoneNumber_descriptor; + } + + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getDefaultInstanceForType() { + return com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.getDefaultInstance(); + } + + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber build() { + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber buildPartial() { + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber result = new com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber(this); + result.number_ = number_; + result.type_ = type_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber) { + return mergeFrom((com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber other) { + if (other == com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.getDefaultInstance()) + return this; + if (!other.getNumber().isEmpty()) { + number_ = other.number_; + onChanged(); + } + if (other.type_ != 0) { + setTypeValue(other.getTypeValue()); + } + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object number_ = ""; + + /** + * optional string number = 1; + */ + public java.lang.String getNumber() { + java.lang.Object ref = number_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + number_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * optional string number = 1; + */ + public com.google.protobuf.ByteString getNumberBytes() { + java.lang.Object ref = number_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + number_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * optional string number = 1; + */ + public Builder setNumber(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + number_ = value; + onChanged(); + return this; + } + + /** + * optional string number = 1; + */ + public Builder clearNumber() { + + number_ = getDefaultInstance().getNumber(); + onChanged(); + return this; + } + + /** + * optional string number = 1; + */ + public Builder setNumberBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + number_ = value; + onChanged(); + return this; + } + + private int type_ = 0; + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public int getTypeValue() { + return type_; + } + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public Builder setTypeValue(int value) { + type_ = value; + onChanged(); + return this; + } + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneType getType() { + com.baeldung.protobuf.BaeldungTraining.Student.PhoneType result = com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.forNumber(type_); + return result == null ? com.baeldung.protobuf.BaeldungTraining.Student.PhoneType.UNRECOGNIZED : result; + } + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public Builder setType(com.baeldung.protobuf.BaeldungTraining.Student.PhoneType value) { + if (value == null) { + throw new NullPointerException(); + } + + type_ = value.getNumber(); + onChanged(); + return this; + } + + /** + * optional .baeldung.Student.PhoneType type = 2; + */ + public Builder clearType() { + + type_ = 0; + onChanged(); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Student.PhoneNumber) + } + + // @@protoc_insertion_point(class_scope:baeldung.Student.PhoneNumber) + private static final com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber(); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public PhoneNumber parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new PhoneNumber(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private int id_; + + /** + * optional int32 id = 1; + */ + public int getId() { + return id_; + } + + public static final int FIRST_NAME_FIELD_NUMBER = 2; + private volatile java.lang.Object firstName_; + + /** + * optional string first_name = 2; + */ + public java.lang.String getFirstName() { + java.lang.Object ref = firstName_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + firstName_ = s; + return s; + } + } + + /** + * optional string first_name = 2; + */ + public com.google.protobuf.ByteString getFirstNameBytes() { + java.lang.Object ref = firstName_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + firstName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int LAST_NAME_FIELD_NUMBER = 3; + private volatile java.lang.Object lastName_; + + /** + * optional string last_name = 3; + */ + public java.lang.String getLastName() { + java.lang.Object ref = lastName_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + lastName_ = s; + return s; + } + } + + /** + * optional string last_name = 3; + */ + public com.google.protobuf.ByteString getLastNameBytes() { + java.lang.Object ref = lastName_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + lastName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int EMAIL_FIELD_NUMBER = 4; + private volatile java.lang.Object email_; + + /** + * optional string email = 4; + */ + public java.lang.String getEmail() { + java.lang.Object ref = email_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + email_ = s; + return s; + } + } + + /** + * optional string email = 4; + */ + public com.google.protobuf.ByteString getEmailBytes() { + java.lang.Object ref = email_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + email_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PHONE_FIELD_NUMBER = 5; + private java.util.List phone_; + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public java.util.List getPhoneList() { + return phone_; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public java.util.List getPhoneOrBuilderList() { + return phone_; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public int getPhoneCount() { + return phone_.size(); + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getPhone(int index) { + return phone_.get(index); + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumberOrBuilder getPhoneOrBuilder(int index) { + return phone_.get(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) + return true; + if (isInitialized == 0) + return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (id_ != 0) { + output.writeInt32(1, id_); + } + if (!getFirstNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessage.writeString(output, 2, firstName_); + } + if (!getLastNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessage.writeString(output, 3, lastName_); + } + if (!getEmailBytes().isEmpty()) { + com.google.protobuf.GeneratedMessage.writeString(output, 4, email_); + } + for (int i = 0; i < phone_.size(); i++) { + output.writeMessage(5, phone_.get(i)); + } + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) + return size; + + size = 0; + if (id_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, id_); + } + if (!getFirstNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessage.computeStringSize(2, firstName_); + } + if (!getLastNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessage.computeStringSize(3, lastName_); + } + if (!getEmailBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessage.computeStringSize(4, email_); + } + for (int i = 0; i < phone_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, phone_.get(i)); + } + memoizedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(com.baeldung.protobuf.BaeldungTraining.Student prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** + * Protobuf type {@code baeldung.Student} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Student) + com.baeldung.protobuf.BaeldungTraining.StudentOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_fieldAccessorTable.ensureFieldAccessorsInitialized(com.baeldung.protobuf.BaeldungTraining.Student.class, + com.baeldung.protobuf.BaeldungTraining.Student.Builder.class); + } + + // Construct using com.baeldung.protobuf.BaeldungTraining.Student.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getPhoneFieldBuilder(); + } + } + + public Builder clear() { + super.clear(); + id_ = 0; + + firstName_ = ""; + + lastName_ = ""; + + email_ = ""; + + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000010); + } else { + phoneBuilder_.clear(); + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.baeldung.protobuf.BaeldungTraining.internal_static_baeldung_Student_descriptor; + } + + public com.baeldung.protobuf.BaeldungTraining.Student getDefaultInstanceForType() { + return com.baeldung.protobuf.BaeldungTraining.Student.getDefaultInstance(); + } + + public com.baeldung.protobuf.BaeldungTraining.Student build() { + com.baeldung.protobuf.BaeldungTraining.Student result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public com.baeldung.protobuf.BaeldungTraining.Student buildPartial() { + com.baeldung.protobuf.BaeldungTraining.Student result = new com.baeldung.protobuf.BaeldungTraining.Student(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.id_ = id_; + result.firstName_ = firstName_; + result.lastName_ = lastName_; + result.email_ = email_; + if (phoneBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010)) { + phone_ = java.util.Collections.unmodifiableList(phone_); + bitField0_ = (bitField0_ & ~0x00000010); + } + result.phone_ = phone_; + } else { + result.phone_ = phoneBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.baeldung.protobuf.BaeldungTraining.Student) { + return mergeFrom((com.baeldung.protobuf.BaeldungTraining.Student) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.baeldung.protobuf.BaeldungTraining.Student other) { + if (other == com.baeldung.protobuf.BaeldungTraining.Student.getDefaultInstance()) + return this; + if (other.getId() != 0) { + setId(other.getId()); + } + if (!other.getFirstName().isEmpty()) { + firstName_ = other.firstName_; + onChanged(); + } + if (!other.getLastName().isEmpty()) { + lastName_ = other.lastName_; + onChanged(); + } + if (!other.getEmail().isEmpty()) { + email_ = other.email_; + onChanged(); + } + if (phoneBuilder_ == null) { + if (!other.phone_.isEmpty()) { + if (phone_.isEmpty()) { + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000010); + } else { + ensurePhoneIsMutable(); + phone_.addAll(other.phone_); + } + onChanged(); + } + } else { + if (!other.phone_.isEmpty()) { + if (phoneBuilder_.isEmpty()) { + phoneBuilder_.dispose(); + phoneBuilder_ = null; + phone_ = other.phone_; + bitField0_ = (bitField0_ & ~0x00000010); + phoneBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPhoneFieldBuilder() : null; + } else { + phoneBuilder_.addAllMessages(other.phone_); + } + } + } + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + com.baeldung.protobuf.BaeldungTraining.Student parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (com.baeldung.protobuf.BaeldungTraining.Student) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private int id_; + + /** + * optional int32 id = 1; + */ + public int getId() { + return id_; + } + + /** + * optional int32 id = 1; + */ + public Builder setId(int value) { + + id_ = value; + onChanged(); + return this; + } + + /** + * optional int32 id = 1; + */ + public Builder clearId() { + + id_ = 0; + onChanged(); + return this; + } + + private java.lang.Object firstName_ = ""; + + /** + * optional string first_name = 2; + */ + public java.lang.String getFirstName() { + java.lang.Object ref = firstName_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + firstName_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * optional string first_name = 2; + */ + public com.google.protobuf.ByteString getFirstNameBytes() { + java.lang.Object ref = firstName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + firstName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * optional string first_name = 2; + */ + public Builder setFirstName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + firstName_ = value; + onChanged(); + return this; + } + + /** + * optional string first_name = 2; + */ + public Builder clearFirstName() { + + firstName_ = getDefaultInstance().getFirstName(); + onChanged(); + return this; + } + + /** + * optional string first_name = 2; + */ + public Builder setFirstNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + firstName_ = value; + onChanged(); + return this; + } + + private java.lang.Object lastName_ = ""; + + /** + * optional string last_name = 3; + */ + public java.lang.String getLastName() { + java.lang.Object ref = lastName_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + lastName_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * optional string last_name = 3; + */ + public com.google.protobuf.ByteString getLastNameBytes() { + java.lang.Object ref = lastName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + lastName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * optional string last_name = 3; + */ + public Builder setLastName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + lastName_ = value; + onChanged(); + return this; + } + + /** + * optional string last_name = 3; + */ + public Builder clearLastName() { + + lastName_ = getDefaultInstance().getLastName(); + onChanged(); + return this; + } + + /** + * optional string last_name = 3; + */ + public Builder setLastNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + lastName_ = value; + onChanged(); + return this; + } + + private java.lang.Object email_ = ""; + + /** + * optional string email = 4; + */ + public java.lang.String getEmail() { + java.lang.Object ref = email_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + email_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** + * optional string email = 4; + */ + public com.google.protobuf.ByteString getEmailBytes() { + java.lang.Object ref = email_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + email_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * optional string email = 4; + */ + public Builder setEmail(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + email_ = value; + onChanged(); + return this; + } + + /** + * optional string email = 4; + */ + public Builder clearEmail() { + + email_ = getDefaultInstance().getEmail(); + onChanged(); + return this; + } + + /** + * optional string email = 4; + */ + public Builder setEmailBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + email_ = value; + onChanged(); + return this; + } + + private java.util.List phone_ = java.util.Collections.emptyList(); + + private void ensurePhoneIsMutable() { + if (!((bitField0_ & 0x00000010) == 0x00000010)) { + phone_ = new java.util.ArrayList(phone_); + bitField0_ |= 0x00000010; + } + } + + private com.google.protobuf.RepeatedFieldBuilder phoneBuilder_; + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public java.util.List getPhoneList() { + if (phoneBuilder_ == null) { + return java.util.Collections.unmodifiableList(phone_); + } else { + return phoneBuilder_.getMessageList(); + } + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public int getPhoneCount() { + if (phoneBuilder_ == null) { + return phone_.size(); + } else { + return phoneBuilder_.getCount(); + } + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber getPhone(int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); + } else { + return phoneBuilder_.getMessage(index); + } + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder setPhone(int index, com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.set(index, value); + onChanged(); + } else { + phoneBuilder_.setMessage(index, value); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder setPhone(int index, com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.set(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder addPhone(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(value); + onChanged(); + } else { + phoneBuilder_.addMessage(value); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder addPhone(int index, com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber value) { + if (phoneBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensurePhoneIsMutable(); + phone_.add(index, value); + onChanged(); + } else { + phoneBuilder_.addMessage(index, value); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder addPhone(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder addPhone(int index, com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder builderForValue) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.add(index, builderForValue.build()); + onChanged(); + } else { + phoneBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder addAllPhone(java.lang.Iterable values) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, phone_); + onChanged(); + } else { + phoneBuilder_.addAllMessages(values); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder clearPhone() { + if (phoneBuilder_ == null) { + phone_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000010); + onChanged(); + } else { + phoneBuilder_.clear(); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public Builder removePhone(int index) { + if (phoneBuilder_ == null) { + ensurePhoneIsMutable(); + phone_.remove(index); + onChanged(); + } else { + phoneBuilder_.remove(index); + } + return this; + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder getPhoneBuilder(int index) { + return getPhoneFieldBuilder().getBuilder(index); + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumberOrBuilder getPhoneOrBuilder(int index) { + if (phoneBuilder_ == null) { + return phone_.get(index); + } else { + return phoneBuilder_.getMessageOrBuilder(index); + } + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public java.util.List getPhoneOrBuilderList() { + if (phoneBuilder_ != null) { + return phoneBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(phone_); + } + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder addPhoneBuilder() { + return getPhoneFieldBuilder().addBuilder(com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.getDefaultInstance()); + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.Builder addPhoneBuilder(int index) { + return getPhoneFieldBuilder().addBuilder(index, com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber.getDefaultInstance()); + } + + /** + * repeated .baeldung.Student.PhoneNumber phone = 5; + */ + public java.util.List getPhoneBuilderList() { + return getPhoneFieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilder getPhoneFieldBuilder() { + if (phoneBuilder_ == null) { + phoneBuilder_ = new com.google.protobuf.RepeatedFieldBuilder( + phone_, ((bitField0_ & 0x00000010) == 0x00000010), getParentForChildren(), isClean()); + phone_ = null; + } + return phoneBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Student) + } + + // @@protoc_insertion_point(class_scope:baeldung.Student) + private static final com.baeldung.protobuf.BaeldungTraining.Student DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new com.baeldung.protobuf.BaeldungTraining.Student(); + } + + public static com.baeldung.protobuf.BaeldungTraining.Student getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + public Student parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { + return new Student(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.baeldung.protobuf.BaeldungTraining.Student getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Course_descriptor; + private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Course_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Student_descriptor; + private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Student_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Student_PhoneNumber_descriptor; + private static final com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Student_PhoneNumber_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { + java.lang.String[] descriptorData = { "\n\030resources/baeldung.proto\022\010baeldung\"M\n\006" + "Course\022\n\n\002id\030\001 \001(\005\022\023\n\013course_name\030\002 \001(\t\022" + + "\"\n\007student\030\003 \003(\0132\021.baeldung.Student\"\352\001\n\007" + "Student\022\n\n\002id\030\001 \001(\005\022\022\n\nfirst_name\030\002 \001(\t\022" + + "\021\n\tlast_name\030\003 \001(\t\022\r\n\005email\030\004 \001(\t\022,\n\005pho" + "ne\030\005 \003(\0132\035.baeldung.Student.PhoneNumber\032" + "H\n\013PhoneNumber\022\016\n\006number\030\001 \001(\t\022)\n\004type\030\002" + + " \001(\0162\033.baeldung.Student.PhoneType\"%\n\tPho" + "neType\022\n\n\006MOBILE\020\000\022\014\n\010LANDLINE\020\001B)\n\025com." + "baeldung.protobufB\020BaeldungTrainingb\006pro", "to3" }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_baeldung_Course_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_baeldung_Course_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Course_descriptor, new java.lang.String[] { "Id", "CourseName", "Student", }); + internal_static_baeldung_Student_descriptor = getDescriptor().getMessageTypes().get(1); + internal_static_baeldung_Student_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Student_descriptor, new java.lang.String[] { "Id", "FirstName", "LastName", "Email", "Phone", }); + internal_static_baeldung_Student_PhoneNumber_descriptor = internal_static_baeldung_Student_descriptor.getNestedTypes().get(0); + internal_static_baeldung_Student_PhoneNumber_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Student_PhoneNumber_descriptor, new java.lang.String[] { "Number", "Type", }); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseController.java b/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseController.java new file mode 100644 index 0000000000..807b9a9ea4 --- /dev/null +++ b/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseController.java @@ -0,0 +1,20 @@ +package com.baeldung.protobuf; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.protobuf.BaeldungTraining.Course; + +@RestController +public class CourseController { + + @Autowired + CourseRepository courseRepo; + + @RequestMapping("/courses/{id}") + Course customer(@PathVariable Integer id) { + return courseRepo.getCourse(id); + } +} diff --git a/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseRepository.java b/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseRepository.java new file mode 100644 index 0000000000..cbafd7d224 --- /dev/null +++ b/spring-protobuf/src/main/java/com/baeldung/protobuf/CourseRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.protobuf; + +import com.baeldung.protobuf.BaeldungTraining.Course; + +import java.util.Map; + +public class CourseRepository { + + private final Map courses; + + public CourseRepository(Map courses) { + this.courses = courses; + } + + public Course getCourse(int id) { + return courses.get(id); + } +} diff --git a/spring-protobuf/src/main/resources/baeldung.proto b/spring-protobuf/src/main/resources/baeldung.proto new file mode 100644 index 0000000000..20124c34c4 --- /dev/null +++ b/spring-protobuf/src/main/resources/baeldung.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package baeldung; + +option java_package = "com.baeldung.protobuf"; +option java_outer_classname = "BaeldungTraining"; + +message Course { + int32 id = 1; + string course_name = 2; + repeated Student student = 3; +} + +message Student { + int32 id = 1; + string first_name = 2; + string last_name = 3; + string email = 4; + repeated PhoneNumber phone = 5; + + message PhoneNumber { + string number = 1; + PhoneType type = 2; + } + + enum PhoneType { + MOBILE = 0; + LANDLINE = 1; + } +} \ No newline at end of file diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java new file mode 100644 index 0000000000..a17082cea7 --- /dev/null +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.protobuf; + +import com.baeldung.protobuf.BaeldungTraining.Course; +import com.googlecode.protobuf.format.JsonFormat; +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 org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.boot.test.WebIntegrationTest; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.io.InputStream; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = Application.class) +@WebIntegrationTest +public class ApplicationTest { + + private static final String COURSE1_URL = "http://localhost:8080/courses/1"; + + @Autowired + private RestTemplate restTemplate; + + @Test + public void whenUsingRestTemplate_thenSucceed() { + ResponseEntity course = restTemplate.getForEntity(COURSE1_URL, Course.class); + assertResponse(course.toString()); + } + + @Test + public void whenUsingHttpClient_thenSucceed() throws IOException { + InputStream responseStream = executeHttpRequest(COURSE1_URL); + String jsonOutput = convertProtobufMessageStreamToJsonString(responseStream); + assertResponse(jsonOutput); + } + + private InputStream executeHttpRequest(String url) throws IOException { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpGet request = new HttpGet(url); + HttpResponse httpResponse = httpClient.execute(request); + return httpResponse.getEntity().getContent(); + } + + private String convertProtobufMessageStreamToJsonString(InputStream protobufStream) throws IOException { + JsonFormat jsonFormat = new JsonFormat(); + Course course = Course.parseFrom(protobufStream); + return jsonFormat.printToString(course); + } + + private void assertResponse(String response) { + assertThat(response, containsString("id")); + assertThat(response, containsString("course_name")); + assertThat(response, containsString("REST with Spring")); + assertThat(response, containsString("student")); + assertThat(response, containsString("first_name")); + assertThat(response, containsString("last_name")); + assertThat(response, containsString("email")); + assertThat(response, containsString("john.doe@baeldung.com")); + assertThat(response, containsString("richard.roe@baeldung.com")); + assertThat(response, containsString("jane.doe@baeldung.com")); + assertThat(response, containsString("phone")); + assertThat(response, containsString("number")); + assertThat(response, containsString("type")); + } +} \ No newline at end of file diff --git a/spring-rest-docs/README.MD b/spring-rest-docs/README.MD new file mode 100644 index 0000000000..2a87b46021 --- /dev/null +++ b/spring-rest-docs/README.MD @@ -0,0 +1,2 @@ +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring diff --git a/spring-rest/.project b/spring-rest/.project index 894841d690..525c5e7795 100644 --- a/spring-rest/.project +++ b/spring-rest/.project @@ -15,11 +15,6 @@ - - org.eclipse.wst.validation.validationbuilder - - - org.springframework.ide.eclipse.core.springbuilder @@ -38,6 +33,5 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature org.eclipse.wst.common.project.facet.core.nature - org.eclipse.wst.jsdt.core.jsNature diff --git a/spring-rest/.settings/.jsdtscope b/spring-rest/.settings/.jsdtscope index b46b9207a8..7b3f0c8b9f 100644 --- a/spring-rest/.settings/.jsdtscope +++ b/spring-rest/.settings/.jsdtscope @@ -1,12 +1,5 @@ - - - - - - - diff --git a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml b/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml index b9386231e6..8a1c189419 100644 --- a/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/spring-rest/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -1,8 +1,5 @@ - - - - + diff --git a/spring-rest/README.md b/spring-rest/README.md index 9d373962c4..7d993b38b8 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -2,6 +2,8 @@ ## Spring REST Example Project +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring @RequestMapping](http://www.baeldung.com/spring-requestmapping) diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index 767f90a6a6..09a50b9579 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -9,7 +9,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.4.RELEASE + 1.3.5.RELEASE @@ -59,7 +59,6 @@ javax.servlet javax.servlet-api - 3.0.1 provided @@ -101,24 +100,20 @@ org.slf4j slf4j-api - ${org.slf4j.version} ch.qos.logback logback-classic - ${logback.version} org.slf4j jcl-over-slf4j - ${org.slf4j.version} org.slf4j log4j-over-slf4j - ${org.slf4j.version} @@ -126,36 +121,42 @@ junit junit - ${junit.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.springframework spring-test - ${spring.version} + + com.google.protobuf + protobuf-java + 2.6.1 + + + + com.esotericsoftware.kryo + kryo + 2.24.0 + @@ -226,11 +227,10 @@ - 4.0.4.RELEASE 4.3.11.Final - 5.1.38 + 5.1.39 @@ -265,4 +265,4 @@ - \ No newline at end of file + diff --git a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java index 999f890ebb..120f1b272a 100644 --- a/spring-rest/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/WebConfig.java @@ -3,11 +3,13 @@ package org.baeldung.config; import java.text.SimpleDateFormat; import java.util.List; +import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @@ -33,7 +35,8 @@ public class WebConfig extends WebMvcConfigurerAdapter { builder.indentOutput(true).dateFormat(new SimpleDateFormat("dd-MM-yyyy hh:mm")); messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build())); - + messageConverters.add(new ProtobufHttpMessageConverter()); + messageConverters.add(new KryoHttpMessageConverter()); super.configureMessageConverters(messageConverters); } diff --git a/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java b/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java new file mode 100644 index 0000000000..7e63a3ba9e --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/config/converter/KryoHttpMessageConverter.java @@ -0,0 +1,57 @@ +package org.baeldung.config.converter; + +import java.io.IOException; + +import org.baeldung.web.dto.Foo; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.HttpOutputMessage; +import org.springframework.http.MediaType; +import org.springframework.http.converter.AbstractHttpMessageConverter; + +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Input; +import com.esotericsoftware.kryo.io.Output; + +/** + * An {@code HttpMessageConverter} that can read and write Kryo messages. + */ +public class KryoHttpMessageConverter extends AbstractHttpMessageConverter { + + public static final MediaType KRYO = new MediaType("application", "x-kryo"); + + private static final ThreadLocal kryoThreadLocal = new ThreadLocal() { + @Override + protected Kryo initialValue() { + final Kryo kryo = new Kryo(); + kryo.register(Foo.class, 1); + return kryo; + } + }; + + public KryoHttpMessageConverter() { + super(KRYO); + } + + @Override + protected boolean supports(final Class clazz) { + return Object.class.isAssignableFrom(clazz); + } + + @Override + protected Object readInternal(final Class clazz, final HttpInputMessage inputMessage) throws IOException { + final Input input = new Input(inputMessage.getBody()); + return kryoThreadLocal.get().readClassAndObject(input); + } + + @Override + protected void writeInternal(final Object object, final HttpOutputMessage outputMessage) throws IOException { + final Output output = new Output(outputMessage.getBody()); + kryoThreadLocal.get().writeClassAndObject(output, object); + output.flush(); + } + + @Override + protected MediaType getDefaultContentType(final Object object) { + return KRYO; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java index ed6b150403..386c64bb09 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/FooController.java @@ -4,6 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.baeldung.web.dto.Foo; +import org.baeldung.web.dto.FooProtos; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -38,4 +39,9 @@ public class FooController { return foo; } + @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}", produces = { "application/x-protobuf" }) + @ResponseBody + public FooProtos.Foo findProtoById(@PathVariable final long id) { + return FooProtos.Foo.newBuilder().setId(1).setName("Foo Name").build(); + } } diff --git a/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java new file mode 100644 index 0000000000..61251ea33a --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/web/dto/FooProtos.java @@ -0,0 +1,620 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: FooProtos.proto + +package org.baeldung.web.dto; + +public final class FooProtos { + private FooProtos() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public interface FooOrBuilder extends + // @@protoc_insertion_point(interface_extends:baeldung.Foo) + com.google.protobuf.MessageOrBuilder { + + /** + * required int64 id = 1; + */ + boolean hasId(); + /** + * required int64 id = 1; + */ + long getId(); + + /** + * required string name = 2; + */ + boolean hasName(); + /** + * required string name = 2; + */ + java.lang.String getName(); + /** + * required string name = 2; + */ + com.google.protobuf.ByteString + getNameBytes(); + } + /** + * Protobuf type {@code baeldung.Foo} + */ + public static final class Foo extends + com.google.protobuf.GeneratedMessage implements + // @@protoc_insertion_point(message_implements:baeldung.Foo) + FooOrBuilder { + // Use Foo.newBuilder() to construct. + private Foo(com.google.protobuf.GeneratedMessage.Builder builder) { + super(builder); + this.unknownFields = builder.getUnknownFields(); + } + private Foo(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } + + private static final Foo defaultInstance; + public static Foo getDefaultInstance() { + return defaultInstance; + } + + public Foo getDefaultInstanceForType() { + return defaultInstance; + } + + private final com.google.protobuf.UnknownFieldSet unknownFields; + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Foo( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + initFields(); + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + id_ = input.readInt64(); + break; + } + case 18: { + com.google.protobuf.ByteString bs = input.readBytes(); + bitField0_ |= 0x00000002; + name_ = bs; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e.getMessage()).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + public static com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public Foo parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Foo(input, extensionRegistry); + } + }; + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private long id_; + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + + public static final int NAME_FIELD_NUMBER = 2; + private java.lang.Object name_; + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } + } + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString + getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + id_ = 0L; + name_ = ""; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + if (!hasId()) { + memoizedIsInitialized = 0; + return false; + } + if (!hasName()) { + memoizedIsInitialized = 0; + return false; + } + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt64(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getNameBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt64Size(1, id_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getNameBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input); + } + public static org.baeldung.web.dto.FooProtos.Foo parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseDelimitedFrom(input, extensionRegistry); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return PARSER.parseFrom(input); + } + public static org.baeldung.web.dto.FooProtos.Foo parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return PARSER.parseFrom(input, extensionRegistry); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(org.baeldung.web.dto.FooProtos.Foo prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code baeldung.Foo} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder implements + // @@protoc_insertion_point(builder_implements:baeldung.Foo) + org.baeldung.web.dto.FooProtos.FooOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_fieldAccessorTable + .ensureFieldAccessorsInitialized( + org.baeldung.web.dto.FooProtos.Foo.class, org.baeldung.web.dto.FooProtos.Foo.Builder.class); + } + + // Construct using org.baeldung.web.dto.FooProtos.Foo.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + id_ = 0L; + bitField0_ = (bitField0_ & ~0x00000001); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return org.baeldung.web.dto.FooProtos.internal_static_baeldung_Foo_descriptor; + } + + public org.baeldung.web.dto.FooProtos.Foo getDefaultInstanceForType() { + return org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance(); + } + + public org.baeldung.web.dto.FooProtos.Foo build() { + org.baeldung.web.dto.FooProtos.Foo result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public org.baeldung.web.dto.FooProtos.Foo buildPartial() { + org.baeldung.web.dto.FooProtos.Foo result = new org.baeldung.web.dto.FooProtos.Foo(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.name_ = name_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof org.baeldung.web.dto.FooProtos.Foo) { + return mergeFrom((org.baeldung.web.dto.FooProtos.Foo)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(org.baeldung.web.dto.FooProtos.Foo other) { + if (other == org.baeldung.web.dto.FooProtos.Foo.getDefaultInstance()) return this; + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasName()) { + bitField0_ |= 0x00000002; + name_ = other.name_; + onChanged(); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + if (!hasId()) { + + return false; + } + if (!hasName()) { + + return false; + } + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + org.baeldung.web.dto.FooProtos.Foo parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (org.baeldung.web.dto.FooProtos.Foo) e.getUnfinishedMessage(); + throw e; + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private long id_ ; + /** + * required int64 id = 1; + */ + public boolean hasId() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + /** + * required int64 id = 1; + */ + public long getId() { + return id_; + } + /** + * required int64 id = 1; + */ + public Builder setId(long value) { + bitField0_ |= 0x00000001; + id_ = value; + onChanged(); + return this; + } + /** + * required int64 id = 1; + */ + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0L; + onChanged(); + return this; + } + + private java.lang.Object name_ = ""; + /** + * required string name = 2; + */ + public boolean hasName() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + /** + * required string name = 2; + */ + public java.lang.String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (bs.isValidUtf8()) { + name_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + * required string name = 2; + */ + public com.google.protobuf.ByteString + getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + * required string name = 2; + */ + public Builder setName( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + /** + * required string name = 2; + */ + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000002); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + /** + * required string name = 2; + */ + public Builder setNameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + name_ = value; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:baeldung.Foo) + } + + static { + defaultInstance = new Foo(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:baeldung.Foo) + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_baeldung_Foo_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_baeldung_Foo_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024org.baeldung.web" + + ".dtoB\tFooProtos" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + internal_static_baeldung_Foo_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_baeldung_Foo_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_baeldung_Foo_descriptor, + new java.lang.String[] { "Id", "Name", }); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java index c21641ca22..1536f14bc8 100644 --- a/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java +++ b/spring-rest/src/test/java/org/baeldung/web/test/SpringHttpMessageConvertersIntegrationTestsCase.java @@ -7,7 +7,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.baeldung.config.converter.KryoHttpMessageConverter; import org.baeldung.web.dto.Foo; +import org.baeldung.web.dto.FooProtos; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpEntity; @@ -17,6 +19,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.xstream.XStreamMarshaller; import org.springframework.web.client.RestTemplate; @@ -94,6 +97,38 @@ public class SpringHttpMessageConvertersIntegrationTestsCase { Assert.assertEquals(resource.getId(), fooResponse.getId()); } + @Test + public void givenConsumingProtobuf_whenReadingTheFoo_thenCorrect() { + final String URI = BASE_URI + "foos/{id}"; + + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.setMessageConverters(Arrays.asList(new ProtobufHttpMessageConverter())); + final HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Arrays.asList(ProtobufHttpMessageConverter.PROTOBUF)); + final HttpEntity entity = new HttpEntity(headers); + + final ResponseEntity response = restTemplate.exchange(URI, HttpMethod.GET, entity, FooProtos.Foo.class, "1"); + final FooProtos.Foo resource = response.getBody(); + + assertThat(resource, notNullValue()); + } + + @Test + public void givenConsumingKryo_whenReadingTheFoo_thenCorrect() { + final String URI = BASE_URI + "foos/{id}"; + + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.setMessageConverters(Arrays.asList(new KryoHttpMessageConverter())); + final HttpHeaders headers = new HttpHeaders(); + headers.setAccept(Arrays.asList(KryoHttpMessageConverter.KRYO)); + final HttpEntity entity = new HttpEntity(headers); + + final ResponseEntity response = restTemplate.exchange(URI, HttpMethod.GET, entity, Foo.class, "1"); + final Foo resource = response.getBody(); + + assertThat(resource, notNullValue()); + } + // UTIL private List> getMessageConverters() { diff --git a/spring-scurity-custom-permission/README.MD b/spring-scurity-custom-permission/README.MD new file mode 100644 index 0000000000..8fb14fa522 --- /dev/null +++ b/spring-scurity-custom-permission/README.MD @@ -0,0 +1,2 @@ +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity diff --git a/spring-security-basic-auth/README.md b/spring-security-basic-auth/README.md index 95e45ae519..f3c29e1777 100644 --- a/spring-security-basic-auth/README.md +++ b/spring-security-basic-auth/README.md @@ -2,6 +2,8 @@ ## Spring Security with Basic Authentication Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) @@ -9,4 +11,4 @@ ### Notes -- the project includes both views as well as a REST layer \ No newline at end of file +- the project includes both views as well as a REST layer diff --git a/spring-security-client/README.MD b/spring-security-client/README.MD new file mode 100644 index 0000000000..2a87b46021 --- /dev/null +++ b/spring-security-client/README.MD @@ -0,0 +1,2 @@ +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring diff --git a/spring-security-custom-permission/README.MD b/spring-security-custom-permission/README.MD new file mode 100644 index 0000000000..2a87b46021 --- /dev/null +++ b/spring-security-custom-permission/README.MD @@ -0,0 +1,2 @@ +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring diff --git a/spring-security-mvc-custom/README.md b/spring-security-mvc-custom/README.md index 17f32e4a2f..cbf5fc6a97 100644 --- a/spring-security-mvc-custom/README.md +++ b/spring-security-mvc-custom/README.md @@ -2,6 +2,8 @@ ## Spring Security Login Example Project +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Spring Security Remember Me](http://www.baeldung.com/spring-security-remember-me) diff --git a/spring-security-mvc-digest-auth/README.md b/spring-security-mvc-digest-auth/README.md index 3b93a84505..21835266bf 100644 --- a/spring-security-mvc-digest-auth/README.md +++ b/spring-security-mvc-digest-auth/README.md @@ -2,6 +2,8 @@ ## Spring Security with Digest Authentication Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Article: - [Spring Security Digest Authentication](http://www.baeldung.com/spring-security-digest-authentication) diff --git a/spring-security-mvc-ldap/README.md b/spring-security-mvc-ldap/README.md index 686f611f99..1eb3b75405 100644 --- a/spring-security-mvc-ldap/README.md +++ b/spring-security-mvc-ldap/README.md @@ -1,6 +1,8 @@ ## Spring Security with LDAP Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Article: - [Spring Security - security none, filters none, access permitAll](http://www.baeldung.com/security-none-filters-none-access-permitAll) diff --git a/spring-security-mvc-login/README.md b/spring-security-mvc-login/README.md index 256078f4b6..448c25d27b 100644 --- a/spring-security-mvc-login/README.md +++ b/spring-security-mvc-login/README.md @@ -2,11 +2,13 @@ ## Spring Security Login Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [Spring Security Form Login](http://www.baeldung.com/spring-security-login) - [Spring Security Logout](http://www.baeldung.com/spring-security-logout) -- [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) +- [Spring Security Expressions – hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) ### Build the Project diff --git a/spring-security-mvc-persisted-remember-me/README.md b/spring-security-mvc-persisted-remember-me/README.md index df83fd3d77..0d5f4f5f0e 100644 --- a/spring-security-mvc-persisted-remember-me/README.md +++ b/spring-security-mvc-persisted-remember-me/README.md @@ -2,6 +2,8 @@ ## Spring Security Persisted Remember Me Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [Spring Security Persisted Remember Me](http://www.baeldung.com/spring-security-persistent-remember-me) diff --git a/spring-security-mvc-session/README.md b/spring-security-mvc-session/README.md index 0df728688a..28f216c130 100644 --- a/spring-security-mvc-session/README.md +++ b/spring-security-mvc-session/README.md @@ -2,9 +2,11 @@ ## Spring Security Login Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: -- [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) +- [HttpSessionListener Example – Monitoring](http://www.baeldung.com/httpsessionlistener_with_metrics) - [Spring Security Session Management](http://www.baeldung.com/spring-security-session) diff --git a/spring-security-rest-basic-auth/README.md b/spring-security-rest-basic-auth/README.md index 723bcebbdd..9621773d91 100644 --- a/spring-security-rest-basic-auth/README.md +++ b/spring-security-rest-basic-auth/README.md @@ -2,6 +2,8 @@ ## REST API with Basic Authentication - Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [RestTemplate with Basic Authentication in Spring](http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1) diff --git a/spring-security-rest-custom/README.md b/spring-security-rest-custom/README.md index f19af32d41..38dc638e8d 100644 --- a/spring-security-rest-custom/README.md +++ b/spring-security-rest-custom/README.md @@ -2,6 +2,9 @@ ## Spring Security for REST Example Project +###The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + ### Relevant Articles: - [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider) - [Retrieve User Information in Spring Security](http://www.baeldung.com/get-user-in-spring-security) diff --git a/spring-security-rest-digest-auth/README.md b/spring-security-rest-digest-auth/README.md index 06e847edad..4fdc934fe5 100644 --- a/spring-security-rest-digest-auth/README.md +++ b/spring-security-rest-digest-auth/README.md @@ -2,6 +2,8 @@ ## REST API with Digest Authentication - Example Project +###The Course +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [RestTemplate with Digest Authentication](http://www.baeldung.com/resttemplate-digest-authentication) diff --git a/spring-security-rest-full/README.md b/spring-security-rest-full/README.md index 72e8636df1..947d32e87c 100644 --- a/spring-security-rest-full/README.md +++ b/spring-security-rest-full/README.md @@ -2,8 +2,10 @@ ## REST Example Project with Spring Security -### The Course - The "REST With Spring" Classes: http://bit.ly/restwithspring +### Courses +The "REST With Spring" Classes: http://bit.ly/restwithspring + +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [Spring Security Expressions - hasRole Example](http://www.baeldung.com/spring-security-expressions-basic) diff --git a/spring-security-rest/README.md b/spring-security-rest/README.md index 290cd491e0..87f14a9047 100644 --- a/spring-security-rest/README.md +++ b/spring-security-rest/README.md @@ -2,6 +2,10 @@ ## Spring Security for REST Example Project +### Courses +The "REST With Spring" Classes: http://bit.ly/restwithspring + +The "Learn Spring Security" Classes: http://bit.ly/learnspringsecurity ### Relevant Articles: - [Spring REST Service Security](http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/) diff --git a/xml/pom.xml b/xml/pom.xml index fc158901e6..9d88bd75eb 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -1,139 +1,117 @@ - 4.0.0 - com.baeldung - xml - 0.1-SNAPSHOT + 4.0.0 + com.baeldung + xml + 0.1-SNAPSHOT - xml + xml - - + + + + dom4j + dom4j + 1.6.1 + + + jaxen + jaxen + 1.1.6 + - - com.google.guava - guava - ${guava.version} - - - commons-io - commons-io - 2.4 - + + org.jdom + jdom2 + 2.0.6 + - - org.apache.commons - commons-collections4 - 4.0 - + + xerces + xercesImpl + 2.9.1 + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - + + + commons-io + commons-io + 2.4 + - - junit - junit - ${junit.version} - test - + + org.apache.commons + commons-collections4 + 4.0 + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - - org.mockito - mockito-core - ${mockito.version} - test - - + - - xml - - - src/main/resources - true - - + + junit + junit + ${junit.version} + test + - + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + + xml + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + - + + 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} + - - - 4.3.11.Final - 5.1.38 + - - 2.7.2 + - - 1.7.13 - 1.1.3 + - - 5.1.3.Final + + 19.0 + 3.4 - - 19.0 - 3.4 + + 4.12 - - 1.3 - 4.12 - 1.10.19 + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 - 4.4.1 - 4.5 - - 2.9.0 - - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 - - + diff --git a/xml/src/main/java/com/baeldung/xml/DefaultParser.java b/xml/src/main/java/com/baeldung/xml/DefaultParser.java index 89326f45c9..1f2a7418fb 100644 --- a/xml/src/main/java/com/baeldung/xml/DefaultParser.java +++ b/xml/src/main/java/com/baeldung/xml/DefaultParser.java @@ -39,7 +39,7 @@ public class DefaultParser { XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/Tutorials/Tutorial"; + String expression = "/tutorials/tutorial"; nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); @@ -60,7 +60,7 @@ public class DefaultParser { XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "/Tutorials/Tutorial[@tutId=" + "'" + id + "'" + "]"; + String expression = "/tutorials/tutorial[@tutId=" + "'" + id + "'" + "]"; node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE); @@ -83,7 +83,7 @@ public class DefaultParser { XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "//Tutorial[descendant::title[text()=" + "'" + name + "'" + "]]"; + String expression = "//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]"; nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); @@ -107,7 +107,7 @@ public class DefaultParser { XPath xPath = XPathFactory.newInstance().newXPath(); - String expression = "//Tutorial[number(translate(date, '/', '')) > " + date + "]"; + String expression = "//tutorial[number(translate(date, '/', '')) > " + date + "]"; nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); @@ -151,7 +151,7 @@ public class DefaultParser { } }); - String expression = "/bdn:Tutorials/bdn:Tutorial"; + String expression = "/bdn:tutorials/bdn:tutorial"; nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); diff --git a/xml/src/main/java/com/baeldung/xml/Dom4JParser.java b/xml/src/main/java/com/baeldung/xml/Dom4JParser.java new file mode 100644 index 0000000000..d9058ba236 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/Dom4JParser.java @@ -0,0 +1,131 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.Node; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.SAXReader; +import org.dom4j.io.XMLWriter; + +public class Dom4JParser { + + private File file; + + public Dom4JParser(File file) { + this.file = file; + } + + public Element getRootElement() { + try { + SAXReader reader = new SAXReader(); + Document document = reader.read(file); + return document.getRootElement(); + } catch (DocumentException e) { + e.printStackTrace(); + return null; + } + } + + public List getFirstElementList() { + try { + SAXReader reader = new SAXReader(); + Document document = reader.read(file); + return document.getRootElement().elements(); + } catch (DocumentException e) { + e.printStackTrace(); + return null; + } + } + + public Node getNodeById(String id) { + try { + SAXReader reader = new SAXReader(); + Document document = reader.read(file); + List elements = document.selectNodes("//*[@tutId='" + id + "']"); + return elements.get(0); + } catch (DocumentException e) { + e.printStackTrace(); + return null; + } + } + + public Node getElementsListByTitle(String name) { + try { + SAXReader reader = new SAXReader(); + Document document = reader.read(file); + List elements = document + .selectNodes("//tutorial[descendant::title[text()=" + "'" + name + "'" + "]]"); + return elements.get(0); + } catch (DocumentException e) { + e.printStackTrace(); + return null; + } + } + + public void generateModifiedDocument() { + try { + SAXReader reader = new SAXReader(); + Document document = reader.read(file); + List nodes = document.selectNodes("/tutorials/tutorial"); + for (Node node : nodes) { + Element element = (Element) node; + Iterator iterator = element.elementIterator("title"); + while (iterator.hasNext()) { + Element title = (Element) iterator.next(); + title.setText(title.getText() + " updated"); + } + } + XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_updated.xml"))); + writer.write(document); + writer.close(); + } catch (DocumentException e) { + e.printStackTrace(); + + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void generateNewDocument() { + try { + Document document = DocumentHelper.createDocument(); + Element root = document.addElement("XMLTutorials"); + Element tutorialElement = root.addElement("tutorial").addAttribute("tutId", "01"); + tutorialElement.addAttribute("type", "xml"); + + tutorialElement.addElement("title").addText("XML with Dom4J"); + + tutorialElement.addElement("description").addText("XML handling with Dom4J"); + + tutorialElement.addElement("date").addText("14/06/2016"); + + tutorialElement.addElement("author").addText("Dom4J tech writer"); + + OutputFormat format = OutputFormat.createPrettyPrint(); + XMLWriter writer = new XMLWriter(new FileWriter(new File("src/test/resources/example_new.xml")), format); + writer.write(document); + writer.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + +} diff --git a/xml/src/main/java/com/baeldung/xml/JDomParser.java b/xml/src/main/java/com/baeldung/xml/JDomParser.java new file mode 100644 index 0000000000..08676b44f8 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/JDomParser.java @@ -0,0 +1,62 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.jdom2.Document; +import org.jdom2.Element; +import org.jdom2.JDOMException; +import org.jdom2.filter.Filters; +import org.jdom2.input.SAXBuilder; +import org.jdom2.xpath.XPathExpression; +import org.jdom2.xpath.XPathFactory; + + +public class JDomParser { + + private File file; + + public JDomParser(File file) { + this.file = file; + } + + public List getAllTitles() { + try { + SAXBuilder builder = new SAXBuilder(); + Document doc = builder.build(this.getFile()); + Element tutorials = doc.getRootElement(); + List titles = tutorials.getChildren("tutorial"); + return titles; + } catch (JDOMException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return null; + } + } + + public Element getNodeById(String id) { + try { + SAXBuilder builder = new SAXBuilder(); + Document document = (Document) builder.build(file); + String filter = "//*[@tutId='" + id + "']"; + XPathFactory xFactory = XPathFactory.instance(); + XPathExpression expr = xFactory.compile(filter, Filters.element()); + List node = expr.evaluate(document); + + return node.get(0); + } catch (JDOMException | IOException e ) { + e.printStackTrace(); + return null; + } + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + +} diff --git a/xml/src/main/java/com/baeldung/xml/JaxbParser.java b/xml/src/main/java/com/baeldung/xml/JaxbParser.java new file mode 100644 index 0000000000..758ebb969c --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/JaxbParser.java @@ -0,0 +1,68 @@ +package com.baeldung.xml; + +import java.io.File; +import java.util.ArrayList; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import com.baeldung.xml.binding.Tutorial; +import com.baeldung.xml.binding.Tutorials; + +public class JaxbParser { + + private File file; + + public JaxbParser(File file) { + this.file = file; + } + + public Tutorials getFullDocument() { + try { + JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class); + Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + Tutorials tutorials = (Tutorials) jaxbUnmarshaller.unmarshal(this.getFile()); + return tutorials; + } catch (JAXBException e) { + e.printStackTrace(); + return null; + } + } + + public void createNewDocument() { + Tutorials tutorials = new Tutorials(); + tutorials.setTutorial(new ArrayList()); + Tutorial tut = new Tutorial(); + tut.setTutId("01"); + tut.setType("XML"); + tut.setTitle("XML with Jaxb"); + tut.setDescription("XML Binding with Jaxb"); + tut.setDate("04/02/2015"); + tut.setAuthor("Jaxb author"); + tutorials.getTutorial().add(tut); + + try { + JAXBContext jaxbContext = JAXBContext.newInstance(Tutorials.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + + jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + + jaxbMarshaller.marshal(tutorials, file); + + } catch (JAXBException e) { + e.printStackTrace(); + } + + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + +} diff --git a/xml/src/main/java/com/baeldung/xml/JaxenDemo.java b/xml/src/main/java/com/baeldung/xml/JaxenDemo.java new file mode 100644 index 0000000000..0c2dca0573 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/JaxenDemo.java @@ -0,0 +1,57 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.jaxen.JaxenException; +import org.jaxen.XPath; +import org.jaxen.dom.DOMXPath; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +public class JaxenDemo { + + private File file; + + public JaxenDemo(File file) { + this.file = file; + } + + public List getAllTutorial(){ + try { + FileInputStream fileIS = new FileInputStream(this.getFile()); + DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); + + DocumentBuilder builder = builderFactory.newDocumentBuilder(); + + Document xmlDocument = builder.parse(fileIS); + + String expression = "/tutorials/tutorial"; + + XPath path = new DOMXPath(expression); + List result = path.selectNodes(xmlDocument); + return result; + + } catch (SAXException | IOException | ParserConfigurationException | JaxenException e) { + e.printStackTrace(); + return null; + } + + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + +} diff --git a/xml/src/main/java/com/baeldung/xml/StaxParser.java b/xml/src/main/java/com/baeldung/xml/StaxParser.java new file mode 100644 index 0000000000..e14d872831 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/StaxParser.java @@ -0,0 +1,120 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.EndElement; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; + +import com.baeldung.xml.binding.Tutorial; + +public class StaxParser { + + private File file; + + public StaxParser(File file) { + this.file = file; + } + + public List getAllTutorial() { + boolean bTitle = false; + boolean bDescription = false; + boolean bDate = false; + boolean bAuthor = false; + List tutorials = new ArrayList(); + try { + XMLInputFactory factory = XMLInputFactory.newInstance(); + XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(this.getFile())); + Tutorial current = null; + while (eventReader.hasNext()) { + XMLEvent event = eventReader.nextEvent(); + switch (event.getEventType()) { + case XMLStreamConstants.START_ELEMENT: + StartElement startElement = event.asStartElement(); + String qName = startElement.getName().getLocalPart(); + if (qName.equalsIgnoreCase("tutorial")) { + current = new Tutorial(); + Iterator attributes = startElement.getAttributes(); + while (attributes.hasNext()) { + Attribute currentAt = attributes.next(); + if (currentAt.getName().toString().equalsIgnoreCase("tutId")) { + current.setTutId(currentAt.getValue()); + } else if (currentAt.getName().toString().equalsIgnoreCase("type")) { + current.setType(currentAt.getValue()); + } + } + } else if (qName.equalsIgnoreCase("title")) { + bTitle = true; + } else if (qName.equalsIgnoreCase("description")) { + bDescription = true; + } else if (qName.equalsIgnoreCase("date")) { + bDate = true; + } else if (qName.equalsIgnoreCase("author")) { + bAuthor = true; + } + break; + case XMLStreamConstants.CHARACTERS: + Characters characters = event.asCharacters(); + if (bTitle) { + if (current != null) { + current.setTitle(characters.getData()); + } + bTitle = false; + } + if (bDescription) { + if (current != null) { + current.setDescription(characters.getData()); + } + bDescription = false; + } + if (bDate) { + if (current != null) { + current.setDate(characters.getData()); + } + bDate = false; + } + if (bAuthor) { + if (current != null) { + current.setAuthor(characters.getData()); + } + bAuthor = false; + } + break; + case XMLStreamConstants.END_ELEMENT: + EndElement endElement = event.asEndElement(); + if (endElement.getName().getLocalPart().equalsIgnoreCase("tutorial")) { + if(current != null){ + tutorials.add(current); + } + } + break; + } + } + + } catch (FileNotFoundException | XMLStreamException e) { + e.printStackTrace(); + } + + return tutorials; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + +} diff --git a/xml/src/main/java/com/baeldung/xml/binding/Tutorial.java b/xml/src/main/java/com/baeldung/xml/binding/Tutorial.java new file mode 100644 index 0000000000..7201d499d0 --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/binding/Tutorial.java @@ -0,0 +1,59 @@ +package com.baeldung.xml.binding; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; + +public class Tutorial { + + private String tutId; + private String type; + private String title; + private String description; + private String date; + private String author; + + + public String getTutId() { + return tutId; + } + + @XmlAttribute + public void setTutId(String tutId) { + this.tutId = tutId; + } + public String getType() { + return type; + } + @XmlAttribute + public void setType(String type) { + this.type = type; + } + public String getTitle() { + return title; + } + @XmlElement + public void setTitle(String title) { + this.title = title; + } + public String getDescription() { + return description; + } + @XmlElement + public void setDescription(String description) { + this.description = description; + } + public String getDate() { + return date; + } + @XmlElement + public void setDate(String date) { + this.date = date; + } + public String getAuthor() { + return author; + } + @XmlElement + public void setAuthor(String author) { + this.author = author; + } +} diff --git a/xml/src/main/java/com/baeldung/xml/binding/Tutorials.java b/xml/src/main/java/com/baeldung/xml/binding/Tutorials.java new file mode 100644 index 0000000000..ab6669c0ad --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/binding/Tutorials.java @@ -0,0 +1,23 @@ +package com.baeldung.xml.binding; + +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Tutorials { + + private List tutorial; + + public List getTutorial() { + return tutorial; + } + + @XmlElement + public void setTutorial(List tutorial) { + this.tutorial = tutorial; + } + + +} diff --git a/xml/src/test/java/com/baeldung/xml/DefaultParserTest.java b/xml/src/test/java/com/baeldung/xml/DefaultParserTest.java index 451917a5da..734e7a93cb 100644 --- a/xml/src/test/java/com/baeldung/xml/DefaultParserTest.java +++ b/xml/src/test/java/com/baeldung/xml/DefaultParserTest.java @@ -8,9 +8,6 @@ import org.junit.Test; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -/** - * Unit test for simple App. - */ public class DefaultParserTest { final String fileName = "src/test/resources/example.xml"; @@ -29,7 +26,7 @@ public class DefaultParserTest { } @Test - public void getNodeListByTitle() { + public void getNodeListByTitleTest() { parser = new DefaultParser(new File(fileName)); NodeList list = parser.getNodeListByTitle("XML"); @@ -47,7 +44,7 @@ public class DefaultParserTest { } @Test - public void getNodeById() { + public void getNodeByIdTest() { parser = new DefaultParser(new File(fileName)); Node node = parser.getNodeById("03"); @@ -56,7 +53,7 @@ public class DefaultParserTest { } @Test - public void getNodeListByDate(){ + public void getNodeListByDateTest(){ parser = new DefaultParser(new File(fileName)); NodeList list = parser.getNodeListByTitle("04022016"); for (int i = 0; null != list && i < list.getLength(); i++) { @@ -73,7 +70,7 @@ public class DefaultParserTest { } @Test - public void getNodeListWithNamespace(){ + public void getNodeListWithNamespaceTest(){ parser = new DefaultParser(new File(fileNameSpace)); NodeList list = parser.getAllTutorials(); assertNotNull(list); diff --git a/xml/src/test/java/com/baeldung/xml/Dom4JParserTest.java b/xml/src/test/java/com/baeldung/xml/Dom4JParserTest.java new file mode 100644 index 0000000000..277eca8355 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/Dom4JParserTest.java @@ -0,0 +1,88 @@ +package com.baeldung.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.List; + +import org.dom4j.Element; +import org.dom4j.Node; +import org.junit.Test; + +public class Dom4JParserTest { + + final String fileName = "src/test/resources/example.xml"; + + Dom4JParser parser; + + @Test + public void getRootElementTest() { + parser = new Dom4JParser(new File(fileName)); + Element root = parser.getRootElement(); + + assertNotNull(root); + assertTrue(root.elements().size() == 4); + } + + @Test + public void getFirstElementListTest() { + parser = new Dom4JParser(new File(fileName)); + List firstList = parser.getFirstElementList(); + + assertNotNull(firstList); + assertTrue(firstList.size() == 4); + assertTrue(firstList.get(0).attributeValue("type").equals("java")); + } + + @Test + public void getElementByIdTest() { + parser = new Dom4JParser(new File(fileName)); + Node element = parser.getNodeById("03"); + + String type = element.valueOf("@type"); + assertEquals("android", type); + } + + @Test + public void getElementsListByTitleTest() { + parser = new Dom4JParser(new File(fileName)); + Node element = parser.getElementsListByTitle("XML"); + + assertEquals("java", element.valueOf("@type")); + assertEquals("02", element.valueOf("@tutId")); + assertEquals("XML", element.selectSingleNode("title").getText()); + assertEquals("title", element.selectSingleNode("title").getName()); + } + + @Test + public void generateModifiedDocumentTest() { + parser = new Dom4JParser(new File(fileName)); + parser.generateModifiedDocument(); + + File generatedFile = new File("src/test/resources/example_updated.xml"); + assertTrue(generatedFile.exists()); + + parser.setFile(generatedFile); + Node element = parser.getNodeById("02"); + + assertEquals("XML updated", element.selectSingleNode("title").getText()); + + } + + @Test + public void generateNewDocumentTest() { + parser = new Dom4JParser(new File(fileName)); + parser.generateNewDocument(); + + File newFile = new File("src/test/resources/example_new.xml"); + assertTrue(newFile.exists()); + + parser.setFile(newFile); + Node element = parser.getNodeById("01"); + + assertEquals("XML with Dom4J", element.selectSingleNode("title").getText()); + + } +} diff --git a/xml/src/test/java/com/baeldung/xml/JDomParserTest.java b/xml/src/test/java/com/baeldung/xml/JDomParserTest.java new file mode 100644 index 0000000000..981458469f --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/JDomParserTest.java @@ -0,0 +1,38 @@ +package com.baeldung.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.List; + +import org.jdom2.Element; +import org.junit.Test; + +public class JDomParserTest { + + final String fileName = "src/test/resources/example.xml"; + + JDomParser parser; + + @Test + public void getFirstElementListTest() { + parser = new JDomParser(new File(fileName)); + List firstList = parser.getAllTitles(); + + assertNotNull(firstList); + assertTrue(firstList.size() == 4); + assertTrue(firstList.get(0).getAttributeValue("type").equals("java")); + } + + @Test + public void getElementByIdTest() { + parser = new JDomParser(new File(fileName)); + Element el = parser.getNodeById("03"); + + String type = el.getAttributeValue("type"); + assertEquals("android", type); + } + +} diff --git a/xml/src/test/java/com/baeldung/xml/JaxbParserTest.java b/xml/src/test/java/com/baeldung/xml/JaxbParserTest.java new file mode 100644 index 0000000000..6c31a7bfdd --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/JaxbParserTest.java @@ -0,0 +1,44 @@ +package com.baeldung.xml; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Test; + +import com.baeldung.xml.binding.Tutorials; + +public class JaxbParserTest { + + + final String fileName = "src/test/resources/example.xml"; + + JaxbParser parser; + + @Test + public void getFullDocumentTest(){ + parser = new JaxbParser(new File(fileName)); + Tutorials tutorials = parser.getFullDocument(); + + assertNotNull(tutorials); + assertTrue(tutorials.getTutorial().size() == 4); + assertTrue(tutorials.getTutorial().get(0).getType().equalsIgnoreCase("java")); + } + + @Test + public void createNewDocumentTest(){ + File newFile = new File("src/test/resources/example_new.xml"); + parser = new JaxbParser(newFile); + parser.createNewDocument(); + + + assertTrue(newFile.exists()); + + Tutorials tutorials = parser.getFullDocument(); + + assertNotNull(tutorials); + assertTrue(tutorials.getTutorial().size() == 1); + assertTrue(tutorials.getTutorial().get(0).getTitle().equalsIgnoreCase("XML with Jaxb")); + } +} diff --git a/xml/src/test/java/com/baeldung/xml/JaxenDemoTest.java b/xml/src/test/java/com/baeldung/xml/JaxenDemoTest.java new file mode 100644 index 0000000000..2521fcaf8a --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/JaxenDemoTest.java @@ -0,0 +1,25 @@ +package com.baeldung.xml; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.List; + +import org.junit.Test; + +public class JaxenDemoTest { + + final String fileName = "src/test/resources/example.xml"; + + JaxenDemo jaxenDemo; + + @Test + public void getFirstLevelNodeListTest() { + jaxenDemo = new JaxenDemo(new File(fileName)); + List list = jaxenDemo.getAllTutorial(); + + assertNotNull(list); + assertTrue(list.size() == 4); + } +} diff --git a/xml/src/test/java/com/baeldung/xml/StaxParserTest.java b/xml/src/test/java/com/baeldung/xml/StaxParserTest.java new file mode 100644 index 0000000000..cf7ee1ee75 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/StaxParserTest.java @@ -0,0 +1,28 @@ +package com.baeldung.xml; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.xml.binding.Tutorial; + +public class StaxParserTest { + + final String fileName = "src/test/resources/example.xml"; + + StaxParser parser; + + @Test + public void getAllTutorialsTest(){ + parser = new StaxParser(new File(fileName)); + List tutorials = parser.getAllTutorial(); + + assertNotNull(tutorials); + assertTrue(tutorials.size() == 4); + assertTrue(tutorials.get(0).getType().equalsIgnoreCase("java")); + } +} diff --git a/xml/src/test/resources/example.xml b/xml/src/test/resources/example.xml index d546dd137b..0993b6240a 100644 --- a/xml/src/test/resources/example.xml +++ b/xml/src/test/resources/example.xml @@ -1,24 +1,24 @@ - - + + Guava Introduction to Guava 04/04/2016 GuavaAuthor - - + + XML Introduction to XPath 04/05/2016 XMLAuthor - - + + Android Introduction to Android 04/03/2016 AndroidAuthor - - + + Spring Introduction to Spring 04/02/2016 @@ -28,5 +28,5 @@
Spring MVC
Spring Batch
-
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/xml/src/test/resources/example_namespace.xml b/xml/src/test/resources/example_namespace.xml index 26131302ea..f1a880951a 100644 --- a/xml/src/test/resources/example_namespace.xml +++ b/xml/src/test/resources/example_namespace.xml @@ -1,24 +1,24 @@ - - + + Guava Introduction to Guava 04/04/2016 GuavaAuthor - - + + XML Introduction to XPath 04/05/2016 XMLAuthor - - + + Android Introduction to Android 04/03/2016 AndroidAuthor - - + + Spring Introduction to Spring 04/02/2016 @@ -28,5 +28,5 @@
Spring MVC
Spring Batch
-
-
\ No newline at end of file +
+
\ No newline at end of file diff --git a/xml/src/test/resources/example_new.xml b/xml/src/test/resources/example_new.xml new file mode 100644 index 0000000000..020760fdd3 --- /dev/null +++ b/xml/src/test/resources/example_new.xml @@ -0,0 +1,10 @@ + + + + + XML with Dom4J + XML handling with Dom4J + 14/06/2016 + Dom4J tech writer + + diff --git a/xml/src/test/resources/example_updated.xml b/xml/src/test/resources/example_updated.xml new file mode 100644 index 0000000000..962ca0c889 --- /dev/null +++ b/xml/src/test/resources/example_updated.xml @@ -0,0 +1,32 @@ + + + + Guava updated + Introduction to Guava + 04/04/2016 + GuavaAuthor + + + XML updated + Introduction to XPath + 04/05/2016 + XMLAuthor + + + Android updated + Introduction to Android + 04/03/2016 + AndroidAuthor + + + Spring updated + Introduction to Spring + 04/02/2016 + SpringAuthor + +
Spring Core
+
Spring MVC
+
Spring Batch
+
+
+
\ No newline at end of file