This commit is contained in:
Seun Matt 2017-08-03 08:44:16 +01:00
commit 559241d15f
100 changed files with 3104 additions and 1055 deletions

View File

@ -35,7 +35,12 @@
<configuration> <configuration>
<sourceDirectory>src/docs/asciidoc</sourceDirectory> <sourceDirectory>src/docs/asciidoc</sourceDirectory>
<outputDirectory>target/docs/asciidoc</outputDirectory> <outputDirectory>target/docs/asciidoc</outputDirectory>
<attributes>
<pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir>
<pdf-style>custom</pdf-style>
</attributes>
<backend>pdf</backend> <backend>pdf</backend>
<doctype>book</doctype>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

View File

@ -1,3 +1,13 @@
== Introduction Section :icons: font
Hi. I'm a simple test to see if this Maven build is working. If you see me in a nice PDF, then it means everything is [red]#working#.
= Generating book with AsciiDoctorj
Baeldung
[abstract]
This is the actual content.
== First Section
This is first section of the book where you can include some nice icons like icon:comment[].
You can also create http://www.baeldung.com[links]

View File

@ -0,0 +1,29 @@
title_page:
align: left
page:
layout: portrait
margin: [0.75in, 1in, 0.75in, 1in]
size: A4
base:
font_color: #333333
line_height_length: 17
line_height: $base_line_height_length / $base_font_size
link:
font_color: #009900
header:
height: 0.5in
line_height: 1
recto_content:
center: '{document-title}'
verso_content:
center: '{document-title}'
footer:
height: 0.5in
line_height: 1
recto_content:
right: '{chapter-title} | *{page-number}*'
verso_content:
left: '*{page-number}* | {chapter-title}'

View File

@ -382,7 +382,7 @@
</profile> </profile>
</profiles> </profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
@ -391,7 +391,7 @@
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
<!-- util --> <!-- util -->
<guava.version>21.0</guava.version> <guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version> <bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
@ -408,7 +408,7 @@
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version> <mockito.version>2.8.9</mockito.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>

View File

@ -21,3 +21,4 @@ public class CyclicBarrierExample {
} }
} }
} }

View File

@ -0,0 +1,23 @@
package com.baeldung.application;
import com.baeldung.entities.User;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) {
Map<User, User> users = new HashMap<>();
User user1 = new User(1L, "John", "john@domain.com");
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
User user3 = new User(3L, "Mary", "mary@domain.com");
users.put(user1, user1);
users.put(user2, user2);
users.put(user3, user3);
if (users.containsKey(user1)) {
System.out.print("User found in the collection");
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class User {
private final Logger logger = LoggerFactory.getLogger(User.class);
private long id;
private String name;
private String email;
public User(long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
User user = (User) o;
return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (int) id;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + (email == null ? 0 : email.hashCode());
logger.info("hashCode() method called - Computed hash: " + hash);
return hash;
}
// getters and setters here
}

View File

@ -0,0 +1,30 @@
package com.baeldung.application;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;
public class ApplicationTest {
private ByteArrayOutputStream outContent;
@Before
public void setUpPrintStreamInstance() throws Exception {
this.outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
}
@After
public void tearDownByteArrayOutputStream() throws Exception {
outContent = null;
}
@Test
public void main_NoInputState_TextPrintedToConsole() throws Exception {
Application.main(new String[]{});
assertEquals("User found in the collection", outContent.toString());
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.entities;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class UserTest {
private User user;
private User comparisonUser;
@Before
public void setUpUserInstances() {
this.user = new User(1L, "test", "test@domain.com");
this.comparisonUser = this.user;
}
@After
public void tearDownUserInstances() {
user = null;
comparisonUser = null;
}
@Test
public void equals_EqualUserInstance_TrueAssertion(){
Assert.assertTrue(user.equals(comparisonUser));
}
@Test
public void hashCode_UserHash_TrueAssertion() {
Assert.assertEquals(1792276941, user.hashCode());
}
}

View File

@ -63,6 +63,6 @@ public class MappedByteBufferUnitTest {
private Path getFileURIFromResources(String fileName) throws Exception { private Path getFileURIFromResources(String fileName) throws Exception {
ClassLoader classLoader = getClass().getClassLoader(); ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).getPath()); return Paths.get(classLoader.getResource(fileName).toURI());
} }
} }

View File

@ -1,190 +1,190 @@
package com.baeldung.money; package com.baeldung.money;
import org.javamoney.moneta.FastMoney; import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money; import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle; import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import javax.money.CurrencyUnit; import javax.money.CurrencyUnit;
import javax.money.Monetary; import javax.money.Monetary;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException; import javax.money.UnknownCurrencyException;
import javax.money.convert.CurrencyConversion; import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions; import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder; import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat; import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats; import javax.money.format.MonetaryFormats;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class JavaMoneyUnitTest { public class JavaMoneyUnitManualTest {
@Test @Test
public void givenCurrencyCode_whenString_thanExist() { public void givenCurrencyCode_whenString_thanExist() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
assertNotNull(usd); assertNotNull(usd);
assertEquals(usd.getCurrencyCode(), "USD"); assertEquals(usd.getCurrencyCode(), "USD");
assertEquals(usd.getNumericCode(), 840); assertEquals(usd.getNumericCode(), 840);
assertEquals(usd.getDefaultFractionDigits(), 2); assertEquals(usd.getDefaultFractionDigits(), 2);
} }
@Test(expected = UnknownCurrencyException.class) @Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() { public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA"); Monetary.getCurrency("AAA");
} }
@Test @Test
public void givenAmounts_whenStringified_thanEquals() { public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency(usd) .setCurrency(usd)
.setNumber(200) .setNumber(200)
.create(); .create();
Money moneyof = Money.of(12, usd); Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd); FastMoney fastmoneyof = FastMoney.of(2, usd);
assertEquals("USD", usd.toString()); assertEquals("USD", usd.toString());
assertEquals("USD 200", fstAmtUSD.toString()); assertEquals("USD 200", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString()); assertEquals("USD 12", moneyof.toString());
assertEquals("USD 2.00000", fastmoneyof.toString()); assertEquals("USD 2.00000", fastmoneyof.toString());
} }
@Test @Test
public void givenCurrencies_whenCompared_thanNotequal() { public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
Money oneEuro = Money.of(1, "EUR"); Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR"))); assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
assertTrue(oneDolar.equals(Money.of(1, "USD"))); assertTrue(oneDolar.equals(Money.of(1, "USD")));
} }
@Test(expected = ArithmeticException.class) @Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() { public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
oneDolar.divide(3); oneDolar.divide(3);
fail(); // if no exception fail(); // if no exception
} }
@Test @Test
public void givenAmounts_whenSummed_thanCorrect() { public void givenAmounts_whenSummed_thanCorrect() {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF")); List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts Money sumAmtCHF = (Money) monetaryAmounts
.stream() .stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add); .reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString()); assertEquals("CHF 111.35", sumAmtCHF.toString());
} }
@Test @Test
public void givenArithmetic_whenStringified_thanEqualsAmount() { public void givenArithmetic_whenStringified_thanEqualsAmount() {
CurrencyUnit usd = Monetary.getCurrency("USD"); CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd); Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency(usd) .setCurrency(usd)
.setNumber(200.50) .setNumber(200.50)
.create(); .create();
MonetaryAmount oneDolar = Monetary MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
Money subtractedAmount = Money Money subtractedAmount = Money
.of(1, "USD") .of(1, "USD")
.subtract(fstAmtUSD); .subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25); MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25); MonetaryAmount divideAmount = oneDolar.divide(0.25);
assertEquals("USD", usd.toString()); assertEquals("USD", usd.toString());
assertEquals("USD 1", oneDolar.toString()); assertEquals("USD 1", oneDolar.toString());
assertEquals("USD 200.5", fstAmtUSD.toString()); assertEquals("USD 200.5", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString()); assertEquals("USD 12", moneyof.toString());
assertEquals("USD -199.5", subtractedAmount.toString()); assertEquals("USD -199.5", subtractedAmount.toString());
assertEquals("USD 0.25", multiplyAmount.toString()); assertEquals("USD 0.25", multiplyAmount.toString());
assertEquals("USD 4", divideAmount.toString()); assertEquals("USD 4", divideAmount.toString());
} }
@Test @Test
public void givenAmount_whenRounded_thanEquals() { public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("EUR") .setCurrency("EUR")
.setNumber(1.30473908) .setNumber(1.30473908)
.create(); .create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding()); MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString()); assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString()); assertEquals("EUR 1.3", roundEUR.toString());
} }
@Test @Test
@Ignore("Currency providers are not always available") @Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() { public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR"); CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR); MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR); assertNotNull(convertedAmountUSDtoEUR);
} }
@Test @Test
public void givenLocale_whenFormatted_thanEquals() { public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US); MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar); String usFormatted = formatUSD.format(oneDollar);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD); assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted); assertEquals("USD1.00", usFormatted);
} }
@Test @Test
public void givenAmount_whenCustomFormat_thanEquals() { public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory() .getDefaultAmountFactory()
.setCurrency("USD") .setCurrency("USD")
.setNumber(1) .setNumber(1)
.create(); .create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US) .of(Locale.US)
.set(CurrencyStyle.NAME) .set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤") .set("pattern", "00000.00 <EFBFBD>")
.build()); .build());
String customFormatted = customFormat.format(oneDollar); String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat); assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString()); assertEquals("USD 1", oneDollar.toString());
assertEquals("00001.00 US Dollar", customFormatted); assertEquals("00001.00 US Dollar", customFormatted);
} }
} }

View File

@ -0,0 +1,65 @@
package com.baeldung.stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Test;
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
import com.google.common.collect.ImmutableList;
public class StreamToImmutableTest {
@Test
public void whenUsingCollectingToImmutableSet_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c");
List<String> result = givenList.stream()
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
System.out.println(result.getClass());
}
@Test
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> result = givenList.stream()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
System.out.println(result.getClass());
}
@Test
public void whenCollectToImmutableList_thenSuccess() {
List<Integer> list = IntStream.range(0, 9)
.boxed()
.collect(ImmutableList.toImmutableList());
System.out.println(list.getClass());
}
@Test
public void whenCollectToMyImmutableListCollector_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList());
System.out.println(result.getClass());
}
@Test
public void whenPassingSupplier_thenSuccess() {
List<String> givenList = Arrays.asList("a", "b", "c", "d");
List<String> result = givenList.stream()
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
System.out.println(result.getClass());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.stream.mycollectors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class MyImmutableListCollector {
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
return Collector.of(supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
return toImmutableList(ArrayList::new);
}
}

View File

@ -41,4 +41,4 @@ public class CustomTemporalAdjusterTest {
assertEquals(fourteenDaysAfterDate, result.toString()); assertEquals(fourteenDaysAfterDate, result.toString());
} }
} }

View File

