Merge remote-tracking branch 'origin/master'

This commit is contained in:
slavisa-baeldung 2016-07-09 08:11:05 +02:00
commit ce4bbd03e4
204 changed files with 8529 additions and 854 deletions

View File

@ -1,7 +1,7 @@
The "REST with Spring" Classes
==============================
After 5 months of work, here's the Master Class: <br/>
After 5 months of work, here's the Master Class of REST With Spring: <br/>
**[>> 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/)**

49
assertj/pom.xml Normal file
View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>assertj</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<String> list = Arrays.asList("1", "2", "3");
assertThat(list)
.contains("1");
}
@Test
public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
List<String> 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<Integer, String> 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);
}
}

View File

@ -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<Integer, String> 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<String> something = Optional.of("something");
assertThat(something)
.isPresent()
.extractingValue()
.isEqualTo("something");
}
@Test
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
final Range<String> range = Range.openClosed("a", "g");
assertThat(range)
.hasOpenedLowerBound()
.isNotEmpty()
.hasClosedUpperBound()
.contains("b");
}
@Test
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
final TreeRangeMap<Integer, String> 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<Integer, String, String> 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");
}
}

View File

@ -63,6 +63,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -27,7 +27,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>

View File

@ -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

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.7"/>
<installed facet="java" version="1.8"/>
</faceted-project>

View File

@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
@Test
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
final List<Integer> sourceList = Lists.<Integer> newArrayList(0, 1, 2, 3, 4, 5);
final List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
}

View File

@ -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')
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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==</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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=</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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=</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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=</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36" version="5.5.1.6" editor="www.draw.io" type="device"><diagram>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=</diagram></mxfile>

View File

@ -1,81 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>dependency-injection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<groupId>com.baeldung</groupId>
<artifactId>dependency-injection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>@Resource vs @Inject vs @Autowired</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely @Resource, @Inject, and @Autowired</description>
<name>Resource vs Inject vs Autowired</name>
<description>Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
Resource, Inject, and Autowired
</description>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Demo.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
</repositories>
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
</repositories>
</project>

View File

@ -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 {
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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";

View File

@ -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";

View File

@ -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";

View File

@ -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());
}
}
}

View File

@ -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());
}

View File

@ -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());
}

View File

@ -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());
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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);
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="anotherAutowiredFieldDependency" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,10 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="autowiredFieldDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -1,11 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="yetAnotherFieldInjectDependency" class="com.baeldung.dependency.YetAnotherArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="defaultFile" class="com.baeldung.dependency.ArbitraryDependency"/>
<bean id="namedFile" class="com.baeldung.dependency.AnotherArbitraryDependency"/>
</beans>

View File

@ -1,10 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="injectDependency" class="com.baeldung.dependency.ArbitraryDependency"/>
</beans>

View File

@ -1,12 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

View File

@ -1,16 +0,0 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="defaultFile" class="java.io.File">
<constructor-arg value="defaultFile.txt"/>
</bean>
<bean id="namedFile" class="java.io.File">
<constructor-arg value="namedFile.txt"/>
</bean>
</beans>

View File

@ -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;
}
}

View File

@ -0,0 +1,13 @@
package org.baeldung.hamcrest;
public class Cat extends Animal {
public Cat() {
super("cat", false, "meow");
}
public String makeSound() {
return getSound();
}
}

View File

@ -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<String> 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<String> hamcrestMatchers = Arrays.asList("collections", "beans",
"text", "number");
assertThat(hamcrestMatchers,
containsInAnyOrder("beans", "text", "collections", "number"));
}
@Test
public void givenAListAndValues_whenChecksListForGivenValuesWithOrder_thenCorrect() {
List<String> 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<String> 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<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasKey("blogname"));
}
@Test
public void givenMapAndEntry_whenEntryFoundInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("blogname", "baeldung");
assertThat(map, hasEntry("blogname", "baeldung"));
}
@Test
public void givenMapAndValue_whenValueFoundInMap_thenCorrect() {
Map<String, String> 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<Integer> 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));
}
}

View File

@ -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<Integer> {
public void describeTo(Description description) {
description.appendText("a positive integer");
}
@Factory
public static Matcher<Integer> isAPositiveInteger() {
return new IsPositiveInteger();
}
@Override
protected boolean matchesSafely(Integer integer) {
return integer > 0;
}
}

View File

@ -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;
}
}

View File

@ -1,7 +1,9 @@
=========
## HttpClient 4.x Cookbooks and Examples
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:

View File

@ -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();

View File

@ -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)

View File

@ -5,22 +5,13 @@
<artifactId>jooq-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<org.jooq.version>3.7.3</org.jooq.version>
<com.h2database.version>1.4.191</com.h2database.version>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.slf4j.version>1.7.18</org.slf4j.version>
<ch.qos.logback.version>1.1.3</ch.qos.logback.version>
<junit.version>4.12</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.3.RELEASE</version>
<version>1.3.5.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -46,30 +37,25 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jooq</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback.version}</version>
<scope>runtime</scope>
</dependency>
@ -77,15 +63,13 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</dependency>
</dependencies>
<build>
@ -166,6 +150,29 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.jooq.version>3.7.3</org.jooq.version>
<com.h2database.version>1.4.191</com.h2database.version>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.slf4j.version>1.7.18</org.slf4j.version>
<ch.qos.logback.version>1.1.3</ch.qos.logback.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -25,6 +25,12 @@
<artifactId>jsf-impl</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>${javax.el.version}</version>
</dependency>
<!-- Spring -->
@ -114,6 +120,7 @@
<!-- JSF -->
<com.sun.faces.version>2.1.7</com.sun.faces.version>
<javax.el.version>2.2</javax.el.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>

