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>
<sourceDirectory>src/docs/asciidoc</sourceDirectory>
<outputDirectory>target/docs/asciidoc</outputDirectory>
<attributes>
<pdf-stylesdir>${project.basedir}/src/themes</pdf-stylesdir>
<pdf-style>custom</pdf-style>
</attributes>
<backend>pdf</backend>
<doctype>book</doctype>
</configuration>
</plugin>
</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>
</profiles>
<properties>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
@ -391,7 +391,7 @@
<logback.version>1.1.7</logback.version>
<!-- util -->
<guava.version>21.0</guava.version>
<guava.version>22.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<bouncycastle.version>1.55</bouncycastle.version>
<commons-codec.version>1.10</commons-codec.version>
@ -408,7 +408,7 @@
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.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>
<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 {
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;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitTest {
@Test
public void givenCurrencyCode_whenString_thanExist() {
CurrencyUnit usd = Monetary.getCurrency("USD");
assertNotNull(usd);
assertEquals(usd.getCurrencyCode(), "USD");
assertEquals(usd.getNumericCode(), 840);
assertEquals(usd.getDefaultFractionDigits(), 2);
}
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
}
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
assertEquals("USD", usd.toString());
assertEquals("USD 200", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD 2.00000", fastmoneyof.toString());
}
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
assertTrue(oneDolar.equals(Money.of(1, "USD")));
}
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
oneDolar.divide(3);
fail(); // if no exception
}
@Test
public void givenAmounts_whenSummed_thanCorrect() {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@Test
public void givenArithmetic_whenStringified_thanEqualsAmount() {
CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money subtractedAmount = Money
.of(1, "USD")
.subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
assertEquals("USD", usd.toString());
assertEquals("USD 1", oneDolar.toString());
assertEquals("USD 200.5", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD -199.5", subtractedAmount.toString());
assertEquals("USD 0.25", multiplyAmount.toString());
assertEquals("USD 4", divideAmount.toString());
}
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
@Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR);
}
@Test
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted);
}
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 ¤")
.build());
String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString());
assertEquals("00001.00 US Dollar", customFormatted);
}
}
package com.baeldung.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.format.CurrencyStyle;
import org.junit.Ignore;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.UnknownCurrencyException;
import javax.money.convert.CurrencyConversion;
import javax.money.convert.MonetaryConversions;
import javax.money.format.AmountFormatQueryBuilder;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class JavaMoneyUnitManualTest {
@Test
public void givenCurrencyCode_whenString_thanExist() {
CurrencyUnit usd = Monetary.getCurrency("USD");
assertNotNull(usd);
assertEquals(usd.getCurrencyCode(), "USD");
assertEquals(usd.getNumericCode(), 840);
assertEquals(usd.getDefaultFractionDigits(), 2);
}
@Test(expected = UnknownCurrencyException.class)
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
Monetary.getCurrency("AAA");
}
@Test
public void givenAmounts_whenStringified_thanEquals() {
CurrencyUnit usd = Monetary.getCurrency("USD");
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200)
.create();
Money moneyof = Money.of(12, usd);
FastMoney fastmoneyof = FastMoney.of(2, usd);
assertEquals("USD", usd.toString());
assertEquals("USD 200", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD 2.00000", fastmoneyof.toString());
}
@Test
public void givenCurrencies_whenCompared_thanNotequal() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money oneEuro = Money.of(1, "EUR");
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
assertTrue(oneDolar.equals(Money.of(1, "USD")));
}
@Test(expected = ArithmeticException.class)
public void givenAmount_whenDivided_thanThrowsException() {
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
oneDolar.divide(3);
fail(); // if no exception
}
@Test
public void givenAmounts_whenSummed_thanCorrect() {
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
Money sumAmtCHF = (Money) monetaryAmounts
.stream()
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
assertEquals("CHF 111.35", sumAmtCHF.toString());
}
@Test
public void givenArithmetic_whenStringified_thanEqualsAmount() {
CurrencyUnit usd = Monetary.getCurrency("USD");
Money moneyof = Money.of(12, usd);
MonetaryAmount fstAmtUSD = Monetary
.getDefaultAmountFactory()
.setCurrency(usd)
.setNumber(200.50)
.create();
MonetaryAmount oneDolar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
Money subtractedAmount = Money
.of(1, "USD")
.subtract(fstAmtUSD);
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
MonetaryAmount divideAmount = oneDolar.divide(0.25);
assertEquals("USD", usd.toString());
assertEquals("USD 1", oneDolar.toString());
assertEquals("USD 200.5", fstAmtUSD.toString());
assertEquals("USD 12", moneyof.toString());
assertEquals("USD -199.5", subtractedAmount.toString());
assertEquals("USD 0.25", multiplyAmount.toString());
assertEquals("USD 4", divideAmount.toString());
}
@Test
public void givenAmount_whenRounded_thanEquals() {
MonetaryAmount fstAmtEUR = Monetary
.getDefaultAmountFactory()
.setCurrency("EUR")
.setNumber(1.30473908)
.create();
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
assertEquals("EUR 1.3", roundEUR.toString());
}
@Test
@Ignore("Currency providers are not always available")
public void givenAmount_whenConversion_thenNotNull() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(convertedAmountUSDtoEUR);
}
@Test
public void givenLocale_whenFormatted_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
String usFormatted = formatUSD.format(oneDollar);
assertEquals("USD 1", oneDollar.toString());
assertNotNull(formatUSD);
assertEquals("USD1.00", usFormatted);
}
@Test
public void givenAmount_whenCustomFormat_thanEquals() {
MonetaryAmount oneDollar = Monetary
.getDefaultAmountFactory()
.setCurrency("USD")
.setNumber(1)
.create();
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US)
.set(CurrencyStyle.NAME)
.set("pattern", "00000.00 <EFBFBD>")
.build());
String customFormatted = customFormat.format(oneDollar);
assertNotNull(customFormat);
assertEquals("USD 1", oneDollar.toString());
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());
}
}
}