@ -11,6 +11,7 @@ import java.io.FileInputStream;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Locale;
import java.util.Scanner; import java.util.Scanner;
import org.junit.Test; import org.junit.Test;
@ -105,6 +106,7 @@ public class JavaScannerUnitTest {
public void whenScanString_thenCorrect() throws IOException { public void whenScanString_thenCorrect() throws IOException {
final String input = "Hello 1 F 3.5"; final String input = "Hello 1 F 3.5";
final Scanner scanner = new Scanner(input); final Scanner scanner = new Scanner(input);
scanner.useLocale(Locale.US);
assertEquals("Hello", scanner.next()); assertEquals("Hello", scanner.next());
assertEquals(1, scanner.nextInt()); assertEquals(1, scanner.nextInt());

View File

@ -4,5 +4,5 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api [1]: https://github.com/eugenp/spring-hypermedia-api
###Relevant Articles: ### Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign) - [Intro to Feign](http://www.baeldung.com/intro-to-feign)

View File

@ -1,12 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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">
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.feign</groupId> <groupId>com.baeldung.feign</groupId>
<artifactId>feign-client</artifactId> <artifactId>feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

74
grpc/pom.xml Normal file
View File

@ -0,0 +1,74 @@
<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>grpc</groupId>
<artifactId>grpc-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>grpc-demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<io.grpc.version>1.5.0</io.grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${io.grpc.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>
com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package org.baeldung.grpc.client;
import org.baeldung.grpc.HelloRequest;
import org.baeldung.grpc.HelloResponse;
import org.baeldung.grpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext(true)
.build();
HelloServiceGrpc.HelloServiceBlockingStub stub
= HelloServiceGrpc.newBlockingStub(channel);
HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder()
.setFirstName("Baeldung")
.setLastName("gRPC")
.build());
System.out.println("Response received from server:\n" + helloResponse);
channel.shutdown();
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung.grpc.server;
import java.io.IOException;
import io.grpc.Server;
import io.grpc.ServerBuilder;
public class GrpcServer {
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new HelloServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
}

View File

@ -0,0 +1,29 @@
package org.baeldung.grpc.server;
import org.baeldung.grpc.HelloRequest;
import org.baeldung.grpc.HelloResponse;
import org.baeldung.grpc.HelloServiceGrpc.HelloServiceImplBase;
import io.grpc.stub.StreamObserver;
public class HelloServiceImpl extends HelloServiceImplBase {
@Override
public void hello(
HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
System.out.println("Request received from client:\n" + request);
String greeting = new StringBuilder().append("Hello, ")
.append(request.getFirstName())
.append(" ")
.append(request.getLastName())
.toString();
HelloResponse response = HelloResponse.newBuilder()
.setGreeting(greeting)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
option java_multiple_files = true;
package org.baeldung.grpc;
message HelloRequest {
string firstName = 1;
string lastName = 2;
}
message HelloResponse {
string greeting = 1;
}
service HelloService {
rpc hello(HelloRequest) returns (HelloResponse);
}

View File

@ -0,0 +1,2 @@
#application.secret = 2o128940921eo298e21
#db = /url/to/the/datastore

42
jooby/conf/logback.xml Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/jooby.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/jooby.%d{yyyy-MM-dd}.log</fileNamePattern>
<totalSizeCap>1mb</totalSizeCap>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/access.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log/access.%d{yyyy-MM-dd}.log</fileNamePattern>
<totalSizeCap>1mb</totalSizeCap>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="org.jooby.RequestLogger" additivity="false">
<appender-ref ref="ACCESS" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

56
jooby/pom.xml Normal file
View File

@ -0,0 +1,56 @@
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jooby</artifactId>
<groupId>com.baeldung.jooby</groupId>
<version>1.0</version>
<name>jooby</name>
<parent>
<groupId>org.jooby</groupId>
<artifactId>modules</artifactId>
<version>1.1.3</version>
</parent>
<properties>
<jooby.version>1.1.3</jooby.version>
<application.class>com.baeldung.jooby.App</application.class>
</properties>
<dependencies>
<dependency>
<groupId>org.jooby</groupId>
<artifactId>jooby-netty</artifactId>
</dependency>
<dependency>
<groupId>org.jooby</groupId>
<artifactId>jooby-jedis</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

17
jooby/public/form.html Normal file
View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form enctype="application/x-www-form-urlencoded" action="/submitForm" method="post">
<input name="id" />
<input name="name" />
<input name="email" />
<input name="phone" />
<input name="address" />
<input type="submit" value="Submit"/>
</form>
</body>
</html>

10
jooby/public/welcome.html Normal file
View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
i m welcomed
</body>
</html>

41
jooby/src/etc/stork.yml Normal file
View File

@ -0,0 +1,41 @@
# Name of application (make sure it has no spaces)
name: "${project.artifactId}"
# Display name of application (can have spaces)
display_name: "${project.name}"
# Type of launcher (CONSOLE or DAEMON)
type: DAEMON
# Java class to run
main_class: "${application.class}"
domain: "${project.groupId}"
short_description: "${project.artifactId}"
# Platform launchers to generate (WINDOWS, LINUX, MAC_OSX)
# Linux launcher is suitable for Bourne shells (e.g. Linux/BSD)
platforms: [ LINUX ]
# Working directory for app
# RETAIN will not change the working directory
# APP_HOME will change the working directory to the home of the app
# (where it was intalled) before running the main class
working_dir_mode: RETAIN
# Minimum version of java required (system will be searched for acceptable jvm)
min_java_version: "1.8"
# Min/max fixed memory (measured in MB)
min_java_memory: 512
max_java_memory: 512
# Min/max memory by percentage of system
#min_java_memory_pct: 10
#max_java_memory_pct: 20
# Try to create a symbolic link to java executable in <app_home>/run with
# the name of "<app_name>-java" so that commands like "ps" will make it
# easier to find your app
symlink_java: true

View File

@ -0,0 +1,95 @@
package com.baeldung.jooby;
import org.jooby.Jooby;
import org.jooby.Mutant;
import org.jooby.Session;
import org.jooby.jedis.Redis;
import org.jooby.jedis.RedisSessionStore;
import com.baeldung.jooby.bean.Employee;
public class App extends Jooby {
{
port(8080);
securePort(8443);
}
{
get("/", () -> "Hello World!");
}
{
get("/user/{id}", req -> "Hello user : " + req.param("id").value());
get("/user/:id", req -> "Hello user: " + req.param("id").value());
get("/uid:{id}", req -> "Hello User with id : uid" + req.param("id").value());
}
{
onStart(() -> {
System.out.println("starting app");
});
onStop(() -> {
System.out.println("stopping app");
});
onStarted(() -> {
System.out.println("app started");
});
}
{
get("/login", () -> "Hello from Baeldung");
}
{
post("/save", req -> {
Mutant token = req.param("token");
return token.intValue();
});
}
{
{
assets("/employee", "form.html");
}
post("/submitForm", req -> {
Employee employee = req.params(Employee.class);
// TODO
return "empoyee data saved successfullly";
});
}
{
get("/filter", (req, resp, chain) -> {
// TODO
// resp.send(...);
chain.next(req, resp);
});
get("/filter", (req, resp) -> {
resp.send("filter response");
});
}
{
// cookieSession();
// use(new Redis());
//
// session(RedisSessionStore.class);
get("/session", req -> {
Session session = req.session();
session.set("token", "value");
return session.get("token").value();
});
}
public static void main(final String[] args) {
run(App::new, args);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.jooby.bean;
public class Employee {
String id;
String name;
String email;
public Employee(String id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.jooby.mvc;
import org.jooby.Result;
import org.jooby.Results;
import org.jooby.mvc.GET;
import org.jooby.mvc.Path;
@Path("/hello")
public class GetController {
@GET
public String hello() {
return "Hello Baeldung";
}
@GET
@Path("/home")
public Result home() {
return Results.html("welcome").put("model", new Object());
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.jooby.mvc;
import org.jooby.mvc.POST;
import org.jooby.mvc.Path;
@Path("/submit")
public class PostController {
@POST
public String hello() {
return "Submit Baeldung";
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jooby;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import org.jooby.test.JoobyRule;
import org.jooby.test.MockRouter;
import org.junit.ClassRule;
import org.junit.Test;
public class AppTest {
@ClassRule
public static JoobyRule app = new JoobyRule(new App());
@Test
public void given_defaultUrl_expect_fixedString() {
get("/").then().assertThat().body(equalTo("Hello World!")).statusCode(200)
.contentType("text/html;charset=UTF-8");
}
@Test
public void given_defaultUrl_with_mockrouter_expect_fixedString() throws Throwable {
String result = new MockRouter(new App()).get("/");
assertEquals("Hello World!", result);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.kotlin.delegates
val data = arrayOf<MutableMap<String, Any?>>(
mutableMapOf(
"id" to 1,
"name" to "George",
"age" to 4
),
mutableMapOf(
"id" to 2,
"name" to "Charlotte",
"age" to 2
)
)
class NoRecordFoundException(id: Int) : Exception("No record found for id $id") {
init {
println("No record found for ID $id")
}
}
fun queryForValue(field: String, id: Int): Any {
println("Loading record $id from the fake database")
val value = data.firstOrNull { it["id"] == id }
?.get(field) ?: throw NoRecordFoundException(id)
println("Loaded value $value for field $field of record $id")
return value
}
fun update(field: String, id: Int, value: Any?) {
println("Updating field $field of record $id to value $value in the fake database")
data.firstOrNull { it["id"] == id }
?.put(field, value)
?: throw NoRecordFoundException(id)
}

View File

@ -0,0 +1,13 @@
package com.baeldung.kotlin.delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class DatabaseDelegate<in R, T>(private val field: String, private val id: Int) : ReadWriteProperty<R, T> {
override fun getValue(thisRef: R, property: KProperty<*>): T =
queryForValue(field, id) as T
override fun setValue(thisRef: R, property: KProperty<*>, value: T) {
update(field, id, value)
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.kotlin.delegates
class User(val id: Int) {
var name: String by DatabaseDelegate("name", id)
var age: Int by DatabaseDelegate("age", id)
}

View File

@ -0,0 +1,26 @@
package com.baeldung.kotlin.delegates
import org.junit.Test
import kotlin.test.assertEquals
class DatabaseDelegatesTest {
@Test
fun testGetKnownFields() {
val user = User(1)
assertEquals("George", user.name)
assertEquals(4, user.age)
}
@Test
fun testSetKnownFields() {
val user = User(2)
user.age = 3
assertEquals(3, user.age)
}
@Test(expected = NoRecordFoundException::class)
fun testGetKnownField() {
val user = User(3)
user.name
}
}

22
libraries-data/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?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>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>libraries-data</artifactId>
<name>libraries-data</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
</dependencies>
<properties>
<kryo.version>4.0.1</kryo.version>
</properties>
</project>

View File

@ -0,0 +1,16 @@
package com.baeldung.kryo;
import java.io.Serializable;
public class ComplexClass implements Serializable{
private static final long serialVersionUID = 123456L;
private String name = "Bael";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.kryo;
import com.esotericsoftware.kryo.DefaultSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
@DefaultSerializer(PersonSerializer.class)
public class Person implements KryoSerializable {
private String name = "John Doe";
private int age = 18;
private Date birthDate = new Date(933191282821L);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public void write(Kryo kryo, Output output) {
output.writeString(name);
output.writeLong(birthDate.getTime());
output.writeInt(age);
}
@Override
public void read(Kryo kryo, Input input) {
name = input.readString();
birthDate = new Date(input.readLong());
age = input.readInt();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.util.Date;
public class PersonSerializer extends Serializer<Person> {
@Override
public void write(Kryo kryo, Output output, Person object) {
output.writeString(object.getName());
output.writeLong(object.getBirthDate()
.getTime());
}
@Override
public Person read(Kryo kryo, Input input, Class<Person> type) {
Person person = new Person();
person.setName(input.readString());
long birthDate = input.readLong();
person.setBirthDate(new Date(birthDate));
person.setAge(calculateAge(birthDate));
return person;
}
private int calculateAge(long birthDate) {
// Some custom logic
return 18;
}
}

View File

@ -0,0 +1,125 @@
package com.baeldung.kryo;
import static org.junit.Assert.assertEquals;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.Test;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
public class KryoUnitTest {
private Kryo kryo;
private Output output;
private Input input;
@Before
public void init() {
kryo = new Kryo();
try {
output = new Output(new FileOutputStream("file.dat"));
input = new Input(new FileInputStream("file.dat"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KryoUnitTest.class.getName())
.log(Level.SEVERE, null, ex);
}
}
@Test
public void givenObject_whenSerializing_thenReadCorrectly() {
Object someObject = "Some string";
kryo.writeClassAndObject(output, someObject);
output.close();
Object theObject = kryo.readClassAndObject(input);
input.close();
assertEquals(theObject, "Some string");
}
@Test
public void givenObjects_whenSerializing_thenReadCorrectly() {
String someString = "Multiple Objects";
Date someDate = new Date(915170400000L);
kryo.writeObject(output, someString);
kryo.writeObject(output, someDate);
output.close();
String readString = kryo.readObject(input, String.class);
Date readDate = kryo.readObject(input, Date.class);
input.close();
assertEquals(readString, "Multiple Objects");
assertEquals(readDate.getTime(), 915170400000L);
}
@Test
public void givenPerson_whenSerializing_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
}
@Test
public void givenPerson_whenUsingCustomSerializer_thenReadCorrectly() {
Person person = new Person();
person.setAge(0);
kryo.register(Person.class, new PersonSerializer());
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenPerson_whenCustomSerialization_thenReadCorrectly() {
Person person = new Person();
kryo.writeObject(output, person);
output.close();
Person readPerson = kryo.readObject(input, Person.class);
input.close();
assertEquals(readPerson.getName(), "John Doe");
assertEquals(readPerson.getAge(), 18);
}
@Test
public void givenJavaSerializable_whenSerializing_thenReadCorrectly() {
ComplexClass complexClass = new ComplexClass();
kryo.register(ComplexClass.class, new JavaSerializer());
kryo.writeObject(output, complexClass);
output.close();
ComplexClass readComplexObject = kryo.readObject(input, ComplexClass.class);
input.close();
assertEquals(readComplexObject.getName(), "Bael");
}
}

View File

@ -27,6 +27,7 @@
- [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing) - [Introduction to Awaitility](http://www.baeldung.com/awaitlity-testing)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog) - [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph) - [Introduction to Neuroph](http://www.baeldung.com/intro-to-neuroph)
- [Guide to Apache Commons CircularFifoQueue](http://www.baeldung.com/commons-circular-fifo-queue)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -1,497 +1,501 @@
<?xml version="1.0" encoding="UTF-8"?> <?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" <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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>libraries</artifactId> <artifactId>libraries</artifactId>
<name>libraries</name> <name>libraries</name>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId> <artifactId>maven-dependency-plugin</artifactId>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.felix</groupId> <groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version> <version>3.3.0</version>
<type>maven-plugin</type> <type>maven-plugin</type>
</dependency>
</dependency> </dependencies>
</dependencies> <extensions>true</extensions>
<extensions>true</extensions> </plugin>
</plugin> <plugin>
<plugin> <artifactId>maven-failsafe-plugin</artifactId>
<artifactId>maven-failsafe-plugin</artifactId> <version>2.20</version>
<version>2.20</version> <configuration>
<configuration> <systemProperties>
<systemProperties> <webdriver.chrome.driver>chromedriver</webdriver.chrome.driver>
<webdriver.chrome.driver>chromedriver</webdriver.chrome.driver> </systemProperties>
</systemProperties> </configuration>
</configuration> </plugin>
</plugin> <plugin>
<plugin> <groupId>net.serenity-bdd.maven.plugins</groupId>
<groupId>net.serenity-bdd.maven.plugins</groupId> <artifactId>serenity-maven-plugin</artifactId>
<artifactId>serenity-maven-plugin</artifactId> <version>${serenity.plugin.version}</version>
<version>${serenity.plugin.version}</version> <executions>
<executions> <execution>
<execution> <id>serenity-reports</id>
<id>serenity-reports</id> <phase>post-integration-test</phase>
<phase>post-integration-test</phase> <goals>
<goals> <goal>aggregate</goal>
<goal>aggregate</goal> </goals>
</goals> </execution>
</execution> </executions>
</executions> </plugin>
</plugin> <!-- JDO Plugin -->
<!-- JDO Plugin --> <plugin>
<plugin> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>datanucleus-maven-plugin</artifactId>
<artifactId>datanucleus-maven-plugin</artifactId> <version>5.0.2</version>
<version>5.0.2</version> <configuration>
<configuration> <api>JDO</api>
<api>JDO</api> <props>${basedir}/datanucleus.properties</props>
<props>${basedir}/datanucleus.properties</props> <log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration> <verbose>true</verbose>
<verbose>true</verbose> <fork>false</fork>
<fork>false</fork> <!-- Solve windows line too long error -->
<!-- Solve windows line too long error --> </configuration>
</configuration> <executions>
<executions> <execution>
<execution> <phase>process-classes</phase>
<phase>process-classes</phase> <goals>
<goals> <goal>enhance</goal>
<goal>enhance</goal> </goals>
</goals> </execution>
</execution> </executions>
</executions> </plugin>
</plugin> <!-- Neuroph -->
<!-- Neuroph --> <plugin>
<plugin> <groupId>org.apache.maven.plugins</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId>
<artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version>
<version>3.0.2</version> <configuration>
<configuration> <excludes>
<excludes> <exclude>**/log4j.properties</exclude>
<exclude>**/log4j.properties</exclude> </excludes>
</excludes> <archive>
<archive> <manifest>
<manifest> <mainClass>com.baeldung.neuroph.NeurophXOR</mainClass>
<mainClass>com.baeldung.neuroph.NeurophXOR</mainClass> </manifest>
</manifest> </archive>
</archive> </configuration>
</configuration> </plugin>
</plugin> <plugin>
<plugin> <groupId>org.apache.maven.plugins</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId>
<artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version>
<version>2.18.1</version> <executions>
<executions> <execution>
<execution> <id>test</id>
<id>test</id> <phase>test</phase>
<phase>test</phase> <goals>
<goals> <goal>test</goal>
<goal>test</goal> </goals>
</goals> <configuration>
<configuration> <includes>
<includes> <include>test/java/com/baeldung/neuroph/XORTest.java</include>
<include>test/java/com/baeldung/neuroph/XORTest.java</include> </includes>
</includes> </configuration>
</configuration> </execution>
</execution> </executions>
</executions> </plugin>
</plugin> <!-- /Neuroph -->
<!-- /Neuroph --> </plugins>
</plugins> </build>
</build> <dependencies>
<dependencies> <!-- https://mvnrepository.com/artifact/org.beykery/neuroph/2.92 -->
<!-- https://mvnrepository.com/artifact/org.beykery/neuroph/2.92 --> <dependency>
<dependency> <groupId>org.beykery</groupId>
<groupId>org.beykery</groupId> <artifactId>neuroph</artifactId>
<artifactId>neuroph</artifactId> <version>${neuroph.version}</version>
<version>${neuroph.version}</version> </dependency>
</dependency> <!-- https://mvnrepository.com/artifact/cglib/cglib -->
<!-- https://mvnrepository.com/artifact/cglib/cglib --> <dependency>
<dependency> <groupId>cglib</groupId>
<groupId>cglib</groupId> <artifactId>cglib</artifactId>
<artifactId>cglib</artifactId> <version>${cglib.version}</version>
<version>${cglib.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>commons-beanutils</groupId>
<groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId>
<artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version>
<version>${commons-beanutils.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.apache.commons</groupId>
<groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId>
<artifactId>commons-lang3</artifactId> <version>${commons-lang.version}</version>
<version>${commons-lang.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.apache.commons</groupId>
<groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId>
<artifactId>commons-text</artifactId> <version>${commons-text.version}</version>
<version>${commons-text.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.apache.commons</groupId>
<groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId>
<artifactId>commons-collections4</artifactId> <version>${commons.collections.version}</version>
<version>${commons.collections.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.jasypt</groupId>
<groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId>
<artifactId>jasypt</artifactId> <version>${jasypt.version}</version>
<version>${jasypt.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.javatuples</groupId>
<groupId>org.javatuples</groupId> <artifactId>javatuples</artifactId>
<artifactId>javatuples</artifactId> <version>${javatuples.version}</version>
<version>${javatuples.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.javassist</groupId>
<groupId>org.javassist</groupId> <artifactId>javassist</artifactId>
<artifactId>javassist</artifactId> <version>${javaassist.version}</version>
<version>${javaassist.version}</version> </dependency>
</dependency> <!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core --> <dependency>
<dependency> <groupId>org.assertj</groupId>
<groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId>
<artifactId>assertj-core</artifactId> <version>${assertj.version}</version>
<version>${assertj.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.skyscreamer</groupId>
<groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId>
<artifactId>jsonassert</artifactId> <version>${jsonassert.version}</version>
<version>${jsonassert.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.javers</groupId>
<groupId>org.javers</groupId> <artifactId>javers-core</artifactId>
<artifactId>javers-core</artifactId> <version>${javers.version}</version>
<version>${javers.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.eclipse.jetty</groupId>
<groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId>
<artifactId>jetty-server</artifactId> <version>${jetty.version}</version>
<version>${jetty.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.eclipse.jetty</groupId>
<groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlet</artifactId>
<artifactId>jetty-servlet</artifactId> <version>${jetty.version}</version>
<version>${jetty.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>io.specto</groupId>
<groupId>org.apache.httpcomponents</groupId> <artifactId>hoverfly-java</artifactId>
<artifactId>httpclient</artifactId> <version>0.8.0</version>
<version>${httpclient.version}</version> </dependency>
<exclusions> <dependency>
<exclusion> <groupId>org.apache.httpcomponents</groupId>
<artifactId>commons-logging</artifactId> <artifactId>httpclient</artifactId>
<groupId>commons-logging</groupId> <version>${httpclient.version}</version>
</exclusion> <exclusions>
</exclusions> <exclusion>
</dependency> <artifactId>commons-logging</artifactId>
<dependency> <groupId>commons-logging</groupId>
<groupId>commons-io</groupId> </exclusion>
<artifactId>commons-io</artifactId> </exclusions>
<version>${commons.io.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>commons-io</groupId>
<groupId>commons-chain</groupId> <artifactId>commons-io</artifactId>
<artifactId>commons-chain</artifactId> <version>${commons.io.version}</version>
<version>${commons-chain.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>commons-chain</groupId>
<groupId>commons-dbutils</groupId> <artifactId>commons-chain</artifactId>
<artifactId>commons-dbutils</artifactId> <version>${commons-chain.version}</version>
<version>${commons.dbutils.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>commons-dbutils</groupId>
<groupId>org.apache.flink</groupId> <artifactId>commons-dbutils</artifactId>
<artifactId>flink-core</artifactId> <version>${commons.dbutils.version}</version>
<version>${flink.version}</version> </dependency>
<exclusions> <dependency>
<exclusion> <groupId>org.apache.flink</groupId>
<artifactId>commons-logging</artifactId> <artifactId>flink-core</artifactId>
<groupId>commons-logging</groupId> <version>${flink.version}</version>
</exclusion> <exclusions>
</exclusions> <exclusion>
</dependency> <artifactId>commons-logging</artifactId>
<dependency> <groupId>commons-logging</groupId>
<groupId>org.apache.flink</groupId> </exclusion>
<artifactId>flink-java</artifactId> </exclusions>
<version>${flink.version}</version> </dependency>
<exclusions> <dependency>
<exclusion> <groupId>org.apache.flink</groupId>
<artifactId>commons-logging</artifactId> <artifactId>flink-java</artifactId>
<groupId>commons-logging</groupId> <version>${flink.version}</version>
</exclusion> <exclusions>
</exclusions> <exclusion>
</dependency> <artifactId>commons-logging</artifactId>
<dependency> <groupId>commons-logging</groupId>
<groupId>org.apache.flink</groupId> </exclusion>
<artifactId>flink-test-utils_2.10</artifactId> </exclusions>
<version>${flink.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>org.apache.flink</groupId>
<dependency> <artifactId>flink-test-utils_2.10</artifactId>
<groupId>org.apache.commons</groupId> <version>${flink.version}</version>
<artifactId>commons-math3</artifactId> <scope>test</scope>
<version>3.6.1</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.apache.commons</groupId>
<groupId>net.serenity-bdd</groupId> <artifactId>commons-math3</artifactId>
<artifactId>serenity-core</artifactId> <version>3.6.1</version>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-core</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.version}</version>
<artifactId>serenity-junit</artifactId> <scope>test</scope>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-junit</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.version}</version>
<artifactId>serenity-jbehave</artifactId> <scope>test</scope>
<version>${serenity.jbehave.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-jbehave</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.jbehave.version}</version>
<artifactId>serenity-rest-assured</artifactId> <scope>test</scope>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-rest-assured</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.version}</version>
<artifactId>serenity-jira-requirements-provider</artifactId> <scope>test</scope>
<version>${serenity.jira.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-jira-requirements-provider</artifactId>
<groupId>com.fasterxml.jackson.core</groupId> <version>${serenity.jira.version}</version>
<artifactId>jackson-databind</artifactId> <scope>test</scope>
<version>${jackson.version}</version> </dependency>
</dependency> <dependency>
<!-- JDO --> <groupId>com.fasterxml.jackson.core</groupId>
<dependency> <artifactId>jackson-databind</artifactId>
<groupId>org.datanucleus</groupId> <version>${jackson.version}</version>
<artifactId>javax.jdo</artifactId> </dependency>
<version>3.2.0-m6</version> <!-- JDO -->
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>javax.jdo</artifactId>
<artifactId>datanucleus-core</artifactId> <version>3.2.0-m6</version>
<version>5.1.0-m1</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>datanucleus-core</artifactId>
<artifactId>datanucleus-api-jdo</artifactId> <version>5.1.0-m1</version>
<version>5.1.0-m1</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>datanucleus-api-jdo</artifactId>
<artifactId>datanucleus-rdbms</artifactId> <version>5.1.0-m1</version>
<version>5.1.0-m1</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>datanucleus-rdbms</artifactId>
<artifactId>datanucleus-maven-plugin</artifactId> <version>5.1.0-m1</version>
<version>5.0.2</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>org.datanucleus</groupId> <artifactId>datanucleus-maven-plugin</artifactId>
<artifactId>datanucleus-xml</artifactId> <version>5.0.2</version>
<version>5.0.0-release</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.datanucleus</groupId>
<groupId>net.openhft</groupId> <artifactId>datanucleus-xml</artifactId>
<artifactId>chronicle</artifactId> <version>5.0.0-release</version>
<version>3.6.4</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>net.openhft</groupId>
<groupId>org.springframework</groupId> <artifactId>chronicle</artifactId>
<artifactId>spring-web</artifactId> <version>3.6.4</version>
<version>4.3.8.RELEASE</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.springframework</groupId>
<groupId>net.serenity-bdd</groupId> <artifactId>spring-web</artifactId>
<artifactId>serenity-spring</artifactId> <version>4.3.8.RELEASE</version>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-spring</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.version}</version>
<artifactId>serenity-screenplay</artifactId> <scope>test</scope>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-screenplay</artifactId>
<groupId>net.serenity-bdd</groupId> <version>${serenity.version}</version>
<artifactId>serenity-screenplay-webdriver</artifactId> <scope>test</scope>
<version>${serenity.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>net.serenity-bdd</groupId>
<dependency> <artifactId>serenity-screenplay-webdriver</artifactId>
<groupId>io.rest-assured</groupId> <version>${serenity.version}</version>
<artifactId>spring-mock-mvc</artifactId> <scope>test</scope>
<version>3.0.3</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>io.rest-assured</groupId>
<dependency> <artifactId>spring-mock-mvc</artifactId>
<groupId>org.multiverse</groupId> <version>3.0.3</version>
<artifactId>multiverse-core</artifactId> <scope>test</scope>
<version>${multiverse.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.multiverse</groupId>
<groupId>com.zaxxer</groupId> <artifactId>multiverse-core</artifactId>
<artifactId>HikariCP</artifactId> <version>${multiverse.version}</version>
<version>2.6.1</version> </dependency>
<scope>compile</scope> <dependency>
</dependency> <groupId>com.zaxxer</groupId>
<dependency> <artifactId>HikariCP</artifactId>
<groupId>com.h2database</groupId> <version>2.6.1</version>
<artifactId>h2</artifactId> <scope>compile</scope>
<version>${h2.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>com.h2database</groupId>
<groupId>pl.pragmatists</groupId> <artifactId>h2</artifactId>
<artifactId>JUnitParams</artifactId> <version>${h2.version}</version>
<version>${jUnitParams.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>pl.pragmatists</groupId>
<dependency> <artifactId>JUnitParams</artifactId>
<groupId>org.quartz-scheduler</groupId> <version>${jUnitParams.version}</version>
<artifactId>quartz</artifactId> <scope>test</scope>
<version>2.3.0</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.quartz-scheduler</groupId>
<groupId>one.util</groupId> <artifactId>quartz</artifactId>
<artifactId>streamex</artifactId> <version>2.3.0</version>
<version>0.6.5</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>one.util</groupId>
<groupId>org.jooq</groupId> <artifactId>streamex</artifactId>
<artifactId>jool</artifactId> <version>0.6.5</version>
<version>0.9.12</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.jooq</groupId>
<groupId>org.openjdk.jmh</groupId> <artifactId>jool</artifactId>
<artifactId>jmh-core</artifactId> <version>0.9.12</version>
<version>1.19</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.openjdk.jmh</groupId>
<groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId>
<artifactId>jmh-generator-annprocess</artifactId> <version>1.19</version>
<version>1.19</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.openjdk.jmh</groupId>
<groupId>io.netty</groupId> <artifactId>jmh-generator-annprocess</artifactId>
<artifactId>netty-all</artifactId> <version>1.19</version>
<version>${netty.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>io.netty</groupId>
<groupId>junit</groupId> <artifactId>netty-all</artifactId>
<artifactId>junit</artifactId> <version>${netty.version}</version>
<version>${junit.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>junit</groupId>
<dependency> <artifactId>junit</artifactId>
<groupId>info.debatty</groupId> <version>${junit.version}</version>
<artifactId>java-lsh</artifactId> <scope>test</scope>
<version>${java-lsh.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>info.debatty</groupId>
<groupId>au.com.dius</groupId> <artifactId>java-lsh</artifactId>
<artifactId>pact-jvm-consumer-junit_2.11</artifactId> <version>${java-lsh.version}</version>
<version>${pact.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>au.com.dius</groupId>
<dependency> <artifactId>pact-jvm-consumer-junit_2.11</artifactId>
<groupId>org.codehaus.groovy</groupId> <version>${pact.version}</version>
<artifactId>groovy-all</artifactId> <scope>test</scope>
<version>2.4.10</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.codehaus.groovy</groupId>
<groupId>org.awaitility</groupId> <artifactId>groovy-all</artifactId>
<artifactId>awaitility</artifactId> <version>2.4.10</version>
<version>${awaitility.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>org.awaitility</groupId>
<dependency> <artifactId>awaitility</artifactId>
<groupId>org.awaitility</groupId> <version>${awaitility.version}</version>
<artifactId>awaitility-proxy</artifactId> <scope>test</scope>
<version>${awaitility.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>org.awaitility</groupId>
<dependency> <artifactId>awaitility-proxy</artifactId>
<groupId>org.hamcrest</groupId> <version>${awaitility.version}</version>
<artifactId>java-hamcrest</artifactId> <scope>test</scope>
<version>${org.hamcrest.java-hamcrest.version}</version> </dependency>
<scope>test</scope> <dependency>
</dependency> <groupId>org.hamcrest</groupId>
<dependency> <artifactId>java-hamcrest</artifactId>
<groupId>net.agkn</groupId> <version>${org.hamcrest.java-hamcrest.version}</version>
<artifactId>hll</artifactId> <scope>test</scope>
<version>${hll.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>net.agkn</groupId>
<groupId>net.bytebuddy</groupId> <artifactId>hll</artifactId>
<artifactId>byte-buddy</artifactId> <version>${hll.version}</version>
<version>${bytebuddy.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>net.bytebuddy</groupId>
<groupId>net.bytebuddy</groupId> <artifactId>byte-buddy</artifactId>
<artifactId>byte-buddy-agent</artifactId> <version>${bytebuddy.version}</version>
<version>${bytebuddy.version}</version> </dependency>
</dependency> <dependency>
<dependency> <groupId>net.bytebuddy</groupId>
<groupId>org.pcollections</groupId> <artifactId>byte-buddy-agent</artifactId>
<artifactId>pcollections</artifactId> <version>${bytebuddy.version}</version>
<version>${pcollections.version}</version> </dependency>
</dependency> <dependency>
</dependencies> <groupId>org.pcollections</groupId>
<properties> <artifactId>pcollections</artifactId>
<multiverse.version>0.7.0</multiverse.version> <version>${pcollections.version}</version>
<cglib.version>3.2.4</cglib.version> </dependency>
<commons-lang.version>3.5</commons-lang.version> </dependencies>
<commons-text.version>1.1</commons-text.version> <properties>
<commons-beanutils.version>1.9.3</commons-beanutils.version> <multiverse.version>0.7.0</multiverse.version>
<commons-chain.version>1.2</commons-chain.version> <cglib.version>3.2.4</cglib.version>
<jasypt.version>1.9.2</jasypt.version> <commons-lang.version>3.5</commons-lang.version>
<javatuples.version>1.2</javatuples.version> <commons-text.version>1.1</commons-text.version>
<javaassist.version>3.21.0-GA</javaassist.version> <commons-beanutils.version>1.9.3</commons-beanutils.version>
<assertj.version>3.6.2</assertj.version> <commons-chain.version>1.2</commons-chain.version>
<jsonassert.version>1.5.0</jsonassert.version> <jasypt.version>1.9.2</jasypt.version>
<javers.version>3.1.0</javers.version> <javatuples.version>1.2</javatuples.version>
<jetty.version>9.4.3.v20170317</jetty.version> <javaassist.version>3.21.0-GA</javaassist.version>
<httpclient.version>4.5.3</httpclient.version> <assertj.version>3.6.2</assertj.version>
<commons.io.version>2.5</commons.io.version> <jsonassert.version>1.5.0</jsonassert.version>
<commons.dbutils.version>1.6</commons.dbutils.version> <javers.version>3.1.0</javers.version>
<h2.version>1.4.196</h2.version> <jetty.version>9.4.3.v20170317</jetty.version>
<jetty.version>9.4.2.v20170220</jetty.version> <httpclient.version>4.5.3</httpclient.version>
<httpclient.version>4.5.3</httpclient.version> <commons.io.version>2.5</commons.io.version>
<commons.io.version>2.5</commons.io.version> <commons.dbutils.version>1.6</commons.dbutils.version>
<flink.version>1.2.0</flink.version> <h2.version>1.4.196</h2.version>
<jackson.version>2.8.5</jackson.version> <jetty.version>9.4.2.v20170220</jetty.version>
<neuroph.version>2.92</neuroph.version> <httpclient.version>4.5.3</httpclient.version>
<serenity.version>1.4.0</serenity.version> <commons.io.version>2.5</commons.io.version>
<serenity.jbehave.version>1.24.0</serenity.jbehave.version> <flink.version>1.2.0</flink.version>
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version> <jackson.version>2.8.5</jackson.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version> <neuroph.version>2.92</neuroph.version>
<jUnitParams.version>1.1.0</jUnitParams.version> <serenity.version>1.4.0</serenity.version>
<netty.version>4.1.10.Final</netty.version> <serenity.jbehave.version>1.24.0</serenity.jbehave.version>
<commons.collections.version>4.1</commons.collections.version> <serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<junit.version>4.12</junit.version> <serenity.plugin.version>1.4.0</serenity.plugin.version>
<java-lsh.version>0.10</java-lsh.version> <jUnitParams.version>1.1.0</jUnitParams.version>
<pact.version>3.5.0</pact.version> <netty.version>4.1.10.Final</netty.version>
<awaitility.version>3.0.0</awaitility.version> <commons.collections.version>4.1</commons.collections.version>
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version> <junit.version>4.12</junit.version>
<hll.version>1.6.0</hll.version> <java-lsh.version>0.10</java-lsh.version>
<bytebuddy.version>1.7.1</bytebuddy.version> <pact.version>3.5.0</pact.version>
<pcollections.version>2.1.2</pcollections.version> <awaitility.version>3.0.0</awaitility.version>
</properties> <org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
<hll.version>1.6.0</hll.version>
<bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version>
</properties>
</project> </project>

View File

@ -0,0 +1,22 @@
package com.baeldung.streamutils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.streamutils;
import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
public InputStream getInputStream() {
return StreamUtils.emptyInput();
}
}

View File

@ -0,0 +1,140 @@
package com.baeldung.hoverfly;
import static io.specto.hoverfly.junit.core.SimulationSource.dsl;
import static io.specto.hoverfly.junit.dsl.HoverflyDsl.service;
import static io.specto.hoverfly.junit.dsl.HttpBodyConverter.jsonWithSingleQuotes;
import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.any;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsTo;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToJson;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.equalsToXml;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matches;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.startsWith;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesJsonPath;
import static io.specto.hoverfly.junit.dsl.matchers.HoverflyMatchers.matchesXPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiTest {
private static final SimulationSource source = dsl(
service("http://www.baeldung.com")
.get("/api/courses/1")
.willReturn(success().body(
jsonWithSingleQuotes("{'id':'1','name':'HCI'}")))
.post("/api/courses")
.willReturn(success())
.andDelay(3, TimeUnit.SECONDS)
.forMethod("POST"),
service(matches("www.*dung.com"))
.get(startsWith("/api/student"))
.queryParam("page", any())
.willReturn(success())
.post(equalsTo("/api/student"))
.body(equalsToJson(jsonWithSingleQuotes("{'id':'1','name':'Joe'}")))
.willReturn(success())
.put("/api/student/1")
.body(matchesJsonPath("$.name"))
.willReturn(success())
.post("/api/student")
.body(equalsToXml("<student><id>2</id><name>John</name></student>"))
.willReturn(success())
.put("/api/student/2")
.body(matchesXPath("/student/name"))
.willReturn(success()));
@ClassRule
public static final HoverflyRule rule = HoverflyRule.inSimulationMode(source);
private final RestTemplate restTemplate = new RestTemplate();
@Test
public void givenGetCourseById_whenRequestSimulated_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<String> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/courses/1", String.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
assertEquals("{\"id\":\"1\",\"name\":\"HCI\"}", courseResponse.getBody());
}
@Test
public void givenPostCourse_whenDelayInRequest_thenResponseIsDelayed() throws URISyntaxException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/courses", null, Void.class);
stopWatch.stop();
long postTime = stopWatch.getTime();
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
assertTrue(3L <= TimeUnit.MILLISECONDS.toSeconds(postTime));
}
@Test
public void givenGetStudent_whenRequestMatcher_thenAPICalledSuccessfully() throws URISyntaxException {
final ResponseEntity<Void> courseResponse = restTemplate.getForEntity(
"http://www.baeldung.com/api/student?page=3", Void.class);
assertEquals(HttpStatus.OK, courseResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherJson_thenResponseContainsEqualJson() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "{\"id\":\"1\",\"name\":\"Joe\"}", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenJsonPathMatcher_thenRequestJsonContainsElementInPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/1"))
.body("{\"id\":\"1\",\"name\":\"Trevor\"}");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
@Test
public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException {
final ResponseEntity<Void> postResponse = restTemplate.postForEntity(
"http://www.baeldung.com/api/student", "<student><id>2</id><name>John</name></student>", Void.class);
assertEquals(HttpStatus.OK, postResponse.getStatusCode());
}
@Test
public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException {
RequestEntity<String> putRequest = RequestEntity
.put(new URI("http://www.baeldung.com/api/student/2"))
.body("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<student><id>2</id><name>Monica</name></student>");
ResponseEntity<String> putResponse = restTemplate.exchange(putRequest, String.class);
assertEquals(HttpStatus.OK, putResponse.getStatusCode());
}
}

View File

@ -10,6 +10,10 @@ import static org.junit.Assert.*;
public class XORTest { public class XORTest {
private NeuralNetwork ann = null; private NeuralNetwork ann = null;
private void print(String input, double output, double actual) {
System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
}
@Before @Before
public void annInit() { public void annInit() {
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork()); ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
@ -19,32 +23,36 @@ public class XORTest {
public void leftDisjunctTest() { public void leftDisjunctTest() {
ann.setInput(0, 1); ann.setInput(0, 1);
ann.calculate(); ann.calculate();
assertEquals(ann.getOutput()[0], 1.0,0.0); print("0, 1", ann.getOutput()[0], 1.0);
assertEquals(ann.getOutput()[0], 1.0, 0.0);
} }
@Test @Test
public void rightDisjunctTest() { public void rightDisjunctTest() {
ann.setInput(1, 0); ann.setInput(1, 0);
ann.calculate(); ann.calculate();
assertEquals(ann.getOutput()[0], 1.0,0.0); print("1, 0", ann.getOutput()[0], 1.0);
assertEquals(ann.getOutput()[0], 1.0, 0.0);
} }
@Test @Test
public void bothFalseConjunctTest() { public void bothFalseConjunctTest() {
ann.setInput(0, 0); ann.setInput(0, 0);
ann.calculate(); ann.calculate();
assertEquals(ann.getOutput()[0], 0.0,0.0); print("0, 0", ann.getOutput()[0], 0.0);
assertEquals(ann.getOutput()[0], 0.0, 0.0);
} }
@Test @Test
public void bothTrueConjunctTest() { public void bothTrueConjunctTest() {
ann.setInput(1, 1); ann.setInput(1, 1);
ann.calculate(); ann.calculate();
assertEquals(ann.getOutput()[0], 0.0,0.0); print("1, 1", ann.getOutput()[0], 0.0);
assertEquals(ann.getOutput()[0], 0.0, 0.0);
} }
@After @After
public void annClose() { public void annClose() {
ann = null; ann = null;
} }
} }

View File

@ -0,0 +1,100 @@
package com.baeldung.streamutils;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.StreamUtils;
import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
public class CopyStreamTest {
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copy(in, out);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent, outputFileContent);
}
@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copyRange(in, out, 1, 10);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}
@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(string, StandardCharsets.UTF_8, out);
assertTrue(outputFile.exists());
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
@Test
public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(byteArray, out);
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
Assert.assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream in = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(in);
String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
Assert.assertEquals(inputFileContent, content);
}
}

View File

@ -0,0 +1 @@
This file is merely for testing.

View File

@ -0,0 +1 @@
Should be copied to OutputStream.

View File

@ -41,7 +41,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version> <version>${powermock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
@ -65,7 +65,7 @@
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<!-- testing --> <!-- testing -->
<powermock.version>1.6.6</powermock.version> <powermock.version>1.7.0</powermock.version>
</properties> </properties>

View File

@ -53,6 +53,6 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- testing --> <!-- testing -->
<mockito.version>2.7.5</mockito.version> <mockito.version>2.8.9</mockito.version>
</properties> </properties>
</project> </project>

View File

@ -13,7 +13,7 @@
<name>mock-comparisons</name> <name>mock-comparisons</name>
<properties> <properties>
<mockito.version>1.10.19</mockito.version> <mockito.version>2.8.9</mockito.version>
<easymock.version>3.4</easymock.version> <easymock.version>3.4</easymock.version>
<jmockit.version>1.29</jmockit.version> <jmockit.version>1.29</jmockit.version>

View File

@ -7,7 +7,13 @@ import org.baeldung.mocks.testCase.UserForm;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.*; import org.mockito.ArgumentMatcher;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
public class LoginControllerIntegrationTest { public class LoginControllerIntegrationTest {
@ -41,50 +47,63 @@ public class LoginControllerIntegrationTest {
public void assertTwoMethodsHaveBeenCalled() { public void assertTwoMethodsHaveBeenCalled() {
UserForm userForm = new UserForm(); UserForm userForm = new UserForm();
userForm.username = "foo"; userForm.username = "foo";
Mockito.when(loginService.login(userForm)).thenReturn(true); Mockito.when(loginService.login(userForm))
.thenReturn(true);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("OK", login); Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm); Mockito.verify(loginService)
Mockito.verify(loginService).setCurrentUser("foo"); .login(userForm);
Mockito.verify(loginService)
.setCurrentUser("foo");
} }
@Test @Test
public void assertOnlyOneMethodHasBeenCalled() { public void assertOnlyOneMethodHasBeenCalled() {
UserForm userForm = new UserForm(); UserForm userForm = new UserForm();
userForm.username = "foo"; userForm.username = "foo";
Mockito.when(loginService.login(userForm)).thenReturn(false); Mockito.when(loginService.login(userForm))
.thenReturn(false);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("KO", login); Assert.assertEquals("KO", login);
Mockito.verify(loginService).login(userForm); Mockito.verify(loginService)
.login(userForm);
Mockito.verifyNoMoreInteractions(loginService); Mockito.verifyNoMoreInteractions(loginService);
} }
@Test @Test
public void mockExceptionThrowing() { public void mockExceptionThrowing() {
UserForm userForm = new UserForm(); UserForm userForm = new UserForm();
Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class); Mockito.when(loginService.login(userForm))
.thenThrow(IllegalArgumentException.class);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("ERROR", login); Assert.assertEquals("ERROR", login);
Mockito.verify(loginService).login(userForm); Mockito.verify(loginService)
.login(userForm);
Mockito.verifyZeroInteractions(loginService); Mockito.verifyZeroInteractions(loginService);
} }
@Test @Test
public void mockAnObjectToPassAround() { public void mockAnObjectToPassAround() {
UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock(); UserForm userForm = Mockito.when(Mockito.mock(UserForm.class)
Mockito.when(loginService.login(userForm)).thenReturn(true); .getUsername())
.thenReturn("foo")
.getMock();
Mockito.when(loginService.login(userForm))
.thenReturn(true);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("OK", login); Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm); Mockito.verify(loginService)
Mockito.verify(loginService).setCurrentUser("foo"); .login(userForm);
Mockito.verify(loginService)
.setCurrentUser("foo");
} }
@Test @Test
@ -92,19 +111,22 @@ public class LoginControllerIntegrationTest {
UserForm userForm = new UserForm(); UserForm userForm = new UserForm();
userForm.username = "foo"; userForm.username = "foo";
// default matcher // default matcher
Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true); Mockito.when(loginService.login(Mockito.any(UserForm.class)))
.thenReturn(true);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("OK", login); Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm); Mockito.verify(loginService)
.login(userForm);
// complex matcher // complex matcher
Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher<String>() { Mockito.verify(loginService)
@Override .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher<String>() {
public boolean matches(Object argument) { @Override
return argument instanceof String && ((String) argument).startsWith("foo"); public boolean matches(String argument) {
} return argument.startsWith("foo");
})); }
}));
} }
@Test @Test
@ -114,12 +136,14 @@ public class LoginControllerIntegrationTest {
UserForm userForm = new UserForm(); UserForm userForm = new UserForm();
userForm.username = "foo"; userForm.username = "foo";
// let service's login use implementation so let's mock DAO call // let service's login use implementation so let's mock DAO call
Mockito.when(loginDao.login(userForm)).thenReturn(1); Mockito.when(loginDao.login(userForm))
.thenReturn(1);
String login = loginController.login(userForm); String login = loginController.login(userForm);
Assert.assertEquals("OK", login); Assert.assertEquals("OK", login);
// verify mocked call // verify mocked call
Mockito.verify(spiedLoginService).setCurrentUser("foo"); Mockito.verify(spiedLoginService)
.setCurrentUser("foo");
} }
} }

View File

@ -28,13 +28,11 @@ import static org.mockserver.model.StringBody.exact;
public class MockServerLiveTest { public class MockServerLiveTest {
private static ClientAndProxy proxy;
private static ClientAndServer mockServer; private static ClientAndServer mockServer;
@BeforeClass @BeforeClass
public static void startProxy() { public static void startServer() {
mockServer = startClientAndServer(1080); mockServer = startClientAndServer(1080);
proxy = startClientAndProxy(1090);
} }
@ -169,8 +167,7 @@ public class MockServerLiveTest {
} }
@AfterClass @AfterClass
public static void stopProxy() { public static void stopServer() {
proxy.stop();
mockServer.stop(); mockServer.stop();
} }
} }

View File

@ -18,7 +18,7 @@
<!-- <gib.enabled>false</gib.enabled>--> <!-- <gib.enabled>false</gib.enabled>-->
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<mockito.version>1.10.19</mockito.version> <mockito.version>2.8.9</mockito.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version> <logback.version>1.1.7</logback.version>
@ -28,7 +28,6 @@
</properties> </properties>
<modules> <modules>
<module>spring-activiti</module>
<module>aws</module> <module>aws</module>
<module>akka-streams</module> <module>akka-streams</module>
<module>algorithms</module> <module>algorithms</module>
@ -94,6 +93,7 @@
<module>jws</module> <module>jws</module>
<module>libraries</module> <module>libraries</module>
<module>libraries-data</module>
<module>log-mdc</module> <module>log-mdc</module>
<module>log4j</module> <module>log4j</module>
<module>log4j2</module> <module>log4j2</module>
@ -128,6 +128,7 @@
<module>spark-java</module> <module>spark-java</module>
<!-- <module>spring-5</module>--> <!-- <module>spring-5</module>-->
<module>spring-5-mvc</module> <module>spring-5-mvc</module>
<module>spring-activiti</module>
<module>spring-akka</module> <module>spring-akka</module>
<module>spring-amqp</module> <module>spring-amqp</module>
<module>spring-all</module> <module>spring-all</module>

View File

@ -0,0 +1,43 @@
package com.baelding.rxjava.operator;
import rx.Observable.Operator;
import rx.Subscriber;
public class ToCleanString implements Operator<String, String> {
public static ToCleanString toCleanString() {
return new ToCleanString();
}
private ToCleanString() {
super();
}
@Override
public Subscriber<? super String> call(final Subscriber<? super String> subscriber) {
return new Subscriber<String>(subscriber) {
@Override
public void onCompleted() {
if (!subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
}
@Override
public void onError(Throwable t) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(t);
}
}
@Override
public void onNext(String item) {
if (!subscriber.isUnsubscribed()) {
final String result = item.replaceAll("[^A-Za-z0-9]", "");
subscriber.onNext(result);
}
}
};
}
}

View File

@ -0,0 +1,20 @@
package com.baelding.rxjava.operator;
import rx.Observable;
import rx.Observable.Transformer;
public class ToLength implements Transformer<String, Integer> {
public static ToLength toLength() {
return new ToLength();
}
private ToLength() {
super();
}
@Override
public Observable<Integer> call(Observable<String> source) {
return source.map(String::length);
}
}

View File

@ -34,7 +34,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() {
// given // given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create(); PublishSubject<Integer> source = PublishSubject.create();
source.observeOn(Schedulers.computation()).subscribe(testSubscriber); source.observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -50,7 +50,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() {
// given // given
TestSubscriber<Observable<Integer>> testSubscriber = new TestSubscriber<>(); TestSubscriber<Observable<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create(); PublishSubject<Integer> source = PublishSubject.create();
// when // when
source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber); source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -67,7 +67,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() { public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() {
// given // given
TestSubscriber<List<Integer>> testSubscriber = new TestSubscriber<>(); TestSubscriber<List<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create(); PublishSubject<Integer> source = PublishSubject.create();
// when // when
source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber); source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -84,7 +84,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() { public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() {
// given // given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create(); PublishSubject<Integer> source = PublishSubject.create();
// when // when
source.sample(100, TimeUnit.MILLISECONDS) source.sample(100, TimeUnit.MILLISECONDS)

View File

@ -0,0 +1,109 @@
package com.baeldung.rxjava;
import static com.baelding.rxjava.operator.ToCleanString.toCleanString;
import static com.baelding.rxjava.operator.ToLength.toLength;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import rx.Observable;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.Subscriber;
import com.baelding.rxjava.operator.ToCleanString;
import com.baelding.rxjava.operator.ToLength;
public class RxJavaCustomOperatorUnitTest {
@Test
public void whenUseCleanStringOperator_thenSuccess() {
final List<String> list = Arrays.asList("john_1", "tom-3");
final List<String> results = new ArrayList<>();
final Observable<String> observable = Observable.from(list)
.lift(toCleanString());
// when
observable.subscribe(results::add);
// then
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
assertThat(results, hasItems("john1", "tom3"));
}
@Test
public void whenUseToLengthOperator_thenSuccess() {
final List<String> list = Arrays.asList("john", "tom");
final List<Integer> results = new ArrayList<>();
final Observable<Integer> observable = Observable.from(list)
.compose(toLength());
// when
observable.subscribe(results::add);
// then
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
assertThat(results, hasItems(4, 3));
}
@Test
public void whenUseFunctionOperator_thenSuccess() {
final Operator<String, String> cleanStringFn = subscriber -> new Subscriber<String>(subscriber) {
@Override
public void onCompleted() {
if (!subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
}
@Override
public void onError(Throwable t) {
if (!subscriber.isUnsubscribed()) {
subscriber.onError(t);
}
}
@Override
public void onNext(String str) {
if (!subscriber.isUnsubscribed()) {
final String result = str.replaceAll("[^A-Za-z0-9]", "");
subscriber.onNext(result);
}
}
};
final List<String> results = new ArrayList<>();
Observable.from(Arrays.asList("ap_p-l@e", "or-an?ge"))
.lift(cleanStringFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
assertThat(results, hasItems("apple", "orange"));
}
@Test
public void whenUseFunctionTransformer_thenSuccess() {
final Transformer<String, Integer> toLengthFn = source -> source.map(String::length);
final List<Integer> results = new ArrayList<>();
Observable.from(Arrays.asList("apple", "orange"))
.compose(toLengthFn)
.subscribe(results::add);
assertThat(results, notNullValue());
assertThat(results, hasSize(2));
assertThat(results, hasItems(5, 6));
}
}

View File

@ -53,6 +53,23 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -1,9 +1,5 @@
package com.example.activitiwithspring; package com.example.activitiwithspring;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.activiti.engine.RuntimeService; import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService; import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task; import org.activiti.engine.task.Task;
@ -12,12 +8,15 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@RestController @RestController
public class ActivitiController { public class ActivitiController {
private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class); private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class);
@Autowired @Autowired
private RuntimeService runtimeService; private RuntimeService runtimeService;
@ -28,32 +27,30 @@ public class ActivitiController {
public String startProcess() { public String startProcess() {
runtimeService.startProcessInstanceByKey("my-process"); runtimeService.startProcessInstanceByKey("my-process");
return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery() return "Process started. Number of currently running process instances = " + runtimeService.createProcessInstanceQuery()
.count(); .count();
} }
@GetMapping("/get-tasks/{processInstanceId}") @GetMapping("/get-tasks/{processInstanceId}")
public List<TaskRepresentation> getTasks(@PathVariable String processInstanceId) { public List<TaskRepresentation> getTasks(@PathVariable String processInstanceId) {
List<Task> usertasks = taskService.createTaskQuery() List<Task> usertasks = taskService.createTaskQuery()
.processInstanceId(processInstanceId) .processInstanceId(processInstanceId)
.list(); .list();
List<TaskRepresentation> tasks = usertasks.stream().map(task -> { return usertasks.stream()
TaskRepresentation taskRepresentation = new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); .map(task -> new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()))
return taskRepresentation; .collect(Collectors.toList());
}).collect(Collectors.toList());
return tasks;
} }
@GetMapping("/complete-task-A/{processInstanceId}") @GetMapping("/complete-task-A/{processInstanceId}")
public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) { public TaskRepresentation completeTaskA(@PathVariable String processInstanceId) {
Task task = taskService.createTaskQuery() Task task = taskService.createTaskQuery()
.processInstanceId(processInstanceId) .processInstanceId(processInstanceId)
.singleResult(); .singleResult();
taskService.complete(task.getId()); taskService.complete(task.getId());
logger.info("Task completed"); logger.info("Task completed");
task = taskService.createTaskQuery() task = taskService.createTaskQuery()
.processInstanceId(processInstanceId) .processInstanceId(processInstanceId)
.singleResult(); .singleResult();
return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId()); return new TaskRepresentation(task.getId(), task.getName(), task.getProcessInstanceId());
} }

View File

@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class ActivitiWithSpringApplication { public class ActivitiWithSpringApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ActivitiWithSpringApplication.class, args); SpringApplication.run(ActivitiWithSpringApplication.class, args);
} }

View File

@ -1,10 +1,6 @@
package com.example.activitiwithspring; package com.example.activitiwithspring;
import static org.junit.Assert.assertEquals; import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.List;
import org.activiti.engine.RuntimeService; import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.runtime.ProcessInstance;
import org.junit.Before; import org.junit.Before;
@ -21,13 +17,16 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration @WebAppConfiguration
@SpringBootTest @SpringBootTest
public class ActivitiControllerTest { public class ActivitiControllerIntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerTest.class); private static final Logger logger = LoggerFactory.getLogger(ActivitiControllerIntegrationTest.class);
private MockMvc mockMvc; private MockMvc mockMvc;
@Autowired @Autowired
@ -39,10 +38,10 @@ public class ActivitiControllerTest {
@Before @Before
public void setUp() { public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac) this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.build(); .build();
for (ProcessInstance instance : runtimeService.createProcessInstanceQuery() for (ProcessInstance instance : runtimeService.createProcessInstanceQuery()
.list()) { .list()) {
runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes"); runtimeService.deleteProcessInstance(instance.getId(), "Reset Processes");
} }
} }
@ -51,21 +50,21 @@ public class ActivitiControllerTest {
public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception { public void givenProcess_whenStartProcess_thenIncreaseInProcessInstanceCount() throws Exception {
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 1", responseBody); assertEquals("Process started. Number of currently running process instances = 1", responseBody);
responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 2", responseBody); assertEquals("Process started. Number of currently running process instances = 2", responseBody);
responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
assertEquals("Process started. Number of currently running process instances = 3", responseBody); assertEquals("Process started. Number of currently running process instances = 3", responseBody);
} }
@ -73,19 +72,19 @@ public class ActivitiControllerTest {
public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception { public void givenProcess_whenProcessInstance_thenReceivedRunningTask() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
.andReturn() .andReturn()
.getResponse(); .getResponse();
ProcessInstance pi = runtimeService.createProcessInstanceQuery() ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.orderByProcessInstanceId() .orderByProcessInstanceId()
.desc() .desc()
.list() .list()
.get(0); .get(0);
logger.info("process instance = " + pi.getId()); logger.info("process instance = " + pi.getId());
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId())) String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/get-tasks/" + pi.getId()))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
List<TaskRepresentation> tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class)); List<TaskRepresentation> tasks = Arrays.asList(mapper.readValue(responseBody, TaskRepresentation[].class));
@ -98,19 +97,19 @@ public class ActivitiControllerTest {
public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception { public void givenProcess_whenCompleteTaskA_thenReceivedNextTask() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process")) this.mockMvc.perform(MockMvcRequestBuilders.get("/start-process"))
.andReturn() .andReturn()
.getResponse(); .getResponse();
ProcessInstance pi = runtimeService.createProcessInstanceQuery() ProcessInstance pi = runtimeService.createProcessInstanceQuery()
.orderByProcessInstanceId() .orderByProcessInstanceId()
.desc() .desc()
.list() .list()
.get(0); .get(0);
logger.info("process instance = " + pi.getId()); logger.info("process instance = " + pi.getId());
String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId())) String responseBody = this.mockMvc.perform(MockMvcRequestBuilders.get("/complete-task-A/" + pi.getId()))
.andReturn() .andReturn()
.getResponse() .getResponse()
.getContentAsString(); .getContentAsString();
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class); TaskRepresentation task = mapper.readValue(responseBody, TaskRepresentation.class);

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
public class ActivitiWithSpringApplicationTests { public class ActivitiWithSpringApplicationIntegrationTest {
@Test @Test
public void contextLoads() { public void contextLoads() {

View File

@ -40,6 +40,15 @@
<include>**/application*.properties</include> <include>**/application*.properties</include>
</includes> </includes>
</resource> </resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/application*.yml</exclude>
<exclude>**/application*.yaml</exclude>
<exclude>**/application*.properties</exclude>
</excludes>
</resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
@ -53,6 +62,14 @@
<useDefaultDelimiters>true</useDefaultDelimiters> <useDefaultDelimiters>true</useDefaultDelimiters>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<configuration>
<mainClass>com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp</mainClass>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -27,6 +27,10 @@ repositories {
mavenCentral() mavenCentral()
} }
springBoot {
executable = true
}
import org.apache.tools.ant.filters.ReplaceTokens import org.apache.tools.ant.filters.ReplaceTokens
processResources { processResources {
with copySpec { with copySpec {

View File

@ -30,4 +30,16 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -1,141 +1,147 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0" 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"> 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> <groupId>com.baeldung</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>spring-core</name> <name>spring-core</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId> <artifactId>mockito-all</artifactId>
<version>${mockito.version}</version> <version>${mockito.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId> <artifactId>spring-beans</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.inject</groupId> <groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId> <artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version> <version>${javax.inject.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>${lombok.version}</version> <version>${lombok.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId> <artifactId>spring-boot-starter</artifactId>
<version>1.5.2.RELEASE</version> <version>1.5.2.RELEASE</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId> <artifactId>spring-boot-test</artifactId>
<version>${mockito.spring.boot.version}</version> <version>${mockito.spring.boot.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
</dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId> <artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version> <version>${maven-war-plugin.version}</version>
<configuration> <configuration>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<profiles> <profiles>
<profile> <profile>
<id>integration</id> <id>integration</id>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<executions> <executions>
<execution> <execution>
<phase>integration-test</phase> <phase>integration-test</phase>
<goals> <goals>
<goal>test</goal> <goal>test</goal>
</goals> </goals>
<configuration> <configuration>
<excludes> <excludes>
<exclude>**/*LiveTest.java</exclude> <exclude>**/*LiveTest.java</exclude>
</excludes> </excludes>
<includes> <includes>
<include>**/*IntegrationTest.java</include> <include>**/*IntegrationTest.java</include>
</includes> </includes>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
<systemPropertyVariables> <systemPropertyVariables>
<test.mime>json</test.mime> <test.mime>json</test.mime>
</systemPropertyVariables> </systemPropertyVariables>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</profile> </profile>
</profiles> </profiles>
<properties> <properties>
<mockito.version>1.10.19</mockito.version> <mockito.version>1.10.19</mockito.version>
<mockito.spring.boot.version>1.4.4.RELEASE</mockito.spring.boot.version> <mockito.spring.boot.version>1.4.4.RELEASE</mockito.spring.boot.version>
<spring.version>4.3.4.RELEASE</spring.version> <spring.version>4.3.4.RELEASE</spring.version>
<javax.inject.version>1</javax.inject.version> <javax.inject.version>1</javax.inject.version>
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-war-plugin.version>2.6</maven-war-plugin.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
</properties> <commons.io.version>2.5</commons.io.version>
</properties>
<repositories> <repositories>
<repository> <repository>
<id>java.net</id> <id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url> <url>https://maven.java.net/content/repositories/releases/</url>
</repository> </repository>
</repositories> </repositories>
</project> </project>

View File

@ -0,0 +1,22 @@
package com.baeldung.streamutils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
public static String getStringFromInputStream(InputStream input) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "UTF-8");
return writer.toString();
}
public InputStream getNonClosingInputStream() throws IOException {
InputStream in = new FileInputStream("src/test/resources/input.txt");
return StreamUtils.nonClosing(in);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.streamutils;
import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
public InputStream getInputStream() {
return StreamUtils.emptyInput();
}
}

View File

@ -0,0 +1,100 @@
package com.baeldung.streamutils;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.util.StreamUtils;
import static com.baeldung.streamutils.CopyStream.getStringFromInputStream;
public class CopyStreamTest {
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copy(in, out);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(inputFileContent, outputFileContent);
}
@Test
public void whenCopyRangeOfInputStreamToOutputStream_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
StreamUtils.copyRange(in, out, 1, 10);
assertTrue(outputFile.exists());
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(inputFileContent.substring(1, 11), outputFileContent);
}
@Test
public void whenCopyStringToOutputStream_thenCorrect() throws IOException {
String string = "Should be copied to OutputStream.";
String outputFileName = "src/test/resources/output.txt";
File outputFile = new File(outputFileName);
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(string, StandardCharsets.UTF_8, out);
assertTrue(outputFile.exists());
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToString_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream is = new FileInputStream(inputFileName);
String content = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
assertEquals(inputFileContent, content);
}
@Test
public void whenCopyByteArrayToOutputStream_thenCorrect() throws IOException {
String outputFileName = "src/test/resources/output.txt";
String string = "Should be copied to OutputStream.";
byte[] byteArray = string.getBytes();
OutputStream out = new FileOutputStream("src/test/resources/output.txt");
StreamUtils.copy(byteArray, out);
String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
assertEquals(outputFileContent, string);
}
@Test
public void whenCopyInputStreamToByteArray_thenCorrect() throws IOException {
String inputFileName = "src/test/resources/input.txt";
InputStream in = new FileInputStream(inputFileName);
byte[] out = StreamUtils.copyToByteArray(in);
String content = new String(out);
String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
assertEquals(inputFileContent, content);
}
}

View File

@ -0,0 +1 @@
This file is merely for testing.

View File

@ -0,0 +1 @@
Should be copied to OutputStream.

View File

@ -15,14 +15,18 @@
</parent> </parent>
<properties> <properties>
<springframework.version>4.3.4.RELEASE</springframework.version> <springframework.version>4.3.10.RELEASE</springframework.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-war-plugin.version>3.1.0</maven-war-plugin.version>
<jstl.version>1.2</jstl.version> <jstl.version>1.2</jstl.version>
<javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version> <javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version> <javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version> <hibernate-validator.version>5.4.1.Final</hibernate-validator.version>
<deploy-path>enter-location-of-server</deploy-path> <deploy-path>enter-location-of-server</deploy-path>
<fileupload.version>1.3.2</fileupload.version> <fileupload.version>1.3.2</fileupload.version>
<java.version>1.8</java.version>
<org.thymeleaf-version>3.0.7.RELEASE</org.thymeleaf-version>
<groovy.version>2.4.12</groovy.version>
<freemarker.version>2.3.23</freemarker.version>
</properties> </properties>
<dependencies> <dependencies>
@ -79,6 +83,38 @@
<artifactId>commons-fileupload</artifactId> <artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version> <version>${fileupload.version}</version>
</dependency> </dependency>
<!-- thymeleaf dependencies -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- freemarker dependencies -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- groovy template dependency -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-templates</artifactId>
<version>${groovy.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<pluginManagement> <pluginManagement>
@ -94,6 +130,14 @@
<outputDirectory>${deploy-path}</outputDirectory> <outputDirectory>${deploy-path}</outputDirectory>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
<finalName>springMvcSimple</finalName> <finalName>springMvcSimple</finalName>

View File

@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.springmvcforms") @ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
class ApplicationConfiguration extends WebMvcConfigurerAdapter { class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Override @Override

View File

@ -0,0 +1,29 @@
package com.baeldung.spring.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
public class FreemarkerConfiguration {
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
return freeMarkerConfigurer;
}
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.spring.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer;
import org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
public class GroovyConfiguration {
@Bean
public GroovyMarkupConfigurer groovyMarkupConfigurer() {
GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer();
configurer.setResourceLoaderPath("/WEB-INF/views/");
return configurer;
}
@Bean
public GroovyMarkupViewResolver thymeleafViewResolver() {
GroovyMarkupViewResolver viewResolver = new GroovyMarkupViewResolver();
viewResolver.setSuffix(".tpl");
return viewResolver;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.spring.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
public class ThymeleafConfiguration {
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(thymeleafTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver thymeleafTemplateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
}

View File

@ -15,6 +15,9 @@ public class WebInitializer implements WebApplicationInitializer {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ApplicationConfiguration.class); ctx.register(ApplicationConfiguration.class);
//ctx.register(ThymeleafConfiguration.class);
//ctx.register(FreemarkerConfiguration.class);
//ctx.register(GroovyConfiguration.class);
ctx.setServletContext(container); ctx.setServletContext(container);
// Manage the lifecycle of the root application context // Manage the lifecycle of the root application context

View File

@ -0,0 +1,44 @@
package com.baeldung.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baeldung.spring.domain.User;
@Controller
public class UserController {
@GetMapping("/registration")
public String getRegistration(Model model) {
model.addAttribute("user", new User());
return "registration";
}
@GetMapping("/registration-thymeleaf")
public String getRegistrationThymeleaf(Model model) {
model.addAttribute("user", new User());
return "registration-thymeleaf";
}
@GetMapping("/registration-freemarker")
public String getRegistrationFreemarker(Model model) {
model.addAttribute("user", new User());
return "registration-freemarker";
}
@GetMapping("/registration-groovy")
public String getRegistrationGroovy(Model model) {
model.addAttribute("user", new User());
return "registration-groovy";
}
@PostMapping("/register")
@ResponseBody
public void register(User user){
System.out.println(user.getEmail());
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.spring.domain;
public class User {
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,15 @@
<#import "/spring.ftl" as spring/>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>User Registration</title>
</head>
<body>
<form action="register" method="post">
<@spring.bind path="user" />
Email:<@spring.formInput "user.email"/> <br />
Password:<@spring.formPasswordInput "user.password"/> <br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

View File

@ -0,0 +1,18 @@
yieldUnescaped '<!DOCTYPE html>'
html(lang:'en') {
head {
meta('http-equiv':'"Content-Type" content="text/html; charset=utf-8"')
title('User Registration')
}
body {
form (id:'userForm', action:'register', method:'post') {
label (for:'email', 'Email')
input (name:'email', type:'text', value:user.email?:'')
label (for:'password', 'Password')
input (name:'password', type:'password', value:user.password?:'')
div (class:'form-actions') {
input (type:'submit', value:'Submit')
}
}
}
}

View File

@ -0,0 +1,13 @@
<html>
<head>
<meta charset="ISO-8859-1" />
<title>User Registration</title>
</head>
<body>
<form action="#" th:action="@{/register}" th:object="${user}" method="post">
Email:<input type="text" th:field="*{email}" /> <br />
Password:<input type="password" th:field="*{password}" /> <br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

View File

@ -0,0 +1,18 @@
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form:form method="POST" modelAttribute="user" action="register">
<form:label path="email">Email: </form:label>
<form:input path="email" type="text"/>
<br />
<form:label path="password">Password: </form:label>
<form:input path="password" type="password" />
<br />
<input type="submit" value="Submit" />
</form:form>
</body>
</html>

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-servlet_RequestMappingHandlerAdapter.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -19,10 +19,10 @@
<param-value>org.baeldung.config</param-value> <param-value>org.baeldung.config</param-value>
</context-param> </context-param>
<listener> <!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </listener>
-->
<!-- Spring child --> <!-- Spring child -->
<servlet> <servlet>
<servlet-name>api</servlet-name> <servlet-name>api</servlet-name>

View File

@ -1,17 +1,14 @@
package org.baeldung.spring; package org.baeldung.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
@Configuration //@Configuration
//@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" }) //@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" })
@EnableWebSecurity //@EnableWebSecurity
@Profile("!https") //@Profile("!https")
public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter { public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
public RedirectionSecurityConfig() { public RedirectionSecurityConfig() {
@ -20,25 +17,23 @@ public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception { protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth auth.inMemoryAuthentication()
.inMemoryAuthentication() .withUser("user1")
.withUser("user1") .password("user1Pass")
.password("user1Pass") .roles("USER");
.roles("USER");
} }
@Override @Override
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
http http.authorizeRequests()
.authorizeRequests() .antMatchers("/login*")
.antMatchers("/login*") .permitAll()
.permitAll() .anyRequest()
.anyRequest() .authenticated()
.authenticated() .and()
.and() .formLogin()
.formLogin() .successHandler(new SavedRequestAwareAuthenticationSuccessHandler());
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler()); // .successHandler(new RefererAuthenticationSuccessHandler())
//.successHandler(new RefererAuthenticationSuccessHandler())
} }
} }

View File

@ -2,9 +2,10 @@ package org.baeldung.config;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication @SpringBootApplication
public class SpringOpenidApplication { public class SpringOpenidApplication extends SpringBootServletInitializer {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(SpringOpenidApplication.class, args); SpringApplication.run(SpringOpenidApplication.class, args);

View File

@ -71,4 +71,26 @@
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
</properties> </properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -1,18 +1,24 @@
package com.baeldung.vavr; package com.baeldung.vavr;
import io.vavr.MatchError;
import io.vavr.control.Option;
import org.junit.Test;
import static io.vavr.API.$; import static io.vavr.API.$;
import static io.vavr.API.Case; import static io.vavr.API.Case;
import static io.vavr.API.Match; import static io.vavr.API.Match;
import static io.vavr.API.run; import static io.vavr.API.run;
import static io.vavr.Predicates.*; import static io.vavr.Predicates.allOf;
import static io.vavr.Predicates.anyOf;
import static io.vavr.Predicates.instanceOf;
import static io.vavr.Predicates.is;
import static io.vavr.Predicates.isIn;
import static io.vavr.Predicates.isNotNull;
import static io.vavr.Predicates.isNull;
import static io.vavr.Predicates.noneOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test;
import io.vavr.MatchError;
import io.vavr.control.Option;
public class PatternMatchingUnitTest { public class PatternMatchingUnitTest {
@Test @Test
public void whenMatchesDefault_thenCorrect() { public void whenMatchesDefault_thenCorrect() {

View File

@ -9,7 +9,9 @@ import org.junit.Test;
import java.util.function.Predicate; import java.util.function.Predicate;
import static io.vavr.API.*; import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
public class PropertyBasedLongRunningUnitTest { public class PropertyBasedLongRunningUnitTest {

View File

@ -5,7 +5,9 @@ import io.vavr.Function1;
import io.vavr.Function2; import io.vavr.Function2;
import io.vavr.Function5; import io.vavr.Function5;
import io.vavr.Lazy; import io.vavr.Lazy;
import io.vavr.*; import io.vavr.Tuple;
import io.vavr.Tuple2;
import io.vavr.Tuple3;
import io.vavr.collection.List; import io.vavr.collection.List;
import io.vavr.collection.Seq; import io.vavr.collection.Seq;
import io.vavr.control.Option; import io.vavr.control.Option;
@ -13,23 +15,25 @@ import io.vavr.control.Try;
import io.vavr.control.Validation; import io.vavr.control.Validation;
import org.junit.Test; import org.junit.Test;
import com.baeldung.vavr.Person;
import com.baeldung.vavr.PersonValidator;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import static io.vavr.API.*; import static io.vavr.API.$;
import static org.junit.Assert.*; import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class VavrUnitTest { public class VavrUnitTest {
@Test @Test
public void givenList_whenSorts_thenCorrect() { public void givenList_whenSorts_thenCorrect() {
List<Integer> sortedList = List.of(3, 2, 1) List<Integer> sortedList = List.of(3, 2, 1)
.sorted(); .sorted();
} }
/* /*
@ -123,7 +127,7 @@ public class VavrUnitTest {
@Test @Test
public void whenCreatesFunction_thenCorrect0() { public void whenCreatesFunction_thenCorrect0() {
Function0<String> getClazzName = () -> this.getClass() Function0<String> getClazzName = () -> this.getClass()
.getName(); .getName();
String clazzName = getClazzName.apply(); String clazzName = getClazzName.apply();
assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName); assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName);
} }
@ -257,7 +261,7 @@ public class VavrUnitTest {
public void whenSumsJava8List_thenCorrect() { public void whenSumsJava8List_thenCorrect() {
// Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j); // Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j);
int sum = IntStream.of(1, 2, 3) int sum = IntStream.of(1, 2, 3)
.sum(); .sum();
assertEquals(6, sum); assertEquals(6, sum);
} }
@ -273,8 +277,8 @@ public class VavrUnitTest {
@Test @Test
public void whenSumsVavrList_thenCorrect() { public void whenSumsVavrList_thenCorrect() {
int sum = List.of(1, 2, 3) int sum = List.of(1, 2, 3)
.sum() .sum()
.intValue(); .intValue();
assertEquals(6, sum); assertEquals(6, sum);
} }
@ -307,21 +311,21 @@ public class VavrUnitTest {
int input = 2; int input = 2;
String output; String output;
switch (input) { switch (input) {
case 0: case 0:
output = "zero"; output = "zero";
break; break;
case 1: case 1:
output = "one"; output = "one";
break; break;
case 2: case 2:
output = "two"; output = "two";
break; break;
case 3: case 3:
output = "three"; output = "three";
break; break;
default: default:
output = "unknown"; output = "unknown";
break; break;
} }
assertEquals("two", output); assertEquals("two", output);
} }

View File

@ -1,17 +1,5 @@
package com.baeldung.vavr.collections; package com.baeldung.vavr.collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import io.vavr.Tuple; import io.vavr.Tuple;
import io.vavr.Tuple2; import io.vavr.Tuple2;
import io.vavr.collection.Array; import io.vavr.collection.Array;
@ -28,6 +16,17 @@ import io.vavr.collection.Stream;
import io.vavr.collection.TreeMap; import io.vavr.collection.TreeMap;
import io.vavr.collection.TreeSet; import io.vavr.collection.TreeSet;
import io.vavr.collection.Vector; import io.vavr.collection.Vector;
import org.junit.Test;
import java.util.Comparator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class CollectionAPIUnitTest { public class CollectionAPIUnitTest {
@ -234,7 +233,7 @@ public class CollectionAPIUnitTest {
.toJavaMap(i -> Tuple.of(i, Integer.valueOf(i))); .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i)));
assertEquals(new Integer(2), map.get("2")); assertEquals(new Integer(2), map.get("2"));
} }
@Test @Test
public void givenVavrList_whenCollected_thenCorrect() { public void givenVavrList_whenCollected_thenCorrect() {
java.util.Set<Integer> javaSet = List.of(1, 2, 3) java.util.Set<Integer> javaSet = List.of(1, 2, 3)

View File

@ -7,32 +7,32 @@ import static org.junit.Assert.assertEquals;
public class EitherUnitTest { public class EitherUnitTest {
@Test @Test
public void givenMarks_whenPassNumber_thenExpectNumber() { public void givenMarks_whenPassNumber_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(100); Either<String, Integer> result = EitherDemo.computeWithEither(100);
int marks = result.right() int marks = result.right()
.getOrElseThrow(x -> new IllegalStateException()); .getOrElseThrow(x -> new IllegalStateException());
assertEquals(100, marks); assertEquals(100, marks);
} }
@Test @Test
public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { public void givenMarks_whenFailNumber_thenExpectErrorMesssage() {
Either<String, Integer> result = EitherDemo.computeWithEither(50); Either<String, Integer> result = EitherDemo.computeWithEither(50);
String error = result.left() String error = result.left()
.getOrNull(); .getOrNull();
assertEquals("Marks not acceptable", error); assertEquals("Marks not acceptable", error);
} }
@Test @Test
public void givenPassMarks_whenModified_thenExpectNumber() { public void givenPassMarks_whenModified_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(90); Either<String, Integer> result = EitherDemo.computeWithEither(90);
int marks = result.right() int marks = result.right()
.map(x -> x * 2) .map(x -> x * 2)
.get(); .get();
assertEquals(180, marks); assertEquals(180, marks);
} }
} }

View File

@ -3,16 +3,18 @@ package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.ClientException; import com.baeldung.vavr.exception.handling.client.ClientException;
import com.baeldung.vavr.exception.handling.client.HttpClient; import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response; import com.baeldung.vavr.exception.handling.client.Response;
import com.baeldung.vavr.exception.handling.VavrTry;
import io.vavr.collection.Stream; import io.vavr.collection.Stream;
import io.vavr.control.Option; import io.vavr.control.Option;
import io.vavr.control.Try; import io.vavr.control.Try;
import org.junit.Test; import org.junit.Test;
import static io.vavr.API.*; import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.Predicates.instanceOf; import static io.vavr.Predicates.instanceOf;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class VavrTryUnitTest { public class VavrTryUnitTest {
@ -26,8 +28,8 @@ public class VavrTryUnitTest {
//when //when
Try<Response> response = new VavrTry(httpClient).getResponse(); Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response Integer chainedResult = response
.map(this::actionThatTakesResponse) .map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult); .getOrElse(defaultChainedResult);
Stream<String> stream = response.toStream().map(it -> it.id); Stream<String> stream = response.toStream().map(it -> it.id);
//then //then
@ -49,8 +51,8 @@ public class VavrTryUnitTest {
//when //when
Try<Response> response = new VavrTry(httpClient).getResponse(); Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response Integer chainedResult = response
.map(this::actionThatTakesResponse) .map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult); .getOrElse(defaultChainedResult);
Option<Response> optionalResponse = response.toOption(); Option<Response> optionalResponse = response.toOption();
//then //then
@ -70,9 +72,9 @@ public class VavrTryUnitTest {
//when //when
Try<Response> recovered = new VavrTry(httpClient).getResponse() Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of( .recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse) Case($(instanceOf(ClientException.class)), defaultResponse)
)); ));
//then //then
assertTrue(recovered.isFailure()); assertTrue(recovered.isFailure());
@ -92,10 +94,10 @@ public class VavrTryUnitTest {
//when //when
Try<Response> recovered = new VavrTry(httpClient).getResponse() Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of( .recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse), Case($(instanceOf(ClientException.class)), defaultResponse),
Case($(instanceOf(IllegalArgumentException.class)), defaultResponse) Case($(instanceOf(IllegalArgumentException.class)), defaultResponse)
)); ));
//then //then
assertTrue(recovered.isSuccess()); assertTrue(recovered.isSuccess());
@ -106,7 +108,7 @@ public class VavrTryUnitTest {
return response.id.hashCode(); return response.id.hashCode();
} }
public int actionThatTakesTryResponse(Try<Response> response, int defaultTransformation){ public int actionThatTakesTryResponse(Try<Response> response, int defaultTransformation) {
return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation)); return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation));
} }

View File

@ -3,18 +3,18 @@ package com.baeldung.vavr.repositories;
import com.baeldung.Application; import com.baeldung.Application;
import com.baeldung.repositories.VavrUserRepository; import com.baeldung.repositories.VavrUserRepository;
import com.baeldung.vavr.User; import com.baeldung.vavr.User;
import io.vavr.collection.Seq; import io.vavr.collection.Seq;
import io.vavr.control.Option; import io.vavr.control.Option;
import org.junit.Test;
import org.junit.Before; import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class) @SpringBootTest(classes = Application.class)

View File

@ -164,7 +164,7 @@
<commons-io.version>2.5</commons-io.version> <commons-io.version>2.5</commons-io.version>
<!-- testing --> <!-- testing -->
<mockito.version>2.2.26</mockito.version> <mockito.version>2.8.9</mockito.version>
<httpcore.version>4.4.1</httpcore.version> <httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version> <httpclient.version>4.5</httpclient.version>