View File

@ -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;
}
}

View File

@ -0,0 +1,38 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Baeldung | The EL Intro</title>
</h:head>
<h:body>
<h:form id="elForm">
<h:messages />
<h:panelGrid columns="2">
<h:outputText value="First Name"/>
<h:inputText id="firstName" binding="#{firstName}" required="true" value="#{ELBean.firstName}"/>
<h:outputText value="Last Name"/>
<h:inputText id="lastName" required="true" value="#{ELBean.lastName}"/>
<h:outputText value="Save by value binding"/>
<h:commandButton value="Save" action="#{ELBean.save}">
</h:commandButton>
<h:outputText value="Evaluate backing bean EL"/>
<h:commandButton value="Save" action="#{ELBean.saveByELEvaluation}">
</h:commandButton>
<h:outputText value="Save by passing value to method"/>
<h:commandButton value="Save" action="#{ELBean.saveFirstName(firstName.value.toString().concat('(passed)'))}"/>
<h:outputText value="JavaScript (click after saving First Name)"/>
<h:button value="Alert" onclick="alert('Hello #{ELBean.firstName}')"/>
</h:panelGrid>
</h:form>
</h:body>
</html>

25
json/pom.xml Normal file
View File

@ -0,0 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>json</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -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);
}
}

View File

@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 0
}

View File

@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 10
}

View File

@ -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"]
}

66
log4j/pom.xml Normal file
View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>log4j</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--log4j dependencies-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--log4j2 dependencies-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<!--disruptor for log4j2 async logging-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
<!--logback dependencies-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<debug>true</debug>
<optimize>true</optimize>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,32 @@
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<!--Console appender-->
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</layout>
</appender>
<!-- File appender-->
<appender name="fout" class="org.apache.log4j.FileAppender">
<param name="file" value="log4j/target/baeldung-log4j.log"/>
<param name="append" value="false"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n"/>
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</layout>
</appender>
<!--Override log level for specified package-->
<category name="com.baeldung.log4j">
<priority value="TRACE"/>
</category>
<root>
<level value="DEBUG"/>
<appender-ref ref="stdout"/>
<appender-ref ref="fout"/>
</root>
</log4j:configuration>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
# Console appender
<Console name="stdout" target="SYSTEM_OUT">
# Pattern of log message for console appender
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</Console>
# File appender
<File name="fout" fileName="log4j/target/baeldung-log4j2.log" immediateFlush="false" append="false">
# Pattern of log message for file appender
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %p %m%n"/>
</File>
</Appenders>
<Loggers>
# Override log level for specified package
<Logger name="com.baeldung.log4j2" level="TRACE"/>
<AsyncRoot level="DEBUG">
<AppenderRef ref="stdout"/>
<AppenderRef ref="fout"/>
</AsyncRoot>
</Loggers>
</Configuration>

View File

@ -0,0 +1,28 @@
<configuration>
# Console appender
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
# Pattern of log message for console appender
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
</layout>
</appender>
# File appender
<appender name="fout" class="ch.qos.logback.core.FileAppender">
# Name of a log file
<file>log4j/target/baeldung-logback.log</file>
<append>false</append>
<encoder>
# Pattern of log message for file appender
<pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
</encoder>
</appender>
# Override log level for specified package
<logger name="com.baeldung.logback" level="TRACE"/>
<root level="DEBUG">
<appender-ref ref="stdout"/>
<appender-ref ref="fout"/>
</root>
</configuration>

7
mocks/jmockit/README.md Normal file
View File

@ -0,0 +1,7 @@
=========
## JMockit related tutorials
### Relevant Articles:
- [JMockit 101](http://www.baeldung.com/jmockit-101)

68
mocks/jmockit/pom.xml Normal file
View File

@ -0,0 +1,68 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>jmockit</artifactId>
<name>jmockit</name>
<properties>
<junit.version>4.12</junit.version>
<jmockit.version>1.24</jmockit.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jmockit</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -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
}
}

View File

@ -0,0 +1,7 @@
package org.baeldung.mocks.jmockit;
public class Model {
public String getInfo(){
return "info";
}
}

View File

@ -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);
}
}

View File

@ -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);
}};
}
}

View File

@ -0,0 +1,7 @@
=========
## Mock comparison realated tutorials
### Relevant Articles:
- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit)

View File

@ -0,0 +1,91 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>mock-comparisons</artifactId>
<name>mock-comparisons</name>
<properties>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<easymock.version>3.4</easymock.version>
<jmockit.version>1.24</jmockit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mock-comparisons</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -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
}

Some files were not shown because too many files have changed in this diff Show More