View File

@ -11,6 +11,7 @@ import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.Scanner;
import org.junit.Test;
@ -105,6 +106,7 @@ public class JavaScannerUnitTest {
public void whenScanString_thenCorrect() throws IOException {
final String input = "Hello 1 F 3.5";
final Scanner scanner = new Scanner(input);
scanner.useLocale(Locale.US);
assertEquals("Hello", scanner.next());
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
###Relevant Articles:
### Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign)

View File

@ -1,12 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.feign</groupId>
<artifactId>feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<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)
- [Guide to the HyperLogLog Algorithm](http://www.baeldung.com/java-hyperloglog)
- [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.

View File

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

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 {
private NeuralNetwork ann = null;
private void print(String input, double output, double actual) {
System.out.println("Testing: " + input + " Expected: " + actual + " Result: " + output);
}
@Before
public void annInit() {
ann = NeurophXOR.trainNeuralNetwork(NeurophXOR.assembleNeuralNetwork());
@ -19,32 +23,36 @@ public class XORTest {
public void leftDisjunctTest() {
ann.setInput(0, 1);
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
public void rightDisjunctTest() {
ann.setInput(1, 0);
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
public void bothFalseConjunctTest() {
ann.setInput(0, 0);
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
public void bothTrueConjunctTest() {
ann.setInput(1, 1);
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
public void annClose() {
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>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
@ -65,7 +65,7 @@
<commons-lang3.version>3.5</commons-lang3.version>
<!-- testing -->
<powermock.version>1.6.6</powermock.version>
<powermock.version>1.7.0</powermock.version>
</properties>

View File

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

View File

@ -13,7 +13,7 @@
<name>mock-comparisons</name>
<properties>
<mockito.version>1.10.19</mockito.version>
<mockito.version>2.8.9</mockito.version>
<easymock.version>3.4</easymock.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.Before;
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 {
@ -41,50 +47,63 @@ public class LoginControllerIntegrationTest {
public void assertTwoMethodsHaveBeenCalled() {
UserForm userForm = new UserForm();
userForm.username = "foo";
Mockito.when(loginService.login(userForm)).thenReturn(true);
Mockito.when(loginService.login(userForm))
.thenReturn(true);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm);
Mockito.verify(loginService).setCurrentUser("foo");
Mockito.verify(loginService)
.login(userForm);
Mockito.verify(loginService)
.setCurrentUser("foo");
}
@Test
public void assertOnlyOneMethodHasBeenCalled() {
UserForm userForm = new UserForm();
userForm.username = "foo";
Mockito.when(loginService.login(userForm)).thenReturn(false);
Mockito.when(loginService.login(userForm))
.thenReturn(false);
String login = loginController.login(userForm);
Assert.assertEquals("KO", login);
Mockito.verify(loginService).login(userForm);
Mockito.verify(loginService)
.login(userForm);
Mockito.verifyNoMoreInteractions(loginService);
}
@Test
public void mockExceptionThrowing() {
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);
Assert.assertEquals("ERROR", login);
Mockito.verify(loginService).login(userForm);
Mockito.verify(loginService)
.login(userForm);
Mockito.verifyZeroInteractions(loginService);
}
@Test
public void mockAnObjectToPassAround() {
UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock();
Mockito.when(loginService.login(userForm)).thenReturn(true);
UserForm userForm = Mockito.when(Mockito.mock(UserForm.class)
.getUsername())
.thenReturn("foo")
.getMock();
Mockito.when(loginService.login(userForm))
.thenReturn(true);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm);
Mockito.verify(loginService).setCurrentUser("foo");
Mockito.verify(loginService)
.login(userForm);
Mockito.verify(loginService)
.setCurrentUser("foo");
}
@Test
@ -92,19 +111,22 @@ public class LoginControllerIntegrationTest {
UserForm userForm = new UserForm();
userForm.username = "foo";
// 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);
Assert.assertEquals("OK", login);
Mockito.verify(loginService).login(userForm);
Mockito.verify(loginService)
.login(userForm);
// complex matcher
Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher<String>() {
@Override
public boolean matches(Object argument) {
return argument instanceof String && ((String) argument).startsWith("foo");
}
}));
Mockito.verify(loginService)
.setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher<String>() {
@Override
public boolean matches(String argument) {
return argument.startsWith("foo");
}
}));
}
@Test
@ -114,12 +136,14 @@ public class LoginControllerIntegrationTest {
UserForm userForm = new UserForm();
userForm.username = "foo";
// let service's login use implementation so let's mock DAO call
Mockito.when(loginDao.login(userForm)).thenReturn(1);
Mockito.when(loginDao.login(userForm))
.thenReturn(1);
String login = loginController.login(userForm);
Assert.assertEquals("OK", login);
// 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 {
private static ClientAndProxy proxy;
private static ClientAndServer mockServer;
@BeforeClass
public static void startProxy() {
public static void startServer() {
mockServer = startClientAndServer(1080);
proxy = startClientAndProxy(1090);
}
@ -169,8 +167,7 @@ public class MockServerLiveTest {
}
@AfterClass
public static void stopProxy() {
proxy.stop();
public static void stopServer() {
mockServer.stop();
}
}

View File

@ -18,7 +18,7 @@
<!-- <gib.enabled>false</gib.enabled>-->
<junit.version>4.12</junit.version>
<org.hamcrest.version>1.3</org.hamcrest.version>
<mockito.version>1.10.19</mockito.version>
<mockito.version>2.8.9</mockito.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
@ -28,7 +28,6 @@
</properties>
<modules>
<module>spring-activiti</module>
<module>aws</module>
<module>akka-streams</module>
<module>algorithms</module>
@ -94,6 +93,7 @@
<module>jws</module>
<module>libraries</module>
<module>libraries-data</module>
<module>log-mdc</module>
<module>log4j</module>
<module>log4j2</module>
@ -128,6 +128,7 @@
<module>spark-java</module>
<!-- <module>spring-5</module>-->
<module>spring-5-mvc</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-amqp</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() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
PublishSubject<Integer> source = PublishSubject.create();
source.observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -50,7 +50,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() {
// given
TestSubscriber<Observable<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
PublishSubject<Integer> source = PublishSubject.create();
// when
source.window(500).observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -67,7 +67,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenBufferIsDefined_shouldNotThrowException() {
// given
TestSubscriber<List<Integer>> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
PublishSubject<Integer> source = PublishSubject.create();
// when
source.buffer(1024).observeOn(Schedulers.computation()).subscribe(testSubscriber);
@ -84,7 +84,7 @@ public class RxJavaBackpressureLongRunningUnitTest {
public void givenHotObservable_whenSkippingOperationIsDefined_shouldNotThrowException() {
// given
TestSubscriber<Integer> testSubscriber = new TestSubscriber<>();
PublishSubject<Integer> source = PublishSubject.<Integer> create();
PublishSubject<Integer> source = PublishSubject.create();
// when
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>
<artifactId>spring-boot-maven-plugin</artifactId>
</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>
</build>

View File

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

View File

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

View File

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

View File

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

View File

@ -40,6 +40,15 @@
<include>**/application*.properties</include>
</includes>
</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>
<plugins>
<plugin>
@ -53,6 +62,14 @@
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</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>
</build>

View File

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

View File

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

View File

@ -1,141 +1,147 @@
<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</groupId>
<artifactId>spring-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<groupId>com.baeldung</groupId>
<artifactId>spring-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-core</name>
<name>spring-core</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>${mockito.spring.boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>${javax.inject.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>${mockito.spring.boot.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</plugins>
</build>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<mockito.version>1.10.19</mockito.version>
<mockito.spring.boot.version>1.4.4.RELEASE</mockito.spring.boot.version>
<spring.version>4.3.4.RELEASE</spring.version>
<javax.inject.version>1</javax.inject.version>
<guava.version>20.0</guava.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<lombok.version>1.16.12</lombok.version>
</properties>
<properties>
<mockito.version>1.10.19</mockito.version>
<mockito.spring.boot.version>1.4.4.RELEASE</mockito.spring.boot.version>
<spring.version>4.3.4.RELEASE</spring.version>
<javax.inject.version>1</javax.inject.version>
<guava.version>20.0</guava.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<lombok.version>1.16.12</lombok.version>
<commons.io.version>2.5</commons.io.version>
</properties>
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
</repositories>
<repositories>
<repository>
<id>java.net</id>
<url>https://maven.java.net/content/repositories/releases/</url>
</repository>
</repositories>
</project>
</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>
<properties>
<springframework.version>4.3.4.RELEASE</springframework.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<springframework.version>4.3.10.RELEASE</springframework.version>
<maven-war-plugin.version>3.1.0</maven-war-plugin.version>
<jstl.version>1.2</jstl.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>
<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>
<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>
<dependencies>
@ -79,6 +83,38 @@
<artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version>
</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>
<build>
<pluginManagement>
@ -94,6 +130,14 @@
<outputDirectory>${deploy-path}</outputDirectory>
</configuration>
</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>
</pluginManagement>
<finalName>springMvcSimple</finalName>

View File

@ -12,7 +12,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.springmvcforms")
@ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" })
class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@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();
ctx.register(ApplicationConfiguration.class);
//ctx.register(ThymeleafConfiguration.class);
//ctx.register(FreemarkerConfiguration.class);
//ctx.register(GroovyConfiguration.class);
ctx.setServletContext(container);
// 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>
</context-param>
<listener>
<!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
-->
<!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>

View File

@ -1,17 +1,14 @@
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.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.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
@Configuration
//@Configuration
//@ImportResource({ "classpath:RedirectionWebSecurityConfig.xml" })
@EnableWebSecurity
@Profile("!https")
//@EnableWebSecurity
//@Profile("!https")
public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
public RedirectionSecurityConfig() {
@ -20,25 +17,23 @@ public class RedirectionSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user1")
.password("user1Pass")
.roles("USER");
auth.inMemoryAuthentication()
.withUser("user1")
.password("user1Pass")
.roles("USER");
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler());
//.successHandler(new RefererAuthenticationSuccessHandler())
http.authorizeRequests()
.antMatchers("/login*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler());
// .successHandler(new RefererAuthenticationSuccessHandler())
}
}

View File

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

View File

@ -71,4 +71,26 @@
<junit.version>4.12</junit.version>
</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>

View File

@ -1,18 +1,24 @@
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.Case;
import static io.vavr.API.Match;
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.assertTrue;
import org.junit.Test;
import io.vavr.MatchError;
import io.vavr.control.Option;
public class PatternMatchingUnitTest {
@Test
public void whenMatchesDefault_thenCorrect() {

View File

@ -9,7 +9,9 @@ import org.junit.Test;
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 {

View File

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

View File

@ -1,17 +1,5 @@
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.Tuple2;
import io.vavr.collection.Array;
@ -28,6 +16,17 @@ import io.vavr.collection.Stream;
import io.vavr.collection.TreeMap;
import io.vavr.collection.TreeSet;
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 {
@ -234,7 +233,7 @@ public class CollectionAPIUnitTest {
.toJavaMap(i -> Tuple.of(i, Integer.valueOf(i)));
assertEquals(new Integer(2), map.get("2"));
}
@Test
public void givenVavrList_whenCollected_thenCorrect() {
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 {
@Test
public void givenMarks_whenPassNumber_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(100);
int marks = result.right()
.getOrElseThrow(x -> new IllegalStateException());
@Test
public void givenMarks_whenPassNumber_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(100);
int marks = result.right()
.getOrElseThrow(x -> new IllegalStateException());
assertEquals(100, marks);
}
assertEquals(100, marks);
}
@Test
public void givenMarks_whenFailNumber_thenExpectErrorMesssage() {
Either<String, Integer> result = EitherDemo.computeWithEither(50);
String error = result.left()
@Test
public void givenMarks_whenFailNumber_thenExpectErrorMesssage() {
Either<String, Integer> result = EitherDemo.computeWithEither(50);
String error = result.left()
.getOrNull();
assertEquals("Marks not acceptable", error);
}
assertEquals("Marks not acceptable", error);
}
@Test
public void givenPassMarks_whenModified_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(90);
int marks = result.right()
@Test
public void givenPassMarks_whenModified_thenExpectNumber() {
Either<String, Integer> result = EitherDemo.computeWithEither(90);
int marks = result.right()
.map(x -> x * 2)
.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.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
import com.baeldung.vavr.exception.handling.VavrTry;
import io.vavr.collection.Stream;
import io.vavr.control.Option;
import io.vavr.control.Try;
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 org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class VavrTryUnitTest {
@ -26,8 +28,8 @@ public class VavrTryUnitTest {
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Stream<String> stream = response.toStream().map(it -> it.id);
//then
@ -49,8 +51,8 @@ public class VavrTryUnitTest {
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Option<Response> optionalResponse = response.toOption();
//then
@ -70,9 +72,9 @@ public class VavrTryUnitTest {
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse)
));
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse)
));
//then
assertTrue(recovered.isFailure());
@ -92,10 +94,10 @@ public class VavrTryUnitTest {
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse),
Case($(instanceOf(IllegalArgumentException.class)), defaultResponse)
));
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse),
Case($(instanceOf(IllegalArgumentException.class)), defaultResponse)
));
//then
assertTrue(recovered.isSuccess());
@ -106,7 +108,7 @@ public class VavrTryUnitTest {
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));
}

View File

@ -3,18 +3,18 @@ package com.baeldung.vavr.repositories;
import com.baeldung.Application;
import com.baeldung.repositories.VavrUserRepository;
import com.baeldung.vavr.User;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
import org.junit.Test;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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)
@SpringBootTest(classes = Application.class)

View File

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