diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index 989f6e5354..a602cd11b9 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -35,7 +35,12 @@ src/docs/asciidoc target/docs/asciidoc + + ${project.basedir}/src/themes + custom + pdf + book diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/asciidoctor/src/docs/asciidoc/test.adoc index 5a86a00440..fec1f73584 100644 --- a/asciidoctor/src/docs/asciidoc/test.adoc +++ b/asciidoctor/src/docs/asciidoc/test.adoc @@ -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#. \ No newline at end of file + += 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] diff --git a/asciidoctor/src/themes/custom-theme.yml b/asciidoctor/src/themes/custom-theme.yml new file mode 100644 index 0000000000..a3c8c00510 --- /dev/null +++ b/asciidoctor/src/themes/custom-theme.yml @@ -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}' \ No newline at end of file diff --git a/core-java/pom.xml b/core-java/pom.xml index ee0d6b4b4a..73b1c22ed8 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -382,7 +382,7 @@ - + 2.8.5 @@ -391,7 +391,7 @@ 1.1.7 - 21.0 + 22.0 3.5 1.55 1.10 @@ -408,7 +408,7 @@ 1.3 4.12 - 1.10.19 + 2.8.9 3.6.1 1.7.0 diff --git a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java index dd80a7971c..a9b92d9f4a 100644 --- a/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java +++ b/core-java/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierExample.java @@ -21,3 +21,4 @@ public class CyclicBarrierExample { } } } + diff --git a/core-java/src/main/java/com/baeldung/hashcode/application/Application.java b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java new file mode 100644 index 0000000000..08c670c82f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashcode/application/Application.java @@ -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 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"); + } + } +} diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java new file mode 100644 index 0000000000..a976233562 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java @@ -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 +} diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java new file mode 100644 index 0000000000..dcd853f451 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java @@ -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()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java new file mode 100644 index 0000000000..01f6085d7e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java @@ -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()); + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java index 3c2d9904d4..0a0993a0d7 100644 --- a/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java +++ b/core-java/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java @@ -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()); } } diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java rename to core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index 8948d1ebf7..fe2747bcee 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -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 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 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); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java new file mode 100644 index 0000000000..69b0b6d3ef --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamToImmutableTest.java @@ -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 givenList = Arrays.asList("a", "b", "c"); + List result = givenList.stream() + .collect(collectingAndThen(toSet(), ImmutableList::copyOf)); + + System.out.println(result.getClass()); + } + + @Test + public void whenUsingCollectingToUnmodifiableList_thenSuccess() { + List givenList = new ArrayList<>(Arrays.asList("a", "b", "c")); + List result = givenList.stream() + .collect(collectingAndThen(toList(), Collections::unmodifiableList)); + + System.out.println(result.getClass()); + } + + @Test + public void whenCollectToImmutableList_thenSuccess() { + List list = IntStream.range(0, 9) + .boxed() + .collect(ImmutableList.toImmutableList()); + + System.out.println(list.getClass()); + } + + @Test + public void whenCollectToMyImmutableListCollector_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList()); + + System.out.println(result.getClass()); + } + + @Test + public void whenPassingSupplier_thenSuccess() { + List givenList = Arrays.asList("a", "b", "c", "d"); + List result = givenList.stream() + .collect(MyImmutableListCollector.toImmutableList(LinkedList::new)); + + System.out.println(result.getClass()); + } +} diff --git a/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java new file mode 100644 index 0000000000..cf6b3601c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java @@ -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 > Collector> toImmutableList(Supplier supplier) { + return Collector.of(supplier, List::add, (left, right) -> { + left.addAll(right); + return left; + }, Collections::unmodifiableList); + } + + public static Collector, List> toImmutableList() { + return toImmutableList(ArrayList::new); + } + +} diff --git a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java index ad8de82e1f..7b5f781620 100644 --- a/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java @@ -41,4 +41,4 @@ public class CustomTemporalAdjusterTest { assertEquals(fourteenDaysAfterDate, result.toString()); } -} +} \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java index 5af286dbca..1c16a5d435 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaScannerUnitTest.java @@ -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()); diff --git a/feign/README.md b/feign/README.md index 149f7320d9..4d6964a73a 100644 --- a/feign/README.md +++ b/feign/README.md @@ -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) diff --git a/feign/pom.xml b/feign/pom.xml index 9c3868c82f..78e1bbcf4c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -1,12 +1,9 @@ - + 4.0.0 com.baeldung.feign feign-client - 1.0.0-SNAPSHOT com.baeldung diff --git a/grpc/pom.xml b/grpc/pom.xml new file mode 100644 index 0000000000..074075b5cc --- /dev/null +++ b/grpc/pom.xml @@ -0,0 +1,74 @@ + + 4.0.0 + + grpc + grpc-demo + 0.0.1-SNAPSHOT + jar + + grpc-demo + http://maven.apache.org + + + UTF-8 + 1.5.0 + + + + + io.grpc + grpc-netty + ${io.grpc.version} + + + io.grpc + grpc-protobuf + ${io.grpc.version} + + + io.grpc + grpc-stub + ${io.grpc.version} + + + junit + junit + 4.12 + test + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + + com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier} + + grpc-java + + io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier} + + + + + + compile + compile-custom + + + + + + + diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java new file mode 100644 index 0000000000..1a1809387f --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java @@ -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(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java new file mode 100644 index 0000000000..8a2b94e53b --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/GrpcServer.java @@ -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(); + } +} diff --git a/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java new file mode 100644 index 0000000000..b08ad02c97 --- /dev/null +++ b/grpc/src/main/java/org/baeldung/grpc/server/HelloServiceImpl.java @@ -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 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(); + } +} diff --git a/grpc/src/main/proto/HelloService.proto b/grpc/src/main/proto/HelloService.proto new file mode 100644 index 0000000000..4f53191ab9 --- /dev/null +++ b/grpc/src/main/proto/HelloService.proto @@ -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); +} diff --git a/jooby/conf/application.conf b/jooby/conf/application.conf new file mode 100644 index 0000000000..2f89e0eb6b --- /dev/null +++ b/jooby/conf/application.conf @@ -0,0 +1,2 @@ +#application.secret = 2o128940921eo298e21 +#db = /url/to/the/datastore \ No newline at end of file diff --git a/jooby/conf/logback.xml b/jooby/conf/logback.xml new file mode 100644 index 0000000000..50733ee6d6 --- /dev/null +++ b/jooby/conf/logback.xml @@ -0,0 +1,42 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + log/jooby.log + + log/jooby.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + log/access.log + + log/access.%d{yyyy-MM-dd}.log + 1mb + 7 + + + + %msg%n + + + + + + + + + + + diff --git a/jooby/pom.xml b/jooby/pom.xml new file mode 100644 index 0000000000..1935c646ee --- /dev/null +++ b/jooby/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + jooby + com.baeldung.jooby + 1.0 + jooby + + + org.jooby + modules + 1.1.3 + + + + 1.1.3 + com.baeldung.jooby.App + + + + + org.jooby + jooby-netty + + + org.jooby + jooby-jedis + 1.1.3 + + + ch.qos.logback + logback-classic + + + junit + junit + test + + + io.rest-assured + rest-assured + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + + diff --git a/jooby/public/form.html b/jooby/public/form.html new file mode 100644 index 0000000000..a23620812a --- /dev/null +++ b/jooby/public/form.html @@ -0,0 +1,17 @@ + + + + +Insert title here + + +
+ + + + + + +
+ + \ No newline at end of file diff --git a/jooby/public/welcome.html b/jooby/public/welcome.html new file mode 100644 index 0000000000..cd21fb1988 --- /dev/null +++ b/jooby/public/welcome.html @@ -0,0 +1,10 @@ + + + + +Insert title here + + +i m welcomed + + \ No newline at end of file diff --git a/jooby/src/etc/stork.yml b/jooby/src/etc/stork.yml new file mode 100644 index 0000000000..f2f2790cd1 --- /dev/null +++ b/jooby/src/etc/stork.yml @@ -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 /run with +# the name of "-java" so that commands like "ps" will make it +# easier to find your app +symlink_java: true diff --git a/jooby/src/main/java/com/baeldung/jooby/App.java b/jooby/src/main/java/com/baeldung/jooby/App.java new file mode 100644 index 0000000000..94a24048c2 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/App.java @@ -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); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java new file mode 100644 index 0000000000..2c4a1038b5 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/bean/Employee.java @@ -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; + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java new file mode 100644 index 0000000000..a2c51bae70 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/GetController.java @@ -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()); + } + +} diff --git a/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java new file mode 100644 index 0000000000..df00e47da5 --- /dev/null +++ b/jooby/src/main/java/com/baeldung/jooby/mvc/PostController.java @@ -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"; + } + +} diff --git a/jooby/src/test/java/com/baeldung/jooby/AppTest.java b/jooby/src/test/java/com/baeldung/jooby/AppTest.java new file mode 100644 index 0000000000..af2626c046 --- /dev/null +++ b/jooby/src/test/java/com/baeldung/jooby/AppTest.java @@ -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); + } + +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt new file mode 100644 index 0000000000..9ea9f027fc --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt @@ -0,0 +1,35 @@ +package com.baeldung.kotlin.delegates + +val data = arrayOf>( + 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) +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt new file mode 100644 index 0000000000..c1c0f8823c --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt @@ -0,0 +1,13 @@ +package com.baeldung.kotlin.delegates + +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty + +class DatabaseDelegate(private val field: String, private val id: Int) : ReadWriteProperty { + 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) + } +} diff --git a/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt new file mode 100644 index 0000000000..7788305ea1 --- /dev/null +++ b/kotlin/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt @@ -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) +} diff --git a/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt new file mode 100644 index 0000000000..fc50730dfa --- /dev/null +++ b/kotlin/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt @@ -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 + } +} diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml new file mode 100644 index 0000000000..94a9ca43f4 --- /dev/null +++ b/libraries-data/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + libraries-data + libraries-data + jar + + + com.esotericsoftware + kryo + ${kryo.version} + + + + 4.0.1 + + \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java new file mode 100644 index 0000000000..0e125e48a9 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/ComplexClass.java @@ -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; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/Person.java b/libraries-data/src/main/java/com/baeldung/kryo/Person.java new file mode 100644 index 0000000000..f9be5cfd62 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/Person.java @@ -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(); + } + +} diff --git a/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java new file mode 100644 index 0000000000..f5d01509a6 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/kryo/PersonSerializer.java @@ -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 { + + @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 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; + } + +} diff --git a/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java new file mode 100644 index 0000000000..c124ca618d --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/kryo/KryoUnitTest.java @@ -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"); + } + +} diff --git a/libraries/README.md b/libraries/README.md index f0484ec710..86baa39045 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -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. diff --git a/libraries/pom.xml b/libraries/pom.xml index a655f5267a..efdf20423a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -1,497 +1,501 @@ - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - libraries - libraries - - - - org.apache.maven.plugins - maven-dependency-plugin - - - org.apache.felix - maven-bundle-plugin - 3.3.0 - maven-plugin - - - - true - - - maven-failsafe-plugin - 2.20 - - - chromedriver - - - - - net.serenity-bdd.maven.plugins - serenity-maven-plugin - ${serenity.plugin.version} - - - serenity-reports - post-integration-test - - aggregate - - - - - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - false - - - - - process-classes - - enhance - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.0.2 - - - **/log4j.properties - - - - com.baeldung.neuroph.NeurophXOR - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18.1 - - - test - test - - test - - - - test/java/com/baeldung/neuroph/XORTest.java - - - - - - - - - - - - org.beykery - neuroph - ${neuroph.version} - - - - cglib - cglib - ${cglib.version} - - - commons-beanutils - commons-beanutils - ${commons-beanutils.version} - - - org.apache.commons - commons-lang3 - ${commons-lang.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.apache.commons - commons-collections4 - ${commons.collections.version} - - - org.jasypt - jasypt - ${jasypt.version} - - - org.javatuples - javatuples - ${javatuples.version} - - - org.javassist - javassist - ${javaassist.version} - - - - org.assertj - assertj-core - ${assertj.version} - - - org.skyscreamer - jsonassert - ${jsonassert.version} - - - org.javers - javers-core - ${javers.version} - - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - commons-io - commons-io - ${commons.io.version} - - - commons-chain - commons-chain - ${commons-chain.version} - - - commons-dbutils - commons-dbutils - ${commons.dbutils.version} - - - org.apache.flink - flink-core - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-java - ${flink.version} - - - commons-logging - commons-logging - - - - - org.apache.flink - flink-test-utils_2.10 - ${flink.version} - test - - - org.apache.commons - commons-math3 - 3.6.1 - - - net.serenity-bdd - serenity-core - ${serenity.version} - test - - - net.serenity-bdd - serenity-junit - ${serenity.version} - test - - - net.serenity-bdd - serenity-jbehave - ${serenity.jbehave.version} - test - - - net.serenity-bdd - serenity-rest-assured - ${serenity.version} - test - - - net.serenity-bdd - serenity-jira-requirements-provider - ${serenity.jira.version} - test - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - org.datanucleus - javax.jdo - 3.2.0-m6 - - - org.datanucleus - datanucleus-core - 5.1.0-m1 - - - org.datanucleus - datanucleus-api-jdo - 5.1.0-m1 - - - org.datanucleus - datanucleus-rdbms - 5.1.0-m1 - - - org.datanucleus - datanucleus-maven-plugin - 5.0.2 - - - org.datanucleus - datanucleus-xml - 5.0.0-release - - - net.openhft - chronicle - 3.6.4 - - - org.springframework - spring-web - 4.3.8.RELEASE - - - net.serenity-bdd - serenity-spring - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay - ${serenity.version} - test - - - net.serenity-bdd - serenity-screenplay-webdriver - ${serenity.version} - test - - - io.rest-assured - spring-mock-mvc - 3.0.3 - test - - - org.multiverse - multiverse-core - ${multiverse.version} - - - com.zaxxer - HikariCP - 2.6.1 - compile - - - com.h2database - h2 - ${h2.version} - - - pl.pragmatists - JUnitParams - ${jUnitParams.version} - test - - - org.quartz-scheduler - quartz - 2.3.0 - - - one.util - streamex - 0.6.5 - - - org.jooq - jool - 0.9.12 - - - org.openjdk.jmh - jmh-core - 1.19 - - - org.openjdk.jmh - jmh-generator-annprocess - 1.19 - - - io.netty - netty-all - ${netty.version} - - - junit - junit - ${junit.version} - test - - - info.debatty - java-lsh - ${java-lsh.version} - - - au.com.dius - pact-jvm-consumer-junit_2.11 - ${pact.version} - test - - - org.codehaus.groovy - groovy-all - 2.4.10 - - - org.awaitility - awaitility - ${awaitility.version} - test - - - org.awaitility - awaitility-proxy - ${awaitility.version} - test - - - org.hamcrest - java-hamcrest - ${org.hamcrest.java-hamcrest.version} - test - - - net.agkn - hll - ${hll.version} - - - net.bytebuddy - byte-buddy - ${bytebuddy.version} - - - net.bytebuddy - byte-buddy-agent - ${bytebuddy.version} - - - org.pcollections - pcollections - ${pcollections.version} - - - - 0.7.0 - 3.2.4 - 3.5 - 1.1 - 1.9.3 - 1.2 - 1.9.2 - 1.2 - 3.21.0-GA - 3.6.2 - 1.5.0 - 3.1.0 - 9.4.3.v20170317 - 4.5.3 - 2.5 - 1.6 - 1.4.196 - 9.4.2.v20170220 - 4.5.3 - 2.5 - 1.2.0 - 2.8.5 - 2.92 - 1.4.0 - 1.24.0 - 1.1.3-rc.5 - 1.4.0 - 1.1.0 - 4.1.10.Final - 4.1 - 4.12 - 0.10 - 3.5.0 - 3.0.0 - 2.0.0.0 - 1.6.0 - 1.7.1 - 2.1.2 - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + libraries + libraries + + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.apache.felix + maven-bundle-plugin + 3.3.0 + maven-plugin + + + true + + + maven-failsafe-plugin + 2.20 + + + chromedriver + + + + + net.serenity-bdd.maven.plugins + serenity-maven-plugin + ${serenity.plugin.version} + + + serenity-reports + post-integration-test + + aggregate + + + + + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + **/log4j.properties + + + + com.baeldung.neuroph.NeurophXOR + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18.1 + + + test + test + + test + + + + test/java/com/baeldung/neuroph/XORTest.java + + + + + + + + + + + + org.beykery + neuroph + ${neuroph.version} + + + + cglib + cglib + ${cglib.version} + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + + + org.apache.commons + commons-lang3 + ${commons-lang.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.apache.commons + commons-collections4 + ${commons.collections.version} + + + org.jasypt + jasypt + ${jasypt.version} + + + org.javatuples + javatuples + ${javatuples.version} + + + org.javassist + javassist + ${javaassist.version} + + + + org.assertj + assertj-core + ${assertj.version} + + + org.skyscreamer + jsonassert + ${jsonassert.version} + + + org.javers + javers-core + ${javers.version} + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + io.specto + hoverfly-java + 0.8.0 + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + commons-io + commons-io + ${commons.io.version} + + + commons-chain + commons-chain + ${commons-chain.version} + + + commons-dbutils + commons-dbutils + ${commons.dbutils.version} + + + org.apache.flink + flink-core + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-java + ${flink.version} + + + commons-logging + commons-logging + + + + + org.apache.flink + flink-test-utils_2.10 + ${flink.version} + test + + + org.apache.commons + commons-math3 + 3.6.1 + + + net.serenity-bdd + serenity-core + ${serenity.version} + test + + + net.serenity-bdd + serenity-junit + ${serenity.version} + test + + + net.serenity-bdd + serenity-jbehave + ${serenity.jbehave.version} + test + + + net.serenity-bdd + serenity-rest-assured + ${serenity.version} + test + + + net.serenity-bdd + serenity-jira-requirements-provider + ${serenity.jira.version} + test + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + org.datanucleus + javax.jdo + 3.2.0-m6 + + + org.datanucleus + datanucleus-core + 5.1.0-m1 + + + org.datanucleus + datanucleus-api-jdo + 5.1.0-m1 + + + org.datanucleus + datanucleus-rdbms + 5.1.0-m1 + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + + org.datanucleus + datanucleus-xml + 5.0.0-release + + + net.openhft + chronicle + 3.6.4 + + + org.springframework + spring-web + 4.3.8.RELEASE + + + net.serenity-bdd + serenity-spring + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay + ${serenity.version} + test + + + net.serenity-bdd + serenity-screenplay-webdriver + ${serenity.version} + test + + + io.rest-assured + spring-mock-mvc + 3.0.3 + test + + + org.multiverse + multiverse-core + ${multiverse.version} + + + com.zaxxer + HikariCP + 2.6.1 + compile + + + com.h2database + h2 + ${h2.version} + + + pl.pragmatists + JUnitParams + ${jUnitParams.version} + test + + + org.quartz-scheduler + quartz + 2.3.0 + + + one.util + streamex + 0.6.5 + + + org.jooq + jool + 0.9.12 + + + org.openjdk.jmh + jmh-core + 1.19 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.19 + + + io.netty + netty-all + ${netty.version} + + + junit + junit + ${junit.version} + test + + + info.debatty + java-lsh + ${java-lsh.version} + + + au.com.dius + pact-jvm-consumer-junit_2.11 + ${pact.version} + test + + + org.codehaus.groovy + groovy-all + 2.4.10 + + + org.awaitility + awaitility + ${awaitility.version} + test + + + org.awaitility + awaitility-proxy + ${awaitility.version} + test + + + org.hamcrest + java-hamcrest + ${org.hamcrest.java-hamcrest.version} + test + + + net.agkn + hll + ${hll.version} + + + net.bytebuddy + byte-buddy + ${bytebuddy.version} + + + net.bytebuddy + byte-buddy-agent + ${bytebuddy.version} + + + org.pcollections + pcollections + ${pcollections.version} + + + + 0.7.0 + 3.2.4 + 3.5 + 1.1 + 1.9.3 + 1.2 + 1.9.2 + 1.2 + 3.21.0-GA + 3.6.2 + 1.5.0 + 3.1.0 + 9.4.3.v20170317 + 4.5.3 + 2.5 + 1.6 + 1.4.196 + 9.4.2.v20170220 + 4.5.3 + 2.5 + 1.2.0 + 2.8.5 + 2.92 + 1.4.0 + 1.24.0 + 1.1.3-rc.5 + 1.4.0 + 1.1.0 + 4.1.10.Final + 4.1 + 4.12 + 0.10 + 3.5.0 + 3.0.0 + 2.0.0.0 + 1.6.0 + 1.7.1 + 2.1.2 + diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..430759f3a0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -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); + } +} diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..6ee4a1ef3a --- /dev/null +++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -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(); + } +} diff --git a/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java new file mode 100644 index 0000000000..bdaf4d7bd9 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/hoverfly/HoverflyApiTest.java @@ -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("2John")) + .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 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 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 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 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 putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/1")) + .body("{\"id\":\"1\",\"name\":\"Trevor\"}"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } + + @Test + public void givenPostStudent_whenBodyRequestMatcherXml_thenResponseContainsEqualXml() throws URISyntaxException { + final ResponseEntity postResponse = restTemplate.postForEntity( + "http://www.baeldung.com/api/student", "2John", Void.class); + + assertEquals(HttpStatus.OK, postResponse.getStatusCode()); + } + + + @Test + public void givenPutStudent_whenXPathMatcher_thenRequestXmlContainsElementInXPath() throws URISyntaxException { + RequestEntity putRequest = RequestEntity + .put(new URI("http://www.baeldung.com/api/student/2")) + .body("" + + "2Monica"); + + ResponseEntity putResponse = restTemplate.exchange(putRequest, String.class); + assertEquals(HttpStatus.OK, putResponse.getStatusCode()); + } +} diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java index 063c57195b..4a6ecf8e46 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORTest.java +++ b/libraries/src/test/java/com/baeldung/neuroph/XORTest.java @@ -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; } -} +} \ No newline at end of file diff --git a/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9a65075e5b --- /dev/null +++ b/libraries/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -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); + } + +} diff --git a/libraries/src/test/resources/input.txt b/libraries/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/libraries/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/libraries/src/test/resources/output.txt b/libraries/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/libraries/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file diff --git a/mockito/pom.xml b/mockito/pom.xml index c77d42f97d..19dd2f6468 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -41,7 +41,7 @@ org.powermock - powermock-api-mockito + powermock-api-mockito2 ${powermock.version} test @@ -65,7 +65,7 @@ 3.5 - 1.6.6 + 1.7.0
diff --git a/mockito2/pom.xml b/mockito2/pom.xml index 523cfa816d..a7c4683c30 100644 --- a/mockito2/pom.xml +++ b/mockito2/pom.xml @@ -53,6 +53,6 @@ UTF-8 - 2.7.5 + 2.8.9
diff --git a/mocks/mock-comparisons/pom.xml b/mocks/mock-comparisons/pom.xml index 2ab35651f1..e350457f54 100644 --- a/mocks/mock-comparisons/pom.xml +++ b/mocks/mock-comparisons/pom.xml @@ -13,7 +13,7 @@ mock-comparisons - 1.10.19 + 2.8.9 3.4 1.29 diff --git a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java index 18bc2ae189..9d47b2f5d4 100644 --- a/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java +++ b/mocks/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerIntegrationTest.java @@ -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() { - @Override - public boolean matches(Object argument) { - return argument instanceof String && ((String) argument).startsWith("foo"); - } - })); + Mockito.verify(loginService) + .setCurrentUser(ArgumentMatchers.argThat(new ArgumentMatcher() { + @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"); } } diff --git a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java index 56d354be7f..e7b972f6a4 100644 --- a/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java +++ b/mockserver/src/test/java/com/baeldung/mock/server/MockServerLiveTest.java @@ -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(); } } diff --git a/pom.xml b/pom.xml index fa6a3e5673..3feba96d5a 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ 4.12 1.3 - 1.10.19 + 2.8.9 1.7.21 1.1.7 @@ -28,7 +28,6 @@ - spring-activiti aws akka-streams algorithms @@ -94,6 +93,7 @@ jws libraries + libraries-data log-mdc log4j log4j2 @@ -128,6 +128,7 @@ spark-java spring-5-mvc + spring-activiti spring-akka spring-amqp spring-all diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java new file mode 100644 index 0000000000..f6cf9fba68 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToCleanString.java @@ -0,0 +1,43 @@ +package com.baelding.rxjava.operator; + +import rx.Observable.Operator; +import rx.Subscriber; + +public class ToCleanString implements Operator { + + public static ToCleanString toCleanString() { + return new ToCleanString(); + } + + private ToCleanString() { + super(); + } + + @Override + public Subscriber call(final Subscriber subscriber) { + return new Subscriber(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); + } + } + }; + } + +} \ No newline at end of file diff --git a/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java new file mode 100644 index 0000000000..006d59de36 --- /dev/null +++ b/rxjava/src/main/java/com/baelding/rxjava/operator/ToLength.java @@ -0,0 +1,20 @@ +package com.baelding.rxjava.operator; + +import rx.Observable; +import rx.Observable.Transformer; + +public class ToLength implements Transformer { + + public static ToLength toLength() { + return new ToLength(); + } + + private ToLength() { + super(); + } + + @Override + public Observable call(Observable source) { + return source.map(String::length); + } +} \ No newline at end of file diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java index 040936a67a..458091fd1c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaBackpressureLongRunningUnitTest.java @@ -34,7 +34,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenBackpressureNotDefined_shouldTrowException() { // given TestSubscriber testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); source.observeOn(Schedulers.computation()).subscribe(testSubscriber); @@ -50,7 +50,7 @@ public class RxJavaBackpressureLongRunningUnitTest { public void givenHotObservable_whenWindowIsDefined_shouldNotThrowException() { // given TestSubscriber> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject 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> testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject 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 testSubscriber = new TestSubscriber<>(); - PublishSubject source = PublishSubject. create(); + PublishSubject source = PublishSubject.create(); // when source.sample(100, TimeUnit.MILLISECONDS) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java new file mode 100644 index 0000000000..a49103196c --- /dev/null +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxJavaCustomOperatorUnitTest.java @@ -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 list = Arrays.asList("john_1", "tom-3"); + final List results = new ArrayList<>(); + + final Observable 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 list = Arrays.asList("john", "tom"); + final List results = new ArrayList<>(); + + final Observable 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 cleanStringFn = subscriber -> new Subscriber(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 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 toLengthFn = source -> source.map(String::length); + + final List 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)); + } +} diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 3d2f1386df..c5289b20a6 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -53,6 +53,23 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java index 3924d31f68..fd184556c4 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiController.java @@ -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 getTasks(@PathVariable String processInstanceId) { List usertasks = taskService.createTaskQuery() - .processInstanceId(processInstanceId) - .list(); + .processInstanceId(processInstanceId) + .list(); - List 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()); } diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java index e98b8ad7ca..2cfacdcf0d 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java @@ -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); } diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java similarity index 78% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java index 3176207664..baca58f6ff 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerTest.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiControllerIntegrationTest.java @@ -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 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); diff --git a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java similarity index 84% rename from spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java rename to spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java index da22c6c7fa..7460c302d8 100644 --- a/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationTests.java +++ b/spring-activiti/src/test/java/com/example/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java @@ -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() { diff --git a/spring-boot-property-exp/property-exp-custom/pom.xml b/spring-boot-property-exp/property-exp-custom/pom.xml index 234404a6c0..cfce323eab 100644 --- a/spring-boot-property-exp/property-exp-custom/pom.xml +++ b/spring-boot-property-exp/property-exp-custom/pom.xml @@ -40,6 +40,15 @@ **/application*.properties + + ${basedir}/src/main/resources + true + + **/application*.yml + **/application*.yaml + **/application*.properties + + @@ -53,6 +62,14 @@ true + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.propertyexpansion.SpringBootPropertyExpansionApp + + diff --git a/spring-boot-property-exp/property-exp-default/build.gradle b/spring-boot-property-exp/property-exp-default/build.gradle index f3c5f4a378..ec27de7c41 100644 --- a/spring-boot-property-exp/property-exp-default/build.gradle +++ b/spring-boot-property-exp/property-exp-default/build.gradle @@ -27,6 +27,10 @@ repositories { mavenCentral() } +springBoot { + executable = true +} + import org.apache.tools.ant.filters.ReplaceTokens processResources { with copySpec { diff --git a/spring-boot-property-exp/property-exp-default/pom.xml b/spring-boot-property-exp/property-exp-default/pom.xml index 3629e56111..2544800e6a 100644 --- a/spring-boot-property-exp/property-exp-default/pom.xml +++ b/spring-boot-property-exp/property-exp-default/pom.xml @@ -30,4 +30,16 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 85cf4573aa..deffaf41db 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -1,141 +1,147 @@ + 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"> - 4.0.0 + 4.0.0 - com.baeldung - spring-core - 0.0.1-SNAPSHOT - war + com.baeldung + spring-core + 0.0.1-SNAPSHOT + war - spring-core + spring-core - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.mockito - mockito-all - ${mockito.version} - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - javax.inject - javax.inject - ${javax.inject.version} - - - com.google.guava - guava - ${guava.version} - - - org.projectlombok - lombok - ${lombok.version} - - - org.springframework.boot - spring-boot-starter - 1.5.2.RELEASE - - - org.springframework.boot - spring-boot-test - ${mockito.spring.boot.version} - test - - + + + org.mockito + mockito-all + ${mockito.version} + + + org.springframework + spring-test + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + javax.inject + javax.inject + ${javax.inject.version} + + + com.google.guava + guava + ${guava.version} + + + org.projectlombok + lombok + ${lombok.version} + + + org.springframework.boot + spring-boot-starter + 1.5.2.RELEASE + + + org.springframework.boot + spring-boot-test + ${mockito.spring.boot.version} + test + + + commons-io + commons-io + ${commons.io.version} + + - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - false - - + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + - + - + - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + - - 1.10.19 - 1.4.4.RELEASE - 4.3.4.RELEASE - 1 - 20.0 - 2.6 - 1.16.12 - + + 1.10.19 + 1.4.4.RELEASE + 4.3.4.RELEASE + 1 + 20.0 + 2.6 + 1.16.12 + 2.5 + - - - java.net - https://maven.java.net/content/repositories/releases/ - - + + + java.net + https://maven.java.net/content/repositories/releases/ + + - + \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java new file mode 100644 index 0000000000..d9097188b3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/CopyStream.java @@ -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); + } +} diff --git a/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java new file mode 100644 index 0000000000..1ce67a075a --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/streamutils/DrainStream.java @@ -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(); + } +} diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java new file mode 100644 index 0000000000..9fe2f00a77 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java @@ -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); + } + +} diff --git a/spring-core/src/test/resources/input.txt b/spring-core/src/test/resources/input.txt new file mode 100644 index 0000000000..811232fa1f --- /dev/null +++ b/spring-core/src/test/resources/input.txt @@ -0,0 +1 @@ +This file is merely for testing. \ No newline at end of file diff --git a/spring-core/src/test/resources/output.txt b/spring-core/src/test/resources/output.txt new file mode 100644 index 0000000000..34e1e27d5a --- /dev/null +++ b/spring-core/src/test/resources/output.txt @@ -0,0 +1 @@ +Should be copied to OutputStream. \ No newline at end of file diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 0cfb3e6dee..14590f3de4 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -15,14 +15,18 @@ - 4.3.4.RELEASE - 2.6 + 4.3.10.RELEASE + 3.1.0 1.2 2.3.1 3.1.0 - 5.3.3.Final + 5.4.1.Final enter-location-of-server 1.3.2 + 1.8 + 3.0.7.RELEASE + 2.4.12 + 2.3.23 @@ -79,6 +83,38 @@ commons-fileupload ${fileupload.version} + + + + org.thymeleaf + thymeleaf + ${org.thymeleaf-version} + + + org.thymeleaf + thymeleaf-spring4 + ${org.thymeleaf-version} + + + + + org.freemarker + freemarker + ${freemarker.version} + + + org.springframework + spring-context-support + ${springframework.version} + + + + + org.codehaus.groovy + groovy-templates + ${groovy.version} + + @@ -94,6 +130,14 @@ ${deploy-path} + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + springMvcSimple diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index 9ace968bbe..b62ccae465 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -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 diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java new file mode 100644 index 0000000000..e43238f8a6 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/FreemarkerConfiguration.java @@ -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; + } +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java new file mode 100644 index 0000000000..b7a9256fc0 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/GroovyConfiguration.java @@ -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; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java new file mode 100644 index 0000000000..257dbc718a --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ThymeleafConfiguration.java @@ -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; + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index d6bbf5eabd..3e5b416191 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -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 diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java new file mode 100644 index 0000000000..55179938fc --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/UserController.java @@ -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()); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java new file mode 100644 index 0000000000..8016f98d85 --- /dev/null +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/domain/User.java @@ -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; + } + +} diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl new file mode 100644 index 0000000000..8dce9a88c9 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-freemarker.ftl @@ -0,0 +1,15 @@ +<#import "/spring.ftl" as spring/> + + + +User Registration + + +
+ <@spring.bind path="user" /> + Email:<@spring.formInput "user.email"/>
+ Password:<@spring.formPasswordInput "user.password"/>
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl new file mode 100644 index 0000000000..291077fc2e --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-groovy.tpl @@ -0,0 +1,18 @@ +yieldUnescaped '' +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') + } + } + } +} \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html new file mode 100644 index 0000000000..c98f3283c0 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration-thymeleaf.html @@ -0,0 +1,13 @@ + + + +User Registration + + +
+ Email:
+ Password:
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp new file mode 100644 index 0000000000..7c2d9c73b1 --- /dev/null +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/registration.jsp @@ -0,0 +1,18 @@ +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> + + + +User Registration + + + + Email: + +
+ Password: + +
+ +
+ + \ No newline at end of file diff --git a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index b6f1065cad..0000000000 --- a/spring-mvc-simple/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - spring - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - classpath*:spring-servlet_RequestMappingHandlerAdapter.xml - - 1 - - - spring - / - - \ No newline at end of file diff --git a/spring-rest/src/main/webapp/WEB-INF/web.xml b/spring-rest/src/main/webapp/WEB-INF/web.xml index a439de8a05..1b8b767ae3 100644 --- a/spring-rest/src/main/webapp/WEB-INF/web.xml +++ b/spring-rest/src/main/webapp/WEB-INF/web.xml @@ -19,10 +19,10 @@ org.baeldung.config - + api diff --git a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java index b68e7eab50..1472a1f89c 100644 --- a/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/org/baeldung/spring/RedirectionSecurityConfig.java @@ -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()) } } diff --git a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java index 608e8a6819..ed57088c56 100644 --- a/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java +++ b/spring-security-openid/src/main/java/org/baeldung/config/SpringOpenidApplication.java @@ -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); diff --git a/vavr/pom.xml b/vavr/pom.xml index d35a408389..426155263c 100644 --- a/vavr/pom.xml +++ b/vavr/pom.xml @@ -71,4 +71,26 @@ 4.12 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 3 + true + + **/*IntegrationTest.java + **/*LongRunningUnitTest.java + **/*ManualTest.java + **/JdbcTest.java + **/*LiveTest.java + + true + + + + + \ No newline at end of file diff --git a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java index 1adff2e845..1c7d70a9a4 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PatternMatchingUnitTest.java @@ -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() { diff --git a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java index 8409dbfa60..e93084f2c0 100644 --- a/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/PropertyBasedLongRunningUnitTest.java @@ -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 { diff --git a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java index 5ddd344c5c..08a5e20b40 100644 --- a/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/VavrUnitTest.java @@ -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 sortedList = List.of(3, 2, 1) - .sorted(); + .sorted(); } /* @@ -123,7 +127,7 @@ public class VavrUnitTest { @Test public void whenCreatesFunction_thenCorrect0() { Function0 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); } diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java index 9f0c48e3ee..4b4eb55fc5 100644 --- a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionAPIUnitTest.java @@ -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 javaSet = List.of(1, 2, 3) diff --git a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java index 6b0a34f9e4..155932888d 100644 --- a/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/either/EitherUnitTest.java @@ -7,32 +7,32 @@ import static org.junit.Assert.assertEquals; public class EitherUnitTest { - @Test - public void givenMarks_whenPassNumber_thenExpectNumber() { - Either result = EitherDemo.computeWithEither(100); - int marks = result.right() - .getOrElseThrow(x -> new IllegalStateException()); + @Test + public void givenMarks_whenPassNumber_thenExpectNumber() { + Either 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 result = EitherDemo.computeWithEither(50); - String error = result.left() + @Test + public void givenMarks_whenFailNumber_thenExpectErrorMesssage() { + Either 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 result = EitherDemo.computeWithEither(90); - int marks = result.right() + @Test + public void givenPassMarks_whenModified_thenExpectNumber() { + Either result = EitherDemo.computeWithEither(90); + int marks = result.right() .map(x -> x * 2) .get(); - assertEquals(180, marks); - } + assertEquals(180, marks); + } } diff --git a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java index 9c3e5a9cae..c7f17c2afc 100644 --- a/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/exception/handling/VavrTryUnitTest.java @@ -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 = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Stream stream = response.toStream().map(it -> it.id); //then @@ -49,8 +51,8 @@ public class VavrTryUnitTest { //when Try response = new VavrTry(httpClient).getResponse(); Integer chainedResult = response - .map(this::actionThatTakesResponse) - .getOrElse(defaultChainedResult); + .map(this::actionThatTakesResponse) + .getOrElse(defaultChainedResult); Option optionalResponse = response.toOption(); //then @@ -70,9 +72,9 @@ public class VavrTryUnitTest { //when Try 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 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, int defaultTransformation){ + public int actionThatTakesTryResponse(Try response, int defaultTransformation) { return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation)); } diff --git a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java index c2e9f377dd..63338afc24 100644 --- a/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/repositories/VavrRepositoryIntegrationTest.java @@ -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) diff --git a/video-tutorials/jackson-annotations/pom.xml b/video-tutorials/jackson-annotations/pom.xml index 853c84a1b8..e44611fab0 100644 --- a/video-tutorials/jackson-annotations/pom.xml +++ b/video-tutorials/jackson-annotations/pom.xml @@ -164,7 +164,7 @@ 2.5 - 2.2.26 + 2.8.9 4.4.1 4.5