Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
428f3403ea
|
@ -27,3 +27,4 @@ target/
|
||||||
|
|
||||||
spring-openid/src/main/resources/application.properties
|
spring-openid/src/main/resources/application.properties
|
||||||
.recommenders/
|
.recommenders/
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
|
|
||||||
The "REST with Spring" Classes
|
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)**
|
**[>> 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:
|
- import the included **formatter** in Eclipse:
|
||||||
`https://github.com/eugenp/tutorials/tree/master/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/)**
|
||||||
|
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?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>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>3.4.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</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>
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.date_migration;
|
||||||
|
|
||||||
|
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 Conversion {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.date_migration;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.time.*;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
|
public class NewApi {
|
||||||
|
public void currentTime() {
|
||||||
|
ZonedDateTime now = ZonedDateTime.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void specificTime() {
|
||||||
|
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractMonth() {
|
||||||
|
Month month = LocalDateTime.now().getMonth();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void subtractTime() {
|
||||||
|
LocalDateTime fiveHoursBefore = LocalDateTime.now().minusHours(5);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void alterField() {
|
||||||
|
LocalDateTime inJune = LocalDateTime.now().withMonth(Month.JUNE.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void truncate() {
|
||||||
|
LocalTime truncated = LocalTime.now().truncatedTo(ChronoUnit.HOURS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void convertTimeZone() {
|
||||||
|
ZonedDateTime centralEastern = LocalDateTime.now().atZone(ZoneId.of("CET"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void getTimeSpan() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
LocalDateTime hourLater = LocalDateTime.now().plusHours(1);
|
||||||
|
Duration span = Duration.between(now, hourLater);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void formatAndParse() throws ParseException {
|
||||||
|
LocalDate now = LocalDate.now();
|
||||||
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
String formattedDate = now.format(formatter);
|
||||||
|
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void daysInMonth() {
|
||||||
|
int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,68 @@
|
||||||
|
package com.baeldung.date_migration;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
public class OldApi {
|
||||||
|
public void currentTime() {
|
||||||
|
Date now = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void specificTime () {
|
||||||
|
Date birthDay = new GregorianCalendar(1990, Calendar.DECEMBER, 15).getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void extractMonth() {
|
||||||
|
int month = new GregorianCalendar().get(Calendar.MONTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void subtractTime() {
|
||||||
|
GregorianCalendar calendar = new GregorianCalendar();
|
||||||
|
calendar.add(Calendar.HOUR_OF_DAY, -5);
|
||||||
|
Date fiveHoursBefore = calendar.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void alterField() {
|
||||||
|
GregorianCalendar calendar = new GregorianCalendar();
|
||||||
|
calendar.set(Calendar.MONTH, Calendar.JUNE);
|
||||||
|
Date inJune = calendar.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void truncate() {
|
||||||
|
Calendar now = Calendar.getInstance();
|
||||||
|
now.set(Calendar.MINUTE, 0);
|
||||||
|
now.set(Calendar.SECOND, 0);
|
||||||
|
now.set(Calendar.MILLISECOND, 0);
|
||||||
|
Date truncated = now.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void convertTimeZone() {
|
||||||
|
GregorianCalendar calendar = new GregorianCalendar();
|
||||||
|
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||||
|
Date centralEastern = calendar.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void getTimeSpan() {
|
||||||
|
GregorianCalendar calendar = new GregorianCalendar();
|
||||||
|
Date now = new Date();
|
||||||
|
calendar.add(Calendar.HOUR, 1);
|
||||||
|
Date hourLater = calendar.getTime();
|
||||||
|
long elapsed = hourLater.getTime() - now.getTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void formatAndParse() throws ParseException {
|
||||||
|
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
Date now = new Date();
|
||||||
|
String formattedDate = dateFormat.format(now);
|
||||||
|
Date parsedDate = dateFormat.parse(formattedDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void daysInMonth() {
|
||||||
|
Calendar calendar = new GregorianCalendar(1990, Calendar.FEBRUARY, 20);
|
||||||
|
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
|
||||||
|
}
|
||||||
|
}
|
|
@ -27,7 +27,7 @@
|
||||||
<attribute name="maven.pomderived" value="true"/>
|
<attribute name="maven.pomderived" value="true"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
</classpathentry>
|
</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>
|
<attributes>
|
||||||
<attribute name="owner.project.facets" value="java"/>
|
<attribute name="owner.project.facets" value="java"/>
|
||||||
</attributes>
|
</attributes>
|
||||||
|
|
|
@ -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.nullable=org.eclipse.jdt.annotation.Nullable
|
||||||
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
|
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
|
||||||
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
|
||||||
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
|
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
|
||||||
org.eclipse.jdt.core.compiler.compliance=1.7
|
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.annotationSuperInterface=warning
|
||||||
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
|
||||||
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
|
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.unusedTypeParameter=ignore
|
||||||
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
|
||||||
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=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
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<faceted-project>
|
<faceted-project>
|
||||||
<installed facet="java" version="1.7"/>
|
<installed facet="java" version="1.8"/>
|
||||||
</faceted-project>
|
</faceted-project>
|
||||||
|
|
|
@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
|
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()]);
|
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,101 @@
|
||||||
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.AbstractSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.WeakHashMap;
|
||||||
|
|
||||||
|
import com.google.common.base.Function;
|
||||||
|
|
||||||
|
public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
|
||||||
|
|
||||||
|
private class SingleEntry implements Entry<K, V> {
|
||||||
|
private K key;
|
||||||
|
|
||||||
|
public SingleEntry( K key) {
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public K getKey() {
|
||||||
|
return this.key;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public V getValue() {
|
||||||
|
V value = GuavaMapFromSet.this.cache.get(this.key);
|
||||||
|
if (value == null) {
|
||||||
|
value = GuavaMapFromSet.this.function.apply(this.key);
|
||||||
|
GuavaMapFromSet.this.cache.put(this.key, value);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public V setValue( V value) {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MyEntrySet extends AbstractSet<Entry<K, V>> {
|
||||||
|
|
||||||
|
public class EntryIterator implements Iterator<Entry<K, V>> {
|
||||||
|
private Iterator<K> inner;
|
||||||
|
|
||||||
|
public EntryIterator() {
|
||||||
|
this.inner = MyEntrySet.this.keys.iterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean hasNext() {
|
||||||
|
return this.inner.hasNext();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map.Entry<K, V> next() {
|
||||||
|
K key = this.inner.next();
|
||||||
|
return new SingleEntry(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void remove() {
|
||||||
|
throw new UnsupportedOperationException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<K> keys;
|
||||||
|
|
||||||
|
public MyEntrySet( Set<K> keys) {
|
||||||
|
this.keys = keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Iterator<Map.Entry<K, V>> iterator() {
|
||||||
|
return new EntryIterator();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int size() {
|
||||||
|
return this.keys.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private WeakHashMap<K, V> cache;
|
||||||
|
private Set<Entry<K, V>> entries;
|
||||||
|
private Function<? super K, ? extends V> function;
|
||||||
|
|
||||||
|
public GuavaMapFromSet( Set<K> keys, Function<? super K, ? extends V> function) {
|
||||||
|
this.function = function;
|
||||||
|
this.cache = new WeakHashMap<K, V>();
|
||||||
|
this.entries = new MyEntrySet(keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<Map.Entry<K, V>> entrySet() {
|
||||||
|
return this.entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,66 @@
|
||||||
|
package org.baeldung.guava;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.google.common.base.Function;
|
||||||
|
|
||||||
|
public class GuavaMapFromSetTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
|
||||||
|
Function<Integer, String> function = new Function<Integer, String>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String apply(Integer from) {
|
||||||
|
return Integer.toBinaryString(from.intValue());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Set<Integer> set = (Set<Integer>) new TreeSet<Integer>(Arrays.asList(
|
||||||
|
32, 64, 128));
|
||||||
|
Map<Integer, String> map = new GuavaMapFromSet<Integer, String>(set,
|
||||||
|
function);
|
||||||
|
assertTrue(map.get(32).equals("100000")
|
||||||
|
&& map.get(64).equals("1000000")
|
||||||
|
&& map.get(128).equals("10000000"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
|
||||||
|
Function<String, Integer> function = new Function<String, Integer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer apply(String from) {
|
||||||
|
return from.length();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Set<String> set = (Set<String>) new TreeSet<String>(Arrays.asList(
|
||||||
|
"four", "three", "twelve"));
|
||||||
|
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||||
|
function);
|
||||||
|
assertTrue(map.get("four") == 4 && map.get("three") == 5
|
||||||
|
&& map.get("twelve") == 6);
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
|
||||||
|
Function<String, Integer> function = new Function<String, Integer>() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer apply(String from) {
|
||||||
|
return from.length();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Set<String> set = (Set<String>) new TreeSet<String>(Arrays.asList(
|
||||||
|
"four", "three", "twelve"));
|
||||||
|
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||||
|
function);
|
||||||
|
set.add("one");
|
||||||
|
assertTrue(map.get("one") == 3 && map.size()==4);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,5 +1,7 @@
|
||||||
package org.baeldung.httpclient;
|
package org.baeldung.httpclient;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.apache.http.Header;
|
import org.apache.http.Header;
|
||||||
|
@ -24,29 +26,25 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.impl.cookie.BasicClientCookie;
|
import org.apache.http.impl.cookie.BasicClientCookie;
|
||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class SandboxTest {
|
public class SandboxTest {
|
||||||
|
|
||||||
|
// original example
|
||||||
|
@Ignore
|
||||||
@Test
|
@Test
|
||||||
public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
|
public final void whenInterestingDigestAuthScenario_then401UnAuthorized() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
|
||||||
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
|
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
|
||||||
|
|
||||||
// set up the credentials to run agains the server
|
// set up the credentials to run agains the server
|
||||||
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||||
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
|
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
|
||||||
|
|
||||||
// This endpoint need fake cookie to work properly
|
|
||||||
final CookieStore cookieStore = new BasicCookieStore();
|
|
||||||
final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
|
|
||||||
cookie.setDomain("httpbin.org");
|
|
||||||
cookie.setPath("/");
|
|
||||||
cookieStore.addCookie(cookie);
|
|
||||||
|
|
||||||
// We need a first run to get a 401 to seed the digest auth
|
// We need a first run to get a 401 to seed the digest auth
|
||||||
|
|
||||||
// Make a client using those creds
|
// Make a client using those creds
|
||||||
final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build();
|
final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
|
||||||
|
|
||||||
// And make a call to the URL we are after
|
// And make a call to the URL we are after
|
||||||
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
|
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
|
||||||
|
@ -91,6 +89,50 @@ public class SandboxTest {
|
||||||
responseGood.close();
|
responseGood.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
|
||||||
|
final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
|
||||||
|
|
||||||
|
// set up the credentials to run agains the server
|
||||||
|
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||||
|
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
|
||||||
|
|
||||||
|
// This endpoint need fake cookie to work properly
|
||||||
|
final CookieStore cookieStore = new BasicCookieStore();
|
||||||
|
final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
|
||||||
|
cookie.setDomain("httpbin.org");
|
||||||
|
cookie.setPath("/");
|
||||||
|
cookieStore.addCookie(cookie);
|
||||||
|
|
||||||
|
// Make a client using those creds
|
||||||
|
final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build();
|
||||||
|
|
||||||
|
// And make a call to the URL we are after
|
||||||
|
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
|
||||||
|
|
||||||
|
// Create a context to use
|
||||||
|
final HttpClientContext context = HttpClientContext.create();
|
||||||
|
|
||||||
|
// Get a response from the sever (401 implicitly)
|
||||||
|
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
|
||||||
|
assertEquals(200, authResponse.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
|
// HttpClient will use cached digest parameters for future requests
|
||||||
|
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
|
||||||
|
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
|
||||||
|
|
||||||
|
try {
|
||||||
|
System.out.println("----------------------------------------");
|
||||||
|
System.out.println(responseGood.getStatusLine());
|
||||||
|
assertEquals(200, responseGood.getStatusLine().getStatusCode());
|
||||||
|
} finally {
|
||||||
|
responseGood.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -117,7 +159,7 @@ public class SandboxTest {
|
||||||
// == end
|
// == end
|
||||||
System.out.println("Executing The Request knowing the digest parameters ==== ");
|
System.out.println("Executing The Request knowing the digest parameters ==== ");
|
||||||
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
|
final HttpResponse authResponse = client.execute(targetHost, httpget, context);
|
||||||
System.out.println(authResponse.toString());
|
assertEquals(200, authResponse.getStatusLine().getStatusCode());
|
||||||
client.close();
|
client.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -133,12 +175,12 @@ public class SandboxTest {
|
||||||
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
|
final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
|
||||||
System.out.println("Executing The Request NOT knowing the digest parameters ==== ");
|
System.out.println("Executing The Request NOT knowing the digest parameters ==== ");
|
||||||
final HttpResponse tempResponse = client.execute(targetHost, httpget, context);
|
final HttpResponse tempResponse = client.execute(targetHost, httpget, context);
|
||||||
System.out.println(tempResponse.toString());
|
assertEquals(200, tempResponse.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
System.out.println("No more Challenges or 401");
|
System.out.println("No more Challenges or 401");
|
||||||
final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context);
|
final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context);
|
||||||
System.out.println(authResponse.toString());
|
assertEquals(200, authResponse.getStatusLine().getStatusCode());
|
||||||
authResponse.close();
|
authResponse.close();
|
||||||
}
|
}
|
||||||
client.close();
|
client.close();
|
||||||
|
|
|
@ -5,22 +5,13 @@
|
||||||
<artifactId>jooq-spring</artifactId>
|
<artifactId>jooq-spring</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<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>
|
<dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<!-- Import dependency management from Spring Boot -->
|
<!-- Import dependency management from Spring Boot -->
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-dependencies</artifactId>
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
<version>1.3.3.RELEASE</version>
|
<version>1.3.5.RELEASE</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
@ -46,30 +37,25 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-context</artifactId>
|
<artifactId>spring-context</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-jdbc</artifactId>
|
<artifactId>spring-jdbc</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-jooq</artifactId>
|
<artifactId>spring-boot-starter-jooq</artifactId>
|
||||||
<version>1.3.3.RELEASE</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Logging -->
|
<!-- Logging -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>ch.qos.logback</groupId>
|
<groupId>ch.qos.logback</groupId>
|
||||||
<artifactId>logback-classic</artifactId>
|
<artifactId>logback-classic</artifactId>
|
||||||
<version>${ch.qos.logback.version}</version>
|
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
@ -77,13 +63,11 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${org.springframework.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
@ -166,6 +150,29 @@
|
||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</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>
|
</project>
|
|
@ -0,0 +1,7 @@
|
||||||
|
=========
|
||||||
|
|
||||||
|
## Mock comparison realated tutorials
|
||||||
|
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit)
|
|
@ -0,0 +1,84 @@
|
||||||
|
<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>mock-comparisons</artifactId>
|
||||||
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<name>mockito</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>
|
||||||
|
|
||||||
|
<!-- 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>
|
|
@ -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
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package org.baeldung.mocks.testCase;
|
||||||
|
|
||||||
|
public class LoginDao {
|
||||||
|
|
||||||
|
public int login(UserForm userForm) {
|
||||||
|
//actual call to a third party library
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package org.baeldung.mocks.testCase;
|
||||||
|
|
||||||
|
public class LoginService {
|
||||||
|
|
||||||
|
private LoginDao loginDao;
|
||||||
|
|
||||||
|
private String currentUser;
|
||||||
|
|
||||||
|
public boolean login(UserForm userForm) {
|
||||||
|
assert null != userForm;
|
||||||
|
|
||||||
|
int loginResults = loginDao.login(userForm);
|
||||||
|
|
||||||
|
switch (loginResults) {
|
||||||
|
case 1:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCurrentUser(String username) {
|
||||||
|
if (null != username) {
|
||||||
|
this.currentUser = username;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLoginDao(LoginDao loginDao) {
|
||||||
|
this.loginDao = loginDao;
|
||||||
|
}
|
||||||
|
|
||||||
|
// standard setters and getters
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package org.baeldung.mocks.testCase;
|
||||||
|
|
||||||
|
public class UserForm {
|
||||||
|
|
||||||
|
// public access modifiers as only for testing
|
||||||
|
|
||||||
|
public String password;
|
||||||
|
|
||||||
|
public String username;
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,143 @@
|
||||||
|
package org.baeldung.mocks.easymock;
|
||||||
|
|
||||||
|
import org.baeldung.mocks.testCase.LoginController;
|
||||||
|
import org.baeldung.mocks.testCase.LoginDao;
|
||||||
|
import org.baeldung.mocks.testCase.LoginService;
|
||||||
|
import org.baeldung.mocks.testCase.UserForm;
|
||||||
|
import org.easymock.*;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
@RunWith(EasyMockRunner.class)
|
||||||
|
public class LoginControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LoginDao loginDao;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LoginService loginService;
|
||||||
|
|
||||||
|
@TestSubject
|
||||||
|
private LoginController loginController = new LoginController();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertThatNoMethodHasBeenCalled() {
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
loginController.login(null);
|
||||||
|
|
||||||
|
// no method called
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertTwoMethodsHaveBeenCalled() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
EasyMock.expect(loginService.login(userForm)).andReturn(true);
|
||||||
|
loginService.setCurrentUser("foo");
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertOnlyOneMethodHasBeenCalled() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
EasyMock.expect(loginService.login(userForm)).andReturn(false);
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("KO", login);
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockExceptionThrowing() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
EasyMock.expect(loginService.login(userForm)).andThrow(new IllegalArgumentException());
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("ERROR", login);
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockAnObjectToPassAround() {
|
||||||
|
UserForm userForm = EasyMock.mock(UserForm.class);
|
||||||
|
EasyMock.expect(userForm.getUsername()).andReturn("foo");
|
||||||
|
EasyMock.expect(loginService.login(userForm)).andReturn(true);
|
||||||
|
loginService.setCurrentUser("foo");
|
||||||
|
EasyMock.replay(userForm);
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
EasyMock.verify(userForm);
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void argumentMatching() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// default matcher
|
||||||
|
EasyMock.expect(loginService.login(EasyMock.isA(UserForm.class))).andReturn(true);
|
||||||
|
// complex matcher
|
||||||
|
loginService.setCurrentUser(specificArgumentMatching("foo"));
|
||||||
|
EasyMock.replay(loginService);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
EasyMock.verify(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String specificArgumentMatching(final String expected) {
|
||||||
|
EasyMock.reportMatcher(new IArgumentMatcher() {
|
||||||
|
@Override
|
||||||
|
public boolean matches(Object argument) {
|
||||||
|
return argument instanceof String && ((String) argument).startsWith(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void appendTo(StringBuffer buffer) {
|
||||||
|
//NOOP
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void partialMocking() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// use partial mock
|
||||||
|
LoginService loginServicePartial = EasyMock.partialMockBuilder(LoginService.class).
|
||||||
|
addMockedMethod("setCurrentUser").createMock();
|
||||||
|
loginServicePartial.setCurrentUser("foo");
|
||||||
|
// let service's login use implementation so let's mock DAO call
|
||||||
|
EasyMock.expect(loginDao.login(userForm)).andReturn(1);
|
||||||
|
|
||||||
|
loginServicePartial.setLoginDao(loginDao);
|
||||||
|
loginController.loginService = loginServicePartial;
|
||||||
|
|
||||||
|
EasyMock.replay(loginDao);
|
||||||
|
EasyMock.replay(loginServicePartial);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
// verify mocked call
|
||||||
|
EasyMock.verify(loginServicePartial);
|
||||||
|
EasyMock.verify(loginDao);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,159 @@
|
||||||
|
package org.baeldung.mocks.jmockit;
|
||||||
|
|
||||||
|
import mockit.*;
|
||||||
|
import mockit.integration.junit4.JMockit;
|
||||||
|
import org.baeldung.mocks.testCase.LoginController;
|
||||||
|
import org.baeldung.mocks.testCase.LoginDao;
|
||||||
|
import org.baeldung.mocks.testCase.LoginService;
|
||||||
|
import org.baeldung.mocks.testCase.UserForm;
|
||||||
|
import org.hamcrest.BaseMatcher;
|
||||||
|
import org.hamcrest.Description;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
@RunWith(JMockit.class)
|
||||||
|
public class LoginControllerTest {
|
||||||
|
|
||||||
|
@Injectable
|
||||||
|
private LoginDao loginDao;
|
||||||
|
|
||||||
|
@Injectable
|
||||||
|
private LoginService loginService;
|
||||||
|
|
||||||
|
@Tested
|
||||||
|
private LoginController loginController;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertThatNoMethodHasBeenCalled() {
|
||||||
|
loginController.login(null);
|
||||||
|
// no method called
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertTwoMethodsHaveBeenCalled() {
|
||||||
|
final UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
new Expectations() {{
|
||||||
|
loginService.login(userForm);
|
||||||
|
result = true;
|
||||||
|
loginService.setCurrentUser("foo");
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertOnlyOneMethodHasBeenCalled() {
|
||||||
|
final UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
new Expectations() {{
|
||||||
|
loginService.login(userForm);
|
||||||
|
result = false;
|
||||||
|
// no expectation for setCurrentUser
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("KO", login);
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockExceptionThrowing() {
|
||||||
|
final UserForm userForm = new UserForm();
|
||||||
|
new Expectations() {{
|
||||||
|
loginService.login(userForm);
|
||||||
|
result = new IllegalArgumentException();
|
||||||
|
// no expectation for setCurrentUser
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("ERROR", login);
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockAnObjectToPassAround(@Mocked final UserForm userForm) {
|
||||||
|
new Expectations() {{
|
||||||
|
userForm.getUsername();
|
||||||
|
result = "foo";
|
||||||
|
loginService.login(userForm);
|
||||||
|
result = true;
|
||||||
|
loginService.setCurrentUser("foo");
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
new FullVerifications(userForm) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void argumentMatching() {
|
||||||
|
final UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// default matcher
|
||||||
|
new Expectations() {{
|
||||||
|
loginService.login((UserForm) any);
|
||||||
|
result = true;
|
||||||
|
// complex matcher
|
||||||
|
loginService.setCurrentUser(withArgThat(new BaseMatcher<String>() {
|
||||||
|
@Override
|
||||||
|
public boolean matches(Object item) {
|
||||||
|
return item instanceof String && ((String) item).startsWith("foo");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void describeTo(Description description) {
|
||||||
|
//NOOP
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
new FullVerifications(loginService) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void partialMocking() {
|
||||||
|
// use partial mock
|
||||||
|
final LoginService partialLoginService = new LoginService();
|
||||||
|
partialLoginService.setLoginDao(loginDao);
|
||||||
|
loginController.loginService = partialLoginService;
|
||||||
|
|
||||||
|
final UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// let service's login use implementation so let's mock DAO call
|
||||||
|
new Expectations() {{
|
||||||
|
loginDao.login(userForm);
|
||||||
|
result = 1;
|
||||||
|
// no expectation for loginService.login
|
||||||
|
partialLoginService.setCurrentUser("foo");
|
||||||
|
}};
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
// verify mocked call
|
||||||
|
new FullVerifications(partialLoginService) {
|
||||||
|
};
|
||||||
|
new FullVerifications(loginDao) {
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,125 @@
|
||||||
|
package org.baeldung.mocks.mockito;
|
||||||
|
|
||||||
|
import org.baeldung.mocks.testCase.LoginController;
|
||||||
|
import org.baeldung.mocks.testCase.LoginDao;
|
||||||
|
import org.baeldung.mocks.testCase.LoginService;
|
||||||
|
import org.baeldung.mocks.testCase.UserForm;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.mockito.*;
|
||||||
|
|
||||||
|
public class LoginControllerTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LoginDao loginDao;
|
||||||
|
|
||||||
|
@Spy
|
||||||
|
@InjectMocks
|
||||||
|
private LoginService spiedLoginService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private LoginService loginService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private LoginController loginController;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
loginController = new LoginController();
|
||||||
|
MockitoAnnotations.initMocks(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertThatNoMethodHasBeenCalled() {
|
||||||
|
loginController.login(null);
|
||||||
|
// no method called
|
||||||
|
Mockito.verifyZeroInteractions(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertTwoMethodsHaveBeenCalled() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
Mockito.when(loginService.login(userForm)).thenReturn(true);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
Mockito.verify(loginService).login(userForm);
|
||||||
|
Mockito.verify(loginService).setCurrentUser("foo");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void assertOnlyOneMethodHasBeenCalled() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
Mockito.when(loginService.login(userForm)).thenReturn(false);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("KO", login);
|
||||||
|
Mockito.verify(loginService).login(userForm);
|
||||||
|
Mockito.verifyNoMoreInteractions(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockExceptionThrowing() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("ERROR", login);
|
||||||
|
Mockito.verify(loginService).login(userForm);
|
||||||
|
Mockito.verifyZeroInteractions(loginService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void mockAnObjectToPassAround() {
|
||||||
|
UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock();
|
||||||
|
Mockito.when(loginService.login(userForm)).thenReturn(true);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
Mockito.verify(loginService).login(userForm);
|
||||||
|
Mockito.verify(loginService).setCurrentUser("foo");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void argumentMatching() {
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// default matcher
|
||||||
|
Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
Mockito.verify(loginService).login(userForm);
|
||||||
|
// complex matcher
|
||||||
|
Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher<String>() {
|
||||||
|
@Override
|
||||||
|
public boolean matches(Object argument) {
|
||||||
|
return argument instanceof String && ((String) argument).startsWith("foo");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void partialMocking() {
|
||||||
|
// use partial mock
|
||||||
|
loginController.loginService = spiedLoginService;
|
||||||
|
UserForm userForm = new UserForm();
|
||||||
|
userForm.username = "foo";
|
||||||
|
// let service's login use implementation so let's mock DAO call
|
||||||
|
Mockito.when(loginDao.login(userForm)).thenReturn(1);
|
||||||
|
|
||||||
|
String login = loginController.login(userForm);
|
||||||
|
|
||||||
|
Assert.assertEquals("OK", login);
|
||||||
|
// verify mocked call
|
||||||
|
Mockito.verify(spiedLoginService).setCurrentUser("foo");
|
||||||
|
}
|
||||||
|
}
|
4
pom.xml
4
pom.xml
|
@ -9,6 +9,8 @@
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>apache-fop</module>
|
<module>apache-fop</module>
|
||||||
|
<module>assertj</module>
|
||||||
|
|
||||||
<module>core-java</module>
|
<module>core-java</module>
|
||||||
<module>core-java-8</module>
|
<module>core-java-8</module>
|
||||||
<module>gson</module>
|
<module>gson</module>
|
||||||
|
@ -23,6 +25,7 @@
|
||||||
<module>jooq-spring</module>
|
<module>jooq-spring</module>
|
||||||
<module>json-path</module>
|
<module>json-path</module>
|
||||||
<module>mockito</module>
|
<module>mockito</module>
|
||||||
|
<module>mock-comparisons</module>
|
||||||
<module>jee7schedule</module>
|
<module>jee7schedule</module>
|
||||||
<!-- <module>jpa-storedprocedure</module> -->
|
<!-- <module>jpa-storedprocedure</module> -->
|
||||||
<module>querydsl</module>
|
<module>querydsl</module>
|
||||||
|
@ -49,6 +52,7 @@
|
||||||
<module>spring-mvc-no-xml</module>
|
<module>spring-mvc-no-xml</module>
|
||||||
<module>spring-mvc-xml</module>
|
<module>spring-mvc-xml</module>
|
||||||
<module>spring-openid</module>
|
<module>spring-openid</module>
|
||||||
|
<module>spring-protobuf</module>
|
||||||
<module>spring-quartz</module>
|
<module>spring-quartz</module>
|
||||||
<module>spring-rest</module>
|
<module>spring-rest</module>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,58 @@
|
||||||
|
<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>spring-protobuf</artifactId>
|
||||||
|
<version>0.1-SNAPSHOT</version>
|
||||||
|
<name>spring-protobuf</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
|
<version>1.2.4.RELEASE</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java</artifactId>
|
||||||
|
<version>3.0.0-beta-3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.protobuf-java-format</groupId>
|
||||||
|
<artifactId>protobuf-java-format</artifactId>
|
||||||
|
<version>1.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
|
<artifactId>httpclient</artifactId>
|
||||||
|
<version>4.5.2</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>
|
|
@ -0,0 +1,66 @@
|
||||||
|
package com.baeldung.protobuf;
|
||||||
|
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Course;
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Student;
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Student.PhoneNumber;
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Student.PhoneType;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) {
|
||||||
|
return new RestTemplate(Arrays.asList(hmc));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
|
||||||
|
return new ProtobufHttpMessageConverter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public CourseRepository createTestCourses() {
|
||||||
|
Map<Integer, Course> courses = new HashMap<>();
|
||||||
|
|
||||||
|
Course course1 = Course.newBuilder().setId(1).setCourseName("REST with Spring").addAllStudent(createTestStudents()).build();
|
||||||
|
|
||||||
|
Course course2 = Course.newBuilder().setId(2).setCourseName("Learn Spring Security").addAllStudent(new ArrayList<>()).build();
|
||||||
|
|
||||||
|
courses.put(course1.getId(), course1);
|
||||||
|
courses.put(course2.getId(), course2);
|
||||||
|
|
||||||
|
return new CourseRepository(courses);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Student> createTestStudents() {
|
||||||
|
PhoneNumber phone1 = createPhone("123456", PhoneType.MOBILE);
|
||||||
|
Student student1 = createStudent(1, "John", "Doe", "john.doe@baeldung.com", Arrays.asList(phone1));
|
||||||
|
|
||||||
|
PhoneNumber phone2 = createPhone("234567", PhoneType.LANDLINE);
|
||||||
|
Student student2 = createStudent(2, "Richard", "Roe", "richard.roe@baeldung.com", Arrays.asList(phone2));
|
||||||
|
|
||||||
|
PhoneNumber phone3_1 = createPhone("345678", PhoneType.MOBILE);
|
||||||
|
PhoneNumber phone3_2 = createPhone("456789", PhoneType.LANDLINE);
|
||||||
|
Student student3 = createStudent(3, "Jane", "Doe", "jane.doe@baeldung.com", Arrays.asList(phone3_1, phone3_2));
|
||||||
|
|
||||||
|
return Arrays.asList(student1, student2, student3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Student createStudent(int id, String firstName, String lastName, String email, List<PhoneNumber> phones) {
|
||||||
|
return Student.newBuilder().setId(id).setFirstName(firstName).setLastName(lastName).setEmail(email).addAllPhone(phones).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private PhoneNumber createPhone(String number, PhoneType type) {
|
||||||
|
return PhoneNumber.newBuilder().setNumber(number).setType(type).build();
|
||||||
|
}
|
||||||
|
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.protobuf;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Course;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
public class CourseController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
CourseRepository courseRepo;
|
||||||
|
|
||||||
|
@RequestMapping("/courses/{id}")
|
||||||
|
Course customer(@PathVariable Integer id) {
|
||||||
|
return courseRepo.getCourse(id);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.protobuf;
|
||||||
|
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Course;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class CourseRepository {
|
||||||
|
|
||||||
|
private final Map<Integer, Course> courses;
|
||||||
|
|
||||||
|
public CourseRepository(Map<Integer, Course> courses) {
|
||||||
|
this.courses = courses;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Course getCourse(int id) {
|
||||||
|
return courses.get(id);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package baeldung;
|
||||||
|
|
||||||
|
option java_package = "com.baeldung.protobuf";
|
||||||
|
option java_outer_classname = "BaeldungTraining";
|
||||||
|
|
||||||
|
message Course {
|
||||||
|
int32 id = 1;
|
||||||
|
string course_name = 2;
|
||||||
|
repeated Student student = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Student {
|
||||||
|
int32 id = 1;
|
||||||
|
string first_name = 2;
|
||||||
|
string last_name = 3;
|
||||||
|
string email = 4;
|
||||||
|
repeated PhoneNumber phone = 5;
|
||||||
|
|
||||||
|
message PhoneNumber {
|
||||||
|
string number = 1;
|
||||||
|
PhoneType type = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PhoneType {
|
||||||
|
MOBILE = 0;
|
||||||
|
LANDLINE = 1;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,75 @@
|
||||||
|
package com.baeldung.protobuf;
|
||||||
|
|
||||||
|
import com.baeldung.protobuf.BaeldungTraining.Course;
|
||||||
|
import com.googlecode.protobuf.format.JsonFormat;
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.client.methods.HttpGet;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||||
|
import org.springframework.boot.test.WebIntegrationTest;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.containsString;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
@RunWith(SpringJUnit4ClassRunner.class)
|
||||||
|
@SpringApplicationConfiguration(classes = Application.class)
|
||||||
|
@WebIntegrationTest
|
||||||
|
public class ApplicationTest {
|
||||||
|
|
||||||
|
private static final String COURSE1_URL = "http://localhost:8080/courses/1";
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RestTemplate restTemplate;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingRestTemplate_thenSucceed() {
|
||||||
|
ResponseEntity<Course> course = restTemplate.getForEntity(COURSE1_URL, Course.class);
|
||||||
|
assertResponse(course.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingHttpClient_thenSucceed() throws IOException {
|
||||||
|
InputStream responseStream = executeHttpRequest(COURSE1_URL);
|
||||||
|
String jsonOutput = convertProtobufMessageStreamToJsonString(responseStream);
|
||||||
|
assertResponse(jsonOutput);
|
||||||
|
}
|
||||||
|
|
||||||
|
private InputStream executeHttpRequest(String url) throws IOException {
|
||||||
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||||
|
HttpGet request = new HttpGet(url);
|
||||||
|
HttpResponse httpResponse = httpClient.execute(request);
|
||||||
|
return httpResponse.getEntity().getContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String convertProtobufMessageStreamToJsonString(InputStream protobufStream) throws IOException {
|
||||||
|
JsonFormat jsonFormat = new JsonFormat();
|
||||||
|
Course course = Course.parseFrom(protobufStream);
|
||||||
|
return jsonFormat.printToString(course);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertResponse(String response) {
|
||||||
|
assertThat(response, containsString("id"));
|
||||||
|
assertThat(response, containsString("course_name"));
|
||||||
|
assertThat(response, containsString("REST with Spring"));
|
||||||
|
assertThat(response, containsString("student"));
|
||||||
|
assertThat(response, containsString("first_name"));
|
||||||
|
assertThat(response, containsString("last_name"));
|
||||||
|
assertThat(response, containsString("email"));
|
||||||
|
assertThat(response, containsString("john.doe@baeldung.com"));
|
||||||
|
assertThat(response, containsString("richard.roe@baeldung.com"));
|
||||||
|
assertThat(response, containsString("jane.doe@baeldung.com"));
|
||||||
|
assertThat(response, containsString("phone"));
|
||||||
|
assertThat(response, containsString("number"));
|
||||||
|
assertThat(response, containsString("type"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -15,11 +15,6 @@
|
||||||
<arguments>
|
<arguments>
|
||||||
</arguments>
|
</arguments>
|
||||||
</buildCommand>
|
</buildCommand>
|
||||||
<buildCommand>
|
|
||||||
<name>org.eclipse.wst.validation.validationbuilder</name>
|
|
||||||
<arguments>
|
|
||||||
</arguments>
|
|
||||||
</buildCommand>
|
|
||||||
<buildCommand>
|
<buildCommand>
|
||||||
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
<name>org.springframework.ide.eclipse.core.springbuilder</name>
|
||||||
<arguments>
|
<arguments>
|
||||||
|
@ -38,6 +33,5 @@
|
||||||
<nature>org.eclipse.jdt.core.javanature</nature>
|
<nature>org.eclipse.jdt.core.javanature</nature>
|
||||||
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
<nature>org.eclipse.m2e.core.maven2Nature</nature>
|
||||||
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
|
||||||
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
|
|
||||||
</natures>
|
</natures>
|
||||||
</projectDescription>
|
</projectDescription>
|
||||||
|
|
|
@ -1,12 +1,5 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<classpath>
|
<classpath>
|
||||||
<classpathentry kind="src" path="src/main/webapp"/>
|
<classpathentry kind="src" path="src/main/webapp"/>
|
||||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
|
|
||||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
|
|
||||||
<attributes>
|
|
||||||
<attribute name="hide" value="true"/>
|
|
||||||
</attributes>
|
|
||||||
</classpathentry>
|
|
||||||
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
|
|
||||||
<classpathentry kind="output" path=""/>
|
<classpathentry kind="output" path=""/>
|
||||||
</classpath>
|
</classpath>
|
||||||
|
|
|
@ -1,8 +1,5 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<faceted-project>
|
<faceted-project>
|
||||||
<fixed facet="wst.jsdt.web"/>
|
|
||||||
<installed facet="cloudfoundry.standalone.app" version="1.0"/>
|
|
||||||
<installed facet="java" version="1.8"/>
|
<installed facet="java" version="1.8"/>
|
||||||
<installed facet="jst.web" version="3.0"/>
|
<installed facet="jst.web" version="3.1"/>
|
||||||
<installed facet="wst.jsdt.web" version="1.0"/>
|
|
||||||
</faceted-project>
|
</faceted-project>
|
||||||
|
|
|
@ -9,7 +9,7 @@
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>1.2.4.RELEASE</version>
|
<version>1.3.5.RELEASE</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -59,7 +59,6 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
<version>3.0.1</version>
|
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
@ -101,24 +100,20 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-api</artifactId>
|
<artifactId>slf4j-api</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>ch.qos.logback</groupId>
|
<groupId>ch.qos.logback</groupId>
|
||||||
<artifactId>logback-classic</artifactId>
|
<artifactId>logback-classic</artifactId>
|
||||||
<version>${logback.version}</version>
|
|
||||||
<!-- <scope>runtime</scope> -->
|
<!-- <scope>runtime</scope> -->
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>jcl-over-slf4j</artifactId>
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
|
||||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>log4j-over-slf4j</artifactId>
|
<artifactId>log4j-over-slf4j</artifactId>
|
||||||
<version>${org.slf4j.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
|
@ -126,34 +121,29 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-core</artifactId>
|
<artifactId>hamcrest-core</artifactId>
|
||||||
<version>${org.hamcrest.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.hamcrest</groupId>
|
<groupId>org.hamcrest</groupId>
|
||||||
<artifactId>hamcrest-library</artifactId>
|
<artifactId>hamcrest-library</artifactId>
|
||||||
<version>${org.hamcrest.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.mockito</groupId>
|
<groupId>org.mockito</groupId>
|
||||||
<artifactId>mockito-core</artifactId>
|
<artifactId>mockito-core</artifactId>
|
||||||
<version>${mockito.version}</version>
|
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
<version>${spring.version}</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
@ -226,11 +216,10 @@
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Spring -->
|
<!-- Spring -->
|
||||||
<org.springframework.security.version>4.0.4.RELEASE</org.springframework.security.version>
|
|
||||||
|
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||||
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
|
<mysql-connector-java.version>5.1.39</mysql-connector-java.version>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue