diff --git a/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java b/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java index 719725598c..95fd058667 100644 --- a/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java +++ b/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java @@ -6,10 +6,12 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.zaxxer.hikari.HikariDataSource; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import java.util.HashMap; import java.util.Map; @@ -22,11 +24,14 @@ import static org.hibernate.cfg.AvailableSettings.PASS; */ public class App implements RequestHandler { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private SessionFactory sessionFactory = createSessionFactory(); public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) { - try (SessionFactory sessionFactory = createSessionFactory()) { + try { ShippingService service = new ShippingService(sessionFactory, new ShippingDao()); return routeRequest(input, service); + } finally { + flushConnectionPool(); } } @@ -105,4 +110,12 @@ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); .buildMetadata() .buildSessionFactory(); } + + private void flushConnectionPool() { + ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions() + .getServiceRegistry() + .getService(ConnectionProvider.class); + HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class); + hikariDataSource.getHikariPoolMXBean().softEvictConnections(); + } } diff --git a/core-java-modules/core-java-15/README.md b/core-java-modules/core-java-15/README.md index 53989f5cbb..de503fbb31 100644 --- a/core-java-modules/core-java-15/README.md +++ b/core-java-modules/core-java-15/README.md @@ -4,4 +4,4 @@ This module contains articles about Java 15. ### Relevant articles -- TODO: add article links here +- [Sealed Classes and Interfaces in Java 15](https://www.baeldung.com/java-sealed-classes-interfaces) diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml index c6f1454078..df8aeafca9 100644 --- a/core-java-modules/core-java-15/pom.xml +++ b/core-java-modules/core-java-15/pom.xml @@ -51,8 +51,8 @@ ${maven.compiler.release} --enable-preview - 15 - 15 + 14 + 14 diff --git a/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/records/Person.java b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/records/Person.java new file mode 100644 index 0000000000..74cf5edf9c --- /dev/null +++ b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/records/Person.java @@ -0,0 +1,15 @@ +package com.baeldung.whatsnew.records; + +/** + * Java record with a header indicating 2 fields. + */ +public record Person(String name, int age) { + /** + * Public constructor that does some basic validation. + */ + public Person { + if (age < 0) { + throw new IllegalArgumentException("Age cannot be negative"); + } + } +} diff --git a/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Employee.java b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Employee.java new file mode 100644 index 0000000000..ec85c371b7 --- /dev/null +++ b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Employee.java @@ -0,0 +1,9 @@ +package com.baeldung.whatsnew.sealedclasses; + +import java.util.Date; + +public non-sealed class Employee extends Person { + public Date getHiredDate() { + return new Date(); + } +} diff --git a/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Manager.java b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Manager.java new file mode 100644 index 0000000000..79c50b057e --- /dev/null +++ b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Manager.java @@ -0,0 +1,4 @@ +package com.baeldung.whatsnew.sealedclasses; + +public final class Manager extends Person { +} diff --git a/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Person.java b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Person.java new file mode 100644 index 0000000000..2a52bc1a73 --- /dev/null +++ b/core-java-modules/core-java-15/src/main/java/com/baeldung/whatsnew/sealedclasses/Person.java @@ -0,0 +1,21 @@ +package com.baeldung.whatsnew.sealedclasses; + +import java.util.Date; + +public sealed class Person permits Employee, Manager { + /** + * Demonstration of pattern matching for instanceof + * + * @param person A Person object + * @return + */ + public static void patternMatchingDemo(Person person) { + if(person instanceof Employee employee) { + Date hiredDate = employee.getHiredDate(); + } + + if(person instanceof Employee employee && employee.getHiredDate() != null) { + Date hiredDate = employee.getHiredDate(); + } + } +} diff --git a/core-java-modules/core-java-arrays-guides/README.md b/core-java-modules/core-java-arrays-guides/README.md index 934833b31b..7338ff9523 100644 --- a/core-java-modules/core-java-arrays-guides/README.md +++ b/core-java-modules/core-java-arrays-guides/README.md @@ -7,3 +7,4 @@ This module contains complete guides about arrays in Java - [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays) - [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array) - [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception) +- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array) diff --git a/core-java-modules/core-java-char/README.md b/core-java-modules/core-java-char/README.md new file mode 100644 index 0000000000..71f8e943aa --- /dev/null +++ b/core-java-modules/core-java-char/README.md @@ -0,0 +1,6 @@ +## Core Java Character + +This module contains articles about Java Character Class + +### Relevant Articles: +- Character#isAlphabetic vs Character#isLetter diff --git a/core-java-modules/core-java-char/pom.xml b/core-java-modules/core-java-char/pom.xml new file mode 100644 index 0000000000..3691079482 --- /dev/null +++ b/core-java-modules/core-java-char/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + core-java-char + 0.1.0-SNAPSHOT + core-java-char + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.openjdk.jmh + jmh-core + ${openjdk.jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${openjdk.jmh.version} + + + + + 1.19 + 3.11.1 + + + diff --git a/core-java-modules/core-java-char/src/test/java/com/baeldung/character/CharacterGeneralCategoryTypeUnitTest.java b/core-java-modules/core-java-char/src/test/java/com/baeldung/character/CharacterGeneralCategoryTypeUnitTest.java new file mode 100644 index 0000000000..4bb41211a9 --- /dev/null +++ b/core-java-modules/core-java-char/src/test/java/com/baeldung/character/CharacterGeneralCategoryTypeUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.character; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class CharacterGeneralCategoryTypeUnitTest { + @Test + public void givenACharacter_whenUpperCaseLetter_thenAssertTrue() { + assertTrue(Character.getType('U') == Character.UPPERCASE_LETTER); + } + + @Test + public void givenACharacter_whenLowerCaseLetter_thenAssertTrue() { + assertTrue(Character.getType('u') == Character.LOWERCASE_LETTER); + } + + @Test + public void givenACharacter_whenTitleCaseLetter_thenAssertTrue() { + assertTrue(Character.getType('\u01f2') == Character.TITLECASE_LETTER); + } + + @Test + public void givenACharacter_whenModifierLetter_thenAssertTrue() { + assertTrue(Character.getType('\u02b0') == Character.MODIFIER_LETTER); + } + + @Test + public void givenACharacter_whenOtherLetter_thenAssertTrue() { + assertTrue(Character.getType('\u05d0') == Character.OTHER_LETTER); + } + + @Test + public void givenACharacter_whenLetterNumber_thenAssertTrue() { + assertTrue(Character.getType('\u2164') == Character.LETTER_NUMBER); + } +} diff --git a/core-java-modules/core-java-char/src/test/java/com/baeldung/character/IsLetterOrAlphabetUnitTest.java b/core-java-modules/core-java-char/src/test/java/com/baeldung/character/IsLetterOrAlphabetUnitTest.java new file mode 100644 index 0000000000..734762ec7b --- /dev/null +++ b/core-java-modules/core-java-char/src/test/java/com/baeldung/character/IsLetterOrAlphabetUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.character; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; + +public class IsLetterOrAlphabetUnitTest { + @Test + public void givenACharacter_whenLetter_thenAssertIsLetterTrue() { + assertTrue(Character.isLetter('a')); + } + + @Test + public void givenACharacter_whenLetter_thenAssertIsAlphabeticTrue() { + assertTrue(Character.isAlphabetic('a')); + } + + @Test + public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsLetterFalse() { + assertFalse(Character.isLetter('\u2164')); + } + + @Test + public void givenACharacter_whenAlphabeticAndNotLetter_thenAssertIsAlphabeticTrue() { + assertTrue(Character.isAlphabetic('\u2164')); + } +} diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index 3637f835cf..d24f7492bb 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -8,4 +8,4 @@ This module contains articles about the Java ArrayList collection - [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist) - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element) - +- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size) diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayCreatorUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayCreatorUnitTest.java new file mode 100644 index 0000000000..74c8b93872 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayCreatorUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.listcapacityvsarraysize; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ArrayCreatorUnitTest { + + @Test + void whenSizeOfAnArrayIsNonZero_thenReturnNewArrayOfGivenSize() { + Integer[] array = new Integer[10]; + assertEquals(10, array.length); + } + + @Test + void whenSizeOfAnArrayIsLessThanZero_thenThrowException() { + assertThrows(NegativeArraySizeException.class, () -> { Integer[] array = new Integer[-1]; }); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayListCreatorUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayListCreatorUnitTest.java new file mode 100644 index 0000000000..62efe43af4 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listcapacityvsarraysize/ArrayListCreatorUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.listcapacityvsarraysize; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.*; + +class ArrayListCreatorUnitTest { + + @Test + void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithGivenCapacity() { + ArrayList list = new ArrayList<>(100); + + assertNotNull(list); + } + + @Test + void givenInvalidCapacityOfList_whenCreateListInvoked_thenThrowException() { + assertThrows(IllegalArgumentException.class, () -> new ArrayList<>(-1)); + } + + @Test + void givenValidCapacityOfList_whenCreateListInvoked_thenCreateNewArrayListWithSizeZero() { + assertEquals(0, new ArrayList(100).size()); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions-3/README.md b/core-java-modules/core-java-exceptions-3/README.md index f93e1a9943..8a59d6a229 100644 --- a/core-java-modules/core-java-exceptions-3/README.md +++ b/core-java-modules/core-java-exceptions-3/README.md @@ -6,3 +6,4 @@ - [AbstractMethodError in Java](https://www.baeldung.com/java-abstractmethoderror) - [Java IndexOutOfBoundsException “Source Does Not Fit in Dest”](https://www.baeldung.com/java-indexoutofboundsexception) - [Localizing Exception Messages in Java](https://www.baeldung.com/java-localize-exception-messages) +- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception) diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Reptile.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Amphibian.java similarity index 59% rename from core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Reptile.java rename to core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Amphibian.java index ed4b0273e5..f31c19bc0f 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Reptile.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Amphibian.java @@ -1,9 +1,9 @@ package com.baeldung.exceptions.classcastexception; -public class Reptile implements Animal { +public class Amphibian implements Animal { @Override public String getName() { - return "Reptile"; + return "Amphibian"; } } diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Frog.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Frog.java index 0a0b2d1f63..a3837f4c2f 100644 --- a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Frog.java +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Frog.java @@ -1,6 +1,6 @@ package com.baeldung.exceptions.classcastexception; -public class Frog extends Reptile { +public class Frog extends Amphibian { @Override public String getName() { diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java index 140d809d44..a18663f544 100644 --- a/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -16,31 +16,42 @@ public class UnzipFile { ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { final File newFile = newFile(destDir, zipEntry); - final FileOutputStream fos = new FileOutputStream(newFile); - int len; - while ((len = zis.read(buffer)) > 0) { - fos.write(buffer, 0, len); + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory " + newFile); + } + } else { + File parent = newFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory " + parent); + } + + final FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); } - fos.close(); zipEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } - + /** * @see https://snyk.io/research/zip-slip-vulnerability */ public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { File destFile = new File(destinationDir, zipEntry.getName()); - + String destDirPath = destinationDir.getCanonicalPath(); String destFilePath = destFile.getCanonicalPath(); - + if (!destFilePath.startsWith(destDirPath + File.separator)) { throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); } - + return destFile; } } \ No newline at end of file diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/iterationcounter/IterationCounter.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/iterationcounter/IterationCounter.java new file mode 100644 index 0000000000..40d997cb0e --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/iterationcounter/IterationCounter.java @@ -0,0 +1,68 @@ +package com.baeldung.iterationcounter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.stream.Stream; + +public class IterationCounter { + public static final List IMDB_TOP_MOVIES = Arrays.asList("The Shawshank Redemption", + "The Godfather", "The Godfather II", "The Dark Knight"); + + public static List getRankingsWithForLoop(List movies) { + List rankings = new ArrayList<>(); + for (int i = 0; i < movies.size(); i++) { + String ranking = (i + 1) + ": " + movies.get(i); + rankings.add(ranking); + } + return rankings; + } + + public static List getRankingsWithForEachLoop(List movies) { + List rankings = new ArrayList<>(); + int i = 0; + for (String movie : movies) { + String ranking = (i + 1) + ": " + movies.get(i); + rankings.add(ranking); + + i++; + } + return rankings; + } + + public static List getRankingsWithFunctionalForEachLoop(List movies) { + List rankings = new ArrayList<>(); + forEachWithCounter(movies, (i, movie) -> { + String ranking = (i + 1) + ": " + movie; + rankings.add(ranking); + }); + + return rankings; + } + + public static void forEachWithCounter(Iterable source, BiConsumer consumer) { + int i = 0; + for (T item : source) { + consumer.accept(i, item); + i++; + } + } + + public static List getRankingsWithStream(Stream movies) { + List rankings = new ArrayList<>(); + movies.forEach(withCounter((i, movie) -> { + String ranking = (i + 1) + ": " + movie; + rankings.add(ranking); + })); + + return rankings; + } + + public static Consumer withCounter(BiConsumer consumer) { + AtomicInteger counter = new AtomicInteger(0); + return item -> consumer.accept(counter.getAndIncrement(), item); + } +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/iterationcounter/IterationCounterUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/iterationcounter/IterationCounterUnitTest.java new file mode 100644 index 0000000000..6746e570ca --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/iterationcounter/IterationCounterUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.iterationcounter; + +import org.junit.Test; + +import static com.baeldung.iterationcounter.IterationCounter.*; +import static org.assertj.core.api.Assertions.*; + +public class IterationCounterUnitTest { + @Test + public void givenRankings_whenCalculateWithForLoop_thenRankingsCorrect() { + assertThat(getRankingsWithForLoop(IMDB_TOP_MOVIES)) + .containsExactly("1: The Shawshank Redemption", + "2: The Godfather", "3: The Godfather II", "4: The Dark Knight"); + } + + @Test + public void givenRankings_whenCalculateWithForEachLoop_thenRankingsCorrect() { + assertThat(getRankingsWithForEachLoop(IMDB_TOP_MOVIES)) + .containsExactly("1: The Shawshank Redemption", + "2: The Godfather", "3: The Godfather II", "4: The Dark Knight"); + } + + @Test + public void givenRankings_whenCalculateWithFunctionalForEach_thenRankingsCorrect() { + assertThat(getRankingsWithFunctionalForEachLoop(IMDB_TOP_MOVIES)) + .containsExactly("1: The Shawshank Redemption", + "2: The Godfather", "3: The Godfather II", "4: The Dark Knight"); + } + + @Test + public void givenRankings_whenCalculateWithStream_thenRankingsCorrect() { + assertThat(getRankingsWithStream(IMDB_TOP_MOVIES.stream())) + .containsExactly("1: The Shawshank Redemption", + "2: The Godfather", "3: The Godfather II", "4: The Dark Knight"); + } +} diff --git a/core-java-modules/core-java-string-apis/README.md b/core-java-modules/core-java-string-apis/README.md index fc36ba8640..c9aa40de7a 100644 --- a/core-java-modules/core-java-string-apis/README.md +++ b/core-java-modules/core-java-string-apis/README.md @@ -8,5 +8,5 @@ This module contains articles about string APIs. - [Guide to java.util.Formatter](https://www.baeldung.com/java-string-formatter) - [Guide to StreamTokenizer](https://www.baeldung.com/java-streamtokenizer) - [CharSequence vs. String in Java](https://www.baeldung.com/java-char-sequence-string) -- [StringBuilder and StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer) +- [StringBuilder vs StringBuffer in Java](https://www.baeldung.com/java-string-builder-string-buffer) - [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index b995092782..2f3965b237 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -29,7 +29,8 @@ core-java-arrays-convert core-java-arrays-operations-basic core-java-arrays-operations-advanced - + + core-java-char core-java-collections core-java-collections-2 core-java-collections-3 diff --git a/core-kotlin-modules/core-kotlin-advanced/README.md b/core-kotlin-modules/core-kotlin-advanced/README.md deleted file mode 100644 index 2e99e3b078..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Core Kotlin Advanced - -This module contains articles about advanced topics in Kotlin. - -### Relevant articles: -- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl) -- [Regular Expressions in Kotlin](https://www.baeldung.com/kotlin-regular-expressions) -- [Idiomatic Logging in Kotlin](https://www.baeldung.com/kotlin-logging) -- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects) -- [Reflection with Kotlin](https://www.baeldung.com/kotlin-reflection) -- [Kotlin Contracts](https://www.baeldung.com/kotlin-contracts) diff --git a/core-kotlin-modules/core-kotlin-advanced/pom.xml b/core-kotlin-modules/core-kotlin-advanced/pom.xml deleted file mode 100644 index 5ddfef23cc..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - core-kotlin-advanced - core-kotlin-advanced - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 1.3.30 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt deleted file mode 100644 index ca0b13cdc7..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/CallsInPlaceEffect.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.contract - -import kotlin.contracts.ExperimentalContracts -import kotlin.contracts.InvocationKind -import kotlin.contracts.contract - -@ExperimentalContracts -inline fun myRun(block: () -> R): R { - contract { - callsInPlace(block, InvocationKind.EXACTLY_ONCE) - } - return block() -} - -@ExperimentalContracts -fun callsInPlace() { - val i: Int - myRun { - i = 1 // Without contract initialization is forbidden due to possible re-assignment - } - println(i) // Without contract variable might be uninitialized -} - diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt deleted file mode 100644 index 56f667af82..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/contract/ReturnsEffect.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.contract - -import kotlin.contracts.ExperimentalContracts -import kotlin.contracts.contract - -data class Request(val arg: String) - -class Service { - - @ExperimentalContracts - fun process(request: Request?) { - validate(request) - println(request.arg) - } - -} - -@ExperimentalContracts -private fun validate(request: Request?) { - contract { - returns() implies (request != null) - } - if (request == null) { - throw IllegalArgumentException("Undefined request") - } -} - -data class MyEvent(val message: String) - -@ExperimentalContracts -fun processEvent(event: Any?) { - if (isInterested(event)) { - println(event.message) // Compiler makes smart cast here with the help of contract - } -} - -@ExperimentalContracts -fun isInterested(event: Any?): Boolean { - contract { - returns(true) implies (event is MyEvent) - } - return event is MyEvent -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/User.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/User.kt deleted file mode 100644 index fdbf95f7ba..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/User.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.datamapping - -data class User( - val firstName: String, - val lastName: String, - val street: String, - val houseNumber: String, - val phone: String, - val age: Int, - val password: String) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt deleted file mode 100644 index 1f3d7f3b47..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.datamapping - -import kotlin.reflect.full.memberProperties - -fun User.toUserView() = UserView( - name = "$firstName $lastName", - address = "$street $houseNumber", - telephone = phone, - age = age -) - -fun User.toUserViewReflection() = with(::UserView) { - val propertiesByName = User::class.memberProperties.associateBy { it.name } - callBy(parameters.associate { parameter -> - parameter to when (parameter.name) { - UserView::name.name -> "$firstName $lastName" - UserView::address.name -> "$street $houseNumber" - UserView::telephone.name -> phone - else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection) - } - }) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserView.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserView.kt deleted file mode 100644 index e1b6de6b57..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/datamapping/UserView.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.datamapping - -data class UserView( - val name: String, - val address: String, - val telephone: String, - val age: Int -) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt deleted file mode 100644 index 207e9dbd53..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/dsl/SqlDsl.kt +++ /dev/null @@ -1,114 +0,0 @@ -package com.baeldung.dsl - -abstract class Condition { - - fun and(initializer: Condition.() -> Unit) { - addCondition(And().apply(initializer)) - } - - fun or(initializer: Condition.() -> Unit) { - addCondition(Or().apply(initializer)) - } - - infix fun String.eq(value: Any?) { - addCondition(Eq(this, value)) - } - - protected abstract fun addCondition(condition: Condition) -} - -open class CompositeCondition(private val sqlOperator: String) : Condition() { - private val conditions = mutableListOf() - - override fun addCondition(condition: Condition) { - conditions += condition - } - - override fun toString(): String { - return if (conditions.size == 1) { - conditions.first().toString() - } else { - conditions.joinToString(prefix = "(", postfix = ")", separator = " $sqlOperator ") { - "$it" - } - } - } -} - -class And : CompositeCondition("and") - -class Or : CompositeCondition("or") - -class Eq(private val column: String, private val value: Any?) : Condition() { - - init { - if (value != null && value !is Number && value !is String) { - throw IllegalArgumentException("Only , numbers and strings values can be used in the 'where' clause") - } - } - - override fun addCondition(condition: Condition) { - throw IllegalStateException("Can't add a nested condition to the sql 'eq'") - } - - override fun toString(): String { - return when (value) { - null -> "$column is null" - is String -> "$column = '$value'" - else -> "$column = $value" - } - } -} - -class SqlSelectBuilder { - - private val columns = mutableListOf() - private lateinit var table: String - private var condition: Condition? = null - - fun select(vararg columns: String) { - if (columns.isEmpty()) { - throw IllegalArgumentException("At least one column should be defined") - } - if (this.columns.isNotEmpty()) { - throw IllegalStateException("Detected an attempt to re-define columns to fetch. Current columns list: " - + "${this.columns}, new columns list: $columns") - } - this.columns.addAll(columns) - } - - fun from(table: String) { - this.table = table - } - - fun where(initializer: Condition.() -> Unit) { - condition = And().apply(initializer) - } - - fun build(): String { - if (!::table.isInitialized) { - throw IllegalStateException("Failed to build an sql select - target table is undefined") - } - return toString() - } - - override fun toString(): String { - val columnsToFetch = - if (columns.isEmpty()) { - "*" - } else { - columns.joinToString(", ") - } - val conditionString = - if (condition == null) { - "" - } else { - " where $condition" - } - return "select $columnsToFetch from $table$conditionString" - } -} - -fun query(initializer: SqlSelectBuilder.() -> Unit): SqlSelectBuilder { - return SqlSelectBuilder().apply(initializer) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt deleted file mode 100644 index 01edf5e871..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnAny.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.logging - -import org.slf4j.Logger - -open class LoggerAsExtensionOnAny { - val logger = logger() - - fun log(s: String) { - logger().info(s) - logger.info(s) - } -} - -class ExtensionSubclass : LoggerAsExtensionOnAny() - -fun T.logger(): Logger = getLogger(getClassForLogging(javaClass)) - -fun main(args: Array) { - LoggerAsExtensionOnAny().log("test") - ExtensionSubclass().log("sub") - "foo".logger().info("foo") - 1.logger().info("uh-oh!") - SomeOtherClass().logger() -} - -class SomeOtherClass { - fun logger(): String { - return "foo" - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt deleted file mode 100644 index 8210361345..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsExtensionOnMarkerInterface.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.logging - -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -interface Logging - -inline fun T.logger(): Logger = - //Wrong logger name! - //LoggerFactory.getLogger(javaClass.name + " w/interface") - LoggerFactory.getLogger(getClassForLogging(T::class.java).name + " w/interface") - -open class LoggerAsExtensionOnMarkerInterface : Logging { - companion object : Logging { - val logger = logger() - } - - fun log(s: String) { - logger().info(s) - logger.info(s) - } -} - -class MarkerExtensionSubclass : LoggerAsExtensionOnMarkerInterface() - -fun main(args: Array) { - LoggerAsExtensionOnMarkerInterface().log("test") - MarkerExtensionSubclass().log("sub") - "foo".logger().info("foo") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt deleted file mode 100644 index 60ac0800e2..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsProperty.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.logging - -open class LoggerAsProperty { - private val logger = getLogger(javaClass) - - fun log(s: String) { - logger.info(s) - } - -} - -class PropertySubclass : LoggerAsProperty() - -fun main(args: Array) { - LoggerAsProperty().log("test") - PropertySubclass().log("sub") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt deleted file mode 100644 index 83cde2b446..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerAsPropertyDelegate.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.logging - -import org.slf4j.Logger -import kotlin.properties.ReadOnlyProperty -import kotlin.reflect.KProperty - -open class LoggerAsPropertyDelegate { - private val lazyLogger by lazyLogger() - protected val logger by LoggerDelegate() - private val logger2 = logger - - companion object { - private val lazyLoggerComp by lazyLogger() - private val loggerComp by LoggerDelegate() - } - - open fun log(s: String) { - logger.info(s) - logger2.info(s) - lazyLogger.info(s) - loggerComp.info(s) - lazyLoggerComp.info(s) - } - -} - -class DelegateSubclass : LoggerAsPropertyDelegate() { - override fun log(s: String) { - logger.info("-- in sub") - super.log(s) - } -} - -fun lazyLogger(forClass: Class<*>): Lazy = - lazy { getLogger(getClassForLogging(forClass)) } - -fun T.lazyLogger(): Lazy = lazyLogger(javaClass) - -fun main(args: Array) { - LoggerAsPropertyDelegate().log("test") - DelegateSubclass().log("sub") -} - -class LoggerDelegate : ReadOnlyProperty { - override fun getValue(thisRef: R, property: KProperty<*>) = - getLogger(getClassForLogging(thisRef.javaClass)) -} diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt deleted file mode 100644 index 6a44675e45..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/LoggerInCompanionObject.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.logging - -open class LoggerInCompanionObject { - companion object { - private val loggerWithExplicitClass = getLogger(LoggerInCompanionObject::class.java) - @Suppress("JAVA_CLASS_ON_COMPANION") - private val loggerWithWrongClass = getLogger(javaClass) - @Suppress("JAVA_CLASS_ON_COMPANION") - private val logger = getLogger(javaClass.enclosingClass) - } - - fun log(s: String) { - loggerWithExplicitClass.info(s) - loggerWithWrongClass.info(s) - logger.info(s) - } - - class Inner { - companion object { - private val loggerWithExplicitClass = getLogger(Inner::class.java) - @Suppress("JAVA_CLASS_ON_COMPANION") - @JvmStatic - private val loggerWithWrongClass = getLogger(javaClass) - @Suppress("JAVA_CLASS_ON_COMPANION") - @JvmStatic - private val logger = getLogger(javaClass.enclosingClass) - } - - fun log(s: String) { - loggerWithExplicitClass.info(s) - loggerWithWrongClass.info(s) - logger.info(s) - } - } - -} - -class CompanionSubclass : LoggerInCompanionObject() - -fun main(args: Array) { - LoggerInCompanionObject().log("test") - LoggerInCompanionObject.Inner().log("test") - CompanionSubclass().log("sub") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt b/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt deleted file mode 100644 index 44dba53cb7..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/main/kotlin/com/baeldung/logging/Util.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.logging - -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import kotlin.reflect.full.companionObject - -fun getLogger(forClass: Class<*>): Logger = LoggerFactory.getLogger(forClass) - -fun getClassForLogging(javaClass: Class): Class<*> { - return javaClass.enclosingClass?.takeIf { - it.kotlin.companionObject?.java == javaClass - } ?: javaClass -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/datamapping/UserTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/datamapping/UserTest.kt deleted file mode 100644 index 44d350ea38..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/datamapping/UserTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.datamapping - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertAll -import kotlin.test.assertEquals - -class UserTest { - - @Test - fun `maps User to UserResponse using extension function`() { - val p = buildUser() - val view = p.toUserView() - assertUserView(view) - } - - @Test - fun `maps User to UserResponse using reflection`() { - val p = buildUser() - val view = p.toUserViewReflection() - assertUserView(view) - } - - private fun buildUser(): User { - return User( - "Java", - "Duke", - "Javastreet", - "42", - "1234567", - 30, - "s3cr37" - ) - } - - private fun assertUserView(pr: UserView) { - assertAll( - { assertEquals("Java Duke", pr.name) }, - { assertEquals("Javastreet 42", pr.address) }, - { assertEquals("1234567", pr.telephone) }, - { assertEquals(30, pr.age) } - ) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt deleted file mode 100644 index a370e7f15d..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/dsl/SqlDslTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.dsl - -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test - -class SqlDslTest { - - @Test - fun `when no columns are specified then star is used`() { - doTest("select * from table1") { - from ("table1") - } - } - - @Test - fun `when no condition is specified then correct query is built`() { - doTest("select column1, column2 from table1") { - select("column1", "column2") - from ("table1") - } - } - - @Test(expected = Exception::class) - fun `when no table is specified then an exception is thrown`() { - query { - select("column1") - }.build() - } - - @Test - fun `when a list of conditions is specified then it's respected`() { - doTest("select * from table1 where (column3 = 4 and column4 is null)") { - from ("table1") - where { - "column3" eq 4 - "column4" eq null - } - } - } - - @Test - fun `when 'or' conditions are specified then they are respected`() { - doTest("select * from table1 where (column3 = 4 or column4 is null)") { - from ("table1") - where { - or { - "column3" eq 4 - "column4" eq null - } - } - } - } - - @Test - fun `when either 'and' or 'or' conditions are specified then they are respected`() { - doTest("select * from table1 where ((column3 = 4 or column4 is null) and column5 = 42)") { - from ("table1") - where { - and { - or { - "column3" eq 4 - "column4" eq null - } - "column5" eq 42 - } - } - } - } - - private fun doTest(expected: String, sql: SqlSelectBuilder.() -> Unit) { - assertThat(query(sql).build()).isEqualTo(expected) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt deleted file mode 100644 index c77774dd81..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/JavaReflectionTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.reflection - -import org.junit.Ignore -import org.junit.Test -import org.slf4j.LoggerFactory - -@Ignore -class JavaReflectionTest { - private val LOG = LoggerFactory.getLogger(KClassTest::class.java) - - @Test - fun listJavaClassMethods() { - Exception::class.java.methods - .forEach { method -> LOG.info("Method: {}", method) } - } - - @Test - fun listKotlinClassMethods() { - JavaReflectionTest::class.java.methods - .forEach { method -> LOG.info("Method: {}", method) } - } - - @Test - fun listKotlinDataClassMethods() { - data class ExampleDataClass(val name: String, var enabled: Boolean) - - ExampleDataClass::class.java.methods - .forEach { method -> LOG.info("Method: {}", method) } - } - - -} diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt deleted file mode 100644 index f5d83cd13d..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KClassTest.kt +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.reflection - -import org.junit.Assert -import org.junit.Ignore -import org.junit.Test -import org.slf4j.LoggerFactory -import java.math.BigDecimal -import kotlin.reflect.full.* - -class KClassTest { - private val LOG = LoggerFactory.getLogger(KClassTest::class.java) - - @Test - fun testKClassDetails() { - val stringClass = String::class - Assert.assertEquals("kotlin.String", stringClass.qualifiedName) - Assert.assertFalse(stringClass.isData) - Assert.assertFalse(stringClass.isCompanion) - Assert.assertFalse(stringClass.isAbstract) - Assert.assertTrue(stringClass.isFinal) - Assert.assertFalse(stringClass.isSealed) - - val listClass = List::class - Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName) - Assert.assertFalse(listClass.isData) - Assert.assertFalse(listClass.isCompanion) - Assert.assertTrue(listClass.isAbstract) - Assert.assertFalse(listClass.isFinal) - Assert.assertFalse(listClass.isSealed) - } - - @Test - fun testGetRelated() { - LOG.info("Companion Object: {}", TestSubject::class.companionObject) - LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance) - LOG.info("Object Instance: {}", TestObject::class.objectInstance) - - Assert.assertSame(TestObject, TestObject::class.objectInstance) - } - - @Test - fun testNewInstance() { - val listClass = ArrayList::class - - val list = listClass.createInstance() - Assert.assertTrue(list is ArrayList) - } - - @Test - @Ignore - fun testMembers() { - val bigDecimalClass = BigDecimal::class - - LOG.info("Constructors: {}", bigDecimalClass.constructors) - LOG.info("Functions: {}", bigDecimalClass.functions) - LOG.info("Properties: {}", bigDecimalClass.memberProperties) - LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions) - } -} - -class TestSubject { - companion object { - val name = "TestSubject" - } -} - -object TestObject { - val answer = 42 -} diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt deleted file mode 100644 index b58c199a7c..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/reflection/KMethodTest.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.reflection - -import org.junit.Assert -import org.junit.Test -import java.io.ByteArrayInputStream -import java.nio.charset.Charset -import kotlin.reflect.KMutableProperty -import kotlin.reflect.full.starProjectedType - -class KMethodTest { - - @Test - fun testCallMethod() { - val str = "Hello" - val lengthMethod = str::length - - Assert.assertEquals(5, lengthMethod()) - } - - @Test - fun testReturnType() { - val str = "Hello" - val method = str::byteInputStream - - Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType) - Assert.assertFalse(method.returnType.isMarkedNullable) - } - - @Test - fun testParams() { - val str = "Hello" - val method = str::byteInputStream - - method.isSuspend - Assert.assertEquals(1, method.parameters.size) - Assert.assertTrue(method.parameters[0].isOptional) - Assert.assertFalse(method.parameters[0].isVararg) - Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type) - } - - @Test - fun testMethodDetails() { - val codePoints = String::codePoints - Assert.assertEquals("codePoints", codePoints.name) - Assert.assertFalse(codePoints.isSuspend) - Assert.assertFalse(codePoints.isExternal) - Assert.assertFalse(codePoints.isInline) - Assert.assertFalse(codePoints.isOperator) - - val byteInputStream = String::byteInputStream - Assert.assertEquals("byteInputStream", byteInputStream.name) - Assert.assertFalse(byteInputStream.isSuspend) - Assert.assertFalse(byteInputStream.isExternal) - Assert.assertTrue(byteInputStream.isInline) - Assert.assertFalse(byteInputStream.isOperator) - } - - val readOnlyProperty: Int = 42 - lateinit var mutableProperty: String - - @Test - fun testPropertyDetails() { - val roProperty = this::readOnlyProperty - Assert.assertEquals("readOnlyProperty", roProperty.name) - Assert.assertFalse(roProperty.isLateinit) - Assert.assertFalse(roProperty.isConst) - Assert.assertFalse(roProperty is KMutableProperty<*>) - - val mProperty = this::mutableProperty - Assert.assertEquals("mutableProperty", mProperty.name) - Assert.assertTrue(mProperty.isLateinit) - Assert.assertFalse(mProperty.isConst) - Assert.assertTrue(mProperty is KMutableProperty<*>) - } - - @Test - fun testProperty() { - val prop = this::mutableProperty - - Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType) - - prop.set("Hello") - Assert.assertEquals("Hello", prop.get()) - - prop.setter("World") - Assert.assertEquals("World", prop.getter()) - } -} diff --git a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt b/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt deleted file mode 100644 index 5cb54b4dda..0000000000 --- a/core-kotlin-modules/core-kotlin-advanced/src/test/kotlin/com/baeldung/regex/RegexTest.kt +++ /dev/null @@ -1,123 +0,0 @@ -package com.baeldung.regex - -import org.junit.Test -import kotlin.test.* - -class RegexTest { - - @Test - fun whenRegexIsInstantiated_thenIsEqualToToRegexMethod() { - val pattern = """a([bc]+)d?\\""" - - assertEquals(Regex.fromLiteral(pattern).pattern, pattern) - assertEquals(pattern, Regex(pattern).pattern) - assertEquals(pattern, pattern.toRegex().pattern) - } - - @Test - fun whenRegexMatches_thenResultIsTrue() { - val regex = """a([bc]+)d?""".toRegex() - - assertTrue(regex.containsMatchIn("xabcdy")) - assertTrue(regex.matches("abcd")) - assertFalse(regex matches "xabcdy") - } - - @Test - fun givenCompletelyMatchingRegex_whenMatchResult_thenDestructuring() { - val regex = """a([bc]+)d?""".toRegex() - - assertNull(regex.matchEntire("xabcdy")) - - val matchResult = regex.matchEntire("abbccbbd") - - assertNotNull(matchResult) - assertEquals(matchResult!!.value, matchResult.groupValues[0]) - assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1)) - assertEquals("bbccbb", matchResult.destructured.component1()) - assertNull(matchResult.next()) - } - - @Test - fun givenPartiallyMatchingRegex_whenMatchResult_thenGroups() { - val regex = """a([bc]+)d?""".toRegex() - var matchResult = regex.find("abcb abbd") - - assertNotNull(matchResult) - assertEquals(matchResult!!.value, matchResult.groupValues[0]) - assertEquals("abcb", matchResult.value) - assertEquals(IntRange(0, 3), matchResult.range) - assertEquals(listOf("abcb", "bcb"), matchResult.groupValues) - assertEquals(matchResult.destructured.toList(), matchResult.groupValues.drop(1)) - - matchResult = matchResult.next() - - assertNotNull(matchResult) - assertEquals("abbd", matchResult!!.value) - assertEquals("bb", matchResult.groupValues[1]) - - matchResult = matchResult.next() - - assertNull(matchResult) - } - - @Test - fun givenPartiallyMatchingRegex_whenMatchResult_thenDestructuring() { - val regex = """([\w\s]+) is (\d+) years old""".toRegex() - val matchResult = regex.find("Mickey Mouse is 95 years old") - val (name, age) = matchResult!!.destructured - - assertEquals("Mickey Mouse", name) - assertEquals("95", age) - } - - @Test - fun givenNonMatchingRegex_whenFindCalled_thenNull() { - val regex = """a([bc]+)d?""".toRegex() - val matchResult = regex.find("foo") - - assertNull(matchResult) - } - - @Test - fun givenNonMatchingRegex_whenFindAllCalled_thenEmptySet() { - val regex = """a([bc]+)d?""".toRegex() - val matchResults = regex.findAll("foo") - - assertNotNull(matchResults) - assertTrue(matchResults.none()) - } - - @Test - fun whenReplace_thenReplacement() { - val regex = """(red|green|blue)""".toRegex() - val beautiful = "Roses are red, Violets are blue" - val grim = regex.replace(beautiful, "dark") - val shiny = regex.replaceFirst(beautiful, "rainbow") - - assertEquals("Roses are dark, Violets are dark", grim) - assertEquals("Roses are rainbow, Violets are blue", shiny) - } - - @Test - fun whenComplexReplace_thenReplacement() { - val regex = """(red|green|blue)""".toRegex() - val beautiful = "Roses are red, Violets are blue" - val reallyBeautiful = regex.replace(beautiful) { - matchResult -> matchResult.value.toUpperCase() + "!" - } - - assertEquals("Roses are RED!, Violets are BLUE!", reallyBeautiful) - } - - @Test - fun whenSplit_thenList() { - val regex = """\W+""".toRegex() - val beautiful = "Roses are red, Violets are blue" - - assertEquals(listOf("Roses", "are", "red", "Violets", "are", "blue"), regex.split(beautiful)) - assertEquals(listOf("Roses", "are", "red", "Violets are blue"), regex.split(beautiful, 4)) - assertEquals(regex.toPattern().split(beautiful).asList(), regex.split(beautiful)) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/README.md b/core-kotlin-modules/core-kotlin-annotations/README.md deleted file mode 100644 index 787b67be11..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Core Kotlin Annotations - -This module contains articles about core Kotlin annotations. - -### Relevant articles: -- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations) -- [Guide to Kotlin @JvmField](https://www.baeldung.com/kotlin-jvm-field-annotation) -- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations) diff --git a/core-kotlin-modules/core-kotlin-annotations/pom.xml b/core-kotlin-modules/core-kotlin-annotations/pom.xml deleted file mode 100644 index 77670be151..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - core-kotlin-annotations - core-kotlin-annotations - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 1.3.30 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Annotations.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Annotations.kt deleted file mode 100644 index a8f83446dc..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Annotations.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.annotations - -@Target(AnnotationTarget.FIELD) -annotation class Positive - -@Target(AnnotationTarget.FIELD) -annotation class AllowedNames(val names: Array) diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Item.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Item.kt deleted file mode 100644 index 6864fe416e..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Item.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.annotations - -class Item(@Positive val amount: Float, @AllowedNames(["Alice", "Bob"]) val name: String) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Main.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Main.kt deleted file mode 100644 index 2b7f2c5590..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Main.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.annotations - -fun main(args: Array) { - val item = Item(amount = 1.0f, name = "Bob") - val validator = Validator() - println("Is instance valid? ${validator.isValid(item)}") -} diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Validator.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Validator.kt deleted file mode 100644 index 40139048ab..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/annotations/Validator.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.annotations - -/** - * Naive annotation-based validator. - * @author A.Shcherbakov - */ -class Validator() { - - /** - * Return true if every item's property annotated with @Positive is positive and if - * every item's property annotated with @AllowedNames has a value specified in that annotation. - */ - fun isValid(item: Item): Boolean { - val fields = item::class.java.declaredFields - for (field in fields) { - field.isAccessible = true - for (annotation in field.annotations) { - val value = field.get(item) - if (field.isAnnotationPresent(Positive::class.java)) { - val amount = value as Float - if (amount < 0) { - return false - } - } - if (field.isAnnotationPresent(AllowedNames::class.java)) { - val allowedNames = field.getAnnotation(AllowedNames::class.java)?.names - val name = value as String - allowedNames?.let { - if (!it.contains(name)) { - return false - } - } - } - } - } - return true - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Document.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Document.kt deleted file mode 100644 index 55f60bfa81..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Document.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.jvmannotations - -import java.util.* - -interface Document { - - @JvmDefault - fun getTypeDefault() = "document" - - fun getType() = "document" -} diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/HtmlDocument.java b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/HtmlDocument.java deleted file mode 100644 index feb71772cb..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/HtmlDocument.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.jvmannotations; - -public class HtmlDocument implements Document { - - @Override - public String getType() { - return "HTML"; - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Message.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Message.kt deleted file mode 100644 index 80180bd924..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/Message.kt +++ /dev/null @@ -1,66 +0,0 @@ -@file:JvmName("MessageHelper") -@file:JvmMultifileClass //used -package com.baeldung.jvmannotations - -import java.util.* - -@JvmName("getMyUsername") -fun getMyName() : String { - return "myUserId" -} - -object MessageBroker { - @JvmStatic - var totalMessagesSent = 0 - - const val maxMessageLength = 0 - - @JvmStatic - fun clearAllMessages() { - } - - @JvmStatic - @JvmOverloads - @Throws(Exception::class) - fun findMessages(sender : String, type : String = "text", maxResults : Int = 10) : List { - if(sender.isEmpty()) { - throw Exception() - } - return ArrayList() - } -} - -class Message { - - // this would cause a compilation error since sender is immutable - // @set:JvmName("setSender") - val sender = "myself" - - // this works as name is overridden - @JvmName("getSenderName") - fun getSender() : String = "from:$sender" - - @get:JvmName("getReceiverName") - @set:JvmName("setReceiverName") - var receiver : String = "" - - @get:JvmName("getContent") - @set:JvmName("setContent") - var text = "" - - // generates a warning - @get:JvmName("getId") - private val id = 0 - - @get:JvmName("hasAttachment") - var hasAttachment = true - - var isEncrypted = true - - fun setReceivers(receiverNames : List) { - } - - @JvmName("setReceiverIds") - fun setReceivers(receiverNames : List) { - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/MessageConverter.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/MessageConverter.kt deleted file mode 100644 index 3b19b12e10..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/MessageConverter.kt +++ /dev/null @@ -1,6 +0,0 @@ -@file:JvmMultifileClass -@file:JvmName("MessageHelper") //applies to all top level functions / variables / constants -package com.baeldung.jvmannotations - -fun convert(message: Message) { -} diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt deleted file mode 100644 index 41cb0df939..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.jvmannotations - -import java.util.* -class TextDocument : Document { - override fun getType() = "text" - - fun transformList(list : List) : List { - return list.filter { n -> n.toInt() > 1 } - } - - fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> { - return list.filter { n -> n.toInt() > 1 } - } - - var list : List<@JvmWildcard Any> = ArrayList() -} diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt deleted file mode 100644 index 00f2582d5f..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.jvmannotations - -import java.util.* - -class XmlDocument(d : Document) : Document by d diff --git a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmfield/JvmSample.kt b/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmfield/JvmSample.kt deleted file mode 100644 index e60894ba88..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/main/kotlin/com/baeldung/jvmfield/JvmSample.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.jvmfield - -class JvmSample(text:String) { - @JvmField - val sampleText:String = text -} - -class CompanionSample { - companion object { - @JvmField val MAX_LIMIT = 20 - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt b/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt deleted file mode 100644 index 5c2b6ef47f..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/annotations/ValidationTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.annotations - -import org.junit.Test -import kotlin.test.assertTrue -import kotlin.test.assertFalse - -class ValidationTest { - - @Test - fun whenAmountIsOneAndNameIsAlice_thenTrue() { - assertTrue(Validator().isValid(Item(1f, "Alice"))) - } - - @Test - fun whenAmountIsOneAndNameIsBob_thenTrue() { - assertTrue(Validator().isValid(Item(1f, "Bob"))) - } - - - @Test - fun whenAmountIsMinusOneAndNameIsAlice_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Alice"))) - } - - @Test - fun whenAmountIsMinusOneAndNameIsBob_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Bob"))) - } - - @Test - fun whenAmountIsOneAndNameIsTom_thenFalse() { - assertFalse(Validator().isValid(Item(1f, "Tom"))) - } - - @Test - fun whenAmountIsMinusOneAndNameIsTom_thenFalse() { - assertFalse(Validator().isValid(Item(-1f, "Tom"))) - } - - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmannotations/DocumentTest.kt b/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmannotations/DocumentTest.kt deleted file mode 100644 index 2ec5402e5a..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmannotations/DocumentTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -import com.baeldung.jvmannotations.*; - -class DocumentTest { - - @Test - fun testDefaultMethod() { - - val myDocument = TextDocument() - val myTextDocument = XmlDocument(myDocument) - - assertEquals("text", myDocument.getType()) - assertEquals("text", myTextDocument.getType()) - assertEquals("document", myTextDocument.getTypeDefault()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmfield/JvmSampleTest.kt b/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmfield/JvmSampleTest.kt deleted file mode 100644 index 769c0311c4..0000000000 --- a/core-kotlin-modules/core-kotlin-annotations/src/test/kotlin/com/baeldung/jvmfield/JvmSampleTest.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.jvmfield - -import org.junit.Before -import org.junit.Test -import kotlin.test.assertTrue - -class JvmSampleTest { - - var sample = "" - - @Before - fun setUp() { - sample = JvmSample("Hello!").sampleText - } - - @Test - fun givenField_whenCheckValue_thenMatchesValue() { - assertTrue(sample == "Hello!") - } - - @Test - fun givenStaticVariable_whenCheckValue_thenMatchesValue() { - // Sample when is treated as a static variable - assertTrue(CompanionSample.MAX_LIMIT == 20) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections-2/README.md b/core-kotlin-modules/core-kotlin-collections-2/README.md deleted file mode 100644 index 64062ee704..0000000000 --- a/core-kotlin-modules/core-kotlin-collections-2/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Core Kotlin Collections - -This module contains articles about core Kotlin collections. - -## Relevant articles: - -- [Aggregate Operations in Kotlin](https://www.baeldung.com/kotlin/aggregate-operations) diff --git a/core-kotlin-modules/core-kotlin-collections-2/pom.xml b/core-kotlin-modules/core-kotlin-collections-2/pom.xml deleted file mode 100644 index be462eed45..0000000000 --- a/core-kotlin-modules/core-kotlin-collections-2/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - core-kotlin-collections-2 - core-kotlin-collections-2 - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 1.3.30 - 3.6.1 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt deleted file mode 100644 index a09e101b59..0000000000 --- a/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.baeldung.aggregate - -class AggregateOperations { - private val numbers = listOf(1, 15, 3, 8) - - fun countList(): Int { - return numbers.count() - } - - fun sumList(): Int { - return numbers.sum() - } - - fun averageList(): Double { - return numbers.average() - } - - fun maximumInList(): Int? { - return numbers.max() - } - - fun minimumInList(): Int? { - return numbers.min() - } - - fun maximumByList(): Int? { - return numbers.maxBy { it % 5 } - } - - fun minimumByList(): Int? { - return numbers.minBy { it % 5 } - } - - fun maximumWithList(): String? { - val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") - return strings.maxWith(compareBy { it.length % 4 }) - } - - fun minimumWithList(): String? { - val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") - return strings.minWith(compareBy { it.length % 4 }) - } - - fun sumByList(): Int { - return numbers.sumBy { it * 5 } - } - - fun sumByDoubleList(): Double { - return numbers.sumByDouble { it.toDouble() / 8 } - } - - fun foldList(): Int { - return numbers.fold(100) { total, it -> - println("total = $total, it = $it") - total - it - } // ((((100 - 1)-15)-3)-8) = 73 - } - - fun foldRightList(): Int { - return numbers.foldRight(100) { it, total -> - println("total = $total, it = $it") - total - it - } // ((((100-8)-3)-15)-1) = 73 - } - - fun foldIndexedList(): Int { - return numbers.foldIndexed(100) { index, total, it -> - println("total = $total, it = $it, index = $index") - if (index.minus(2) >= 0) total - it else total - } // ((100 - 3)-8) = 89 - } - - fun foldRightIndexedList(): Int { - return numbers.foldRightIndexed(100) { index, it, total -> - println("total = $total, it = $it, index = $index") - if (index.minus(2) >= 0) total - it else total - } // ((100 - 8)-3) = 89 - } - - fun reduceList(): Int { - return numbers.reduce { total, it -> - println("total = $total, it = $it") - total - it - } // (((1 - 15)-3)-8) = -25 - } - - fun reduceRightList(): Int { - return numbers.reduceRight() { it, total -> - println("total = $total, it = $it") - total - it - } // ((8-3)-15)-1) = -11 - } - - fun reduceIndexedList(): Int { - return numbers.reduceIndexed { index, total, it -> - println("total = $total, it = $it, index = $index") - if (index.minus(2) >= 0) total - it else total - } // ((1-3)-8) = -10 - } - - fun reduceRightIndexedList(): Int { - return numbers.reduceRightIndexed { index, it, total -> - println("total = $total, it = $it, index = $index") - if (index.minus(2) >= 0) total - it else total - } // ((8-3) = 5 - } -} diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt deleted file mode 100644 index a619759b0a..0000000000 --- a/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt +++ /dev/null @@ -1,104 +0,0 @@ -package com.baeldung.aggregate - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class AggregateOperationsUnitTest { - - private val classUnderTest: AggregateOperations = AggregateOperations() - - @Test - fun whenCountOfList_thenReturnsValue() { - assertEquals(4, classUnderTest.countList()) - } - - @Test - fun whenSumOfList_thenReturnsTotalValue() { - assertEquals(27, classUnderTest.sumList()) - } - - @Test - fun whenAverageOfList_thenReturnsValue() { - assertEquals(6.75, classUnderTest.averageList()) - } - - @Test - fun whenMaximumOfList_thenReturnsMaximumValue() { - assertEquals(15, classUnderTest.maximumInList()) - } - - @Test - fun whenMinimumOfList_thenReturnsMinimumValue() { - assertEquals(1, classUnderTest.minimumInList()) - } - - @Test - fun whenMaxByList_thenReturnsLargestValue() { - assertEquals(3, classUnderTest.maximumByList()) - } - - @Test - fun whenMinByList_thenReturnsSmallestValue() { - assertEquals(15, classUnderTest.minimumByList()) - } - - @Test - fun whenMaxWithList_thenReturnsLargestValue(){ - assertEquals("Kolkata", classUnderTest.maximumWithList()) - } - - @Test - fun whenMinWithList_thenReturnsSmallestValue(){ - assertEquals("Barcelona", classUnderTest.minimumWithList()) - } - - @Test - fun whenSumByList_thenReturnsIntegerValue(){ - assertEquals(135, classUnderTest.sumByList()) - } - - @Test - fun whenSumByDoubleList_thenReturnsDoubleValue(){ - assertEquals(3.375, classUnderTest.sumByDoubleList()) - } - - @Test - fun whenFoldList_thenReturnsValue(){ - assertEquals(73, classUnderTest.foldList()) - } - - @Test - fun whenFoldRightList_thenReturnsValue(){ - assertEquals(73, classUnderTest.foldRightList()) - } - - @Test - fun whenFoldIndexedList_thenReturnsValue(){ - assertEquals(89, classUnderTest.foldIndexedList()) - } - - @Test - fun whenFoldRightIndexedList_thenReturnsValue(){ - assertEquals(89, classUnderTest.foldRightIndexedList()) - } - - @Test - fun whenReduceList_thenReturnsValue(){ - assertEquals(-25, classUnderTest.reduceList()) - } - - @Test - fun whenReduceRightList_thenReturnsValue(){ - assertEquals(-11, classUnderTest.reduceRightList()) - } - - @Test - fun whenReduceIndexedList_thenReturnsValue(){ - assertEquals(-10, classUnderTest.reduceIndexedList()) - } - - @Test - fun whenReduceRightIndexedList_thenReturnsValue(){ - assertEquals(5, classUnderTest.reduceRightIndexedList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md deleted file mode 100644 index 2ebb748cba..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Kotlin Collections - -This module contains articles about core Kotlin collections. - -### Relevant articles: - -- [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) -- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) -- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) -- [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) -- [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) -- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) -- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce) -- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) -- [Working With Lists in Kotlin](https://www.baeldung.com/kotlin/lists) -- [Iterating Collections by Index in Kotlin](https://www.baeldung.com/kotlin/iterating-collections-by-index) diff --git a/core-kotlin-modules/core-kotlin-collections/pom.xml b/core-kotlin-modules/core-kotlin-collections/pom.xml deleted file mode 100644 index 52401d267c..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - core-kotlin-collections - core-kotlin-collections - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 1.3.30 - 3.6.1 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt deleted file mode 100644 index 07fb595ede..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/index/IndexedIteration.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.index - -fun main() { - - // Index only - val colors = listOf("Red", "Green", "Blue") - for (i in colors.indices) { - println(colors[i]) - } - - val colorArray = arrayOf("Red", "Green", "Blue") - for (i in colorArray.indices) { - println(colorArray[i]) - } - - (0 until colors.size).forEach { println(colors[it]) } - for (i in 0 until colors.size) { - println(colors[i]) - } - - // Index and Value - colors.forEachIndexed { i, v -> println("The value for index $i is $v") } - for (indexedValue in colors.withIndex()) { - println("The value for index ${indexedValue.index} is ${indexedValue.value}") - } - - for ((i, v) in colors.withIndex()) { - println("The value for index $i is $v") - } - - colors.filterIndexed { i, _ -> i % 2 == 0 } - colors.filterIndexed { _, v -> v == "RED" } -} diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/ListExample.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/ListExample.kt deleted file mode 100644 index a29eabe623..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/kotlin/collections/ListExample.kt +++ /dev/null @@ -1,204 +0,0 @@ -package com.baeldung.kotlin.collections - -import kotlin.collections.List - -class ListExample { - - private val countries = listOf("Germany", "India", "Japan", "Brazil", "Australia") - private val cities = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo", "Sydney") - - fun createList(): List { - val countryList = listOf("Germany", "India", "Japan", "Brazil") - return countryList - } - - fun createMutableList(): MutableList { - val cityList = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo") - return cityList - } - - fun iterateUsingForEachLoop(): List { - val countryLength = mutableListOf() - countries.forEach { it -> - print("$it ") - println(" Length: ${it.length}") - countryLength.add(it.length) - } - return countryLength - } - - fun iterateUsingForLoop(): List { - val countryLength = mutableListOf() - for (country in countries) { - print("$country ") - println(" Length: ${country.length}") - countryLength.add(country.length) - } - return countryLength - } - - fun iterateUsingForLoopRange(): List { - val countryLength = mutableListOf() - for (i in 0 until countries.size) { - print("${countries[i]} ") - println(" Length: ${countries[i].length}") - countryLength.add(countries[i].length) - } - return countryLength - } - - fun iterateUsingForEachIndexedLoop(): List { - val countryLength = mutableListOf() - countries.forEachIndexed { i, e -> - println("country[$i] = $e") - print(" Index: $i") - println(" Length: ${e.length}") - countryLength.add(e.length) - } - return countryLength - } - - fun iterateUsingListIterator() { - val iterator = countries.listIterator() - while (iterator.hasNext()) { - val country = iterator.next() - print("$country ") - } - println() - - while (iterator.hasPrevious()) { - println("Index: ${iterator.previousIndex()}") - } - } - - fun iterateUsingIterator() { - val iterator = cities.iterator() - iterator.next() - iterator.remove() - println(cities) - } - - fun iterateUsingMutableListIterator() { - val iterator = cities.listIterator(1) - iterator.next() - iterator.add("London") - iterator.next() - iterator.set("Milan") - println(cities) - } - - fun retrieveElementsInList(): String { - println(countries[2]) - return countries[2] - } - - fun retrieveElementsUsingGet(): String { - println(countries.get(3)) - return countries.get(3) - } - - fun retrieveElementsFirstAndLast(): String? { - println(countries.first()) - println(countries.last()) - println(countries.first { it.length > 7 }) - println(countries.last { it.startsWith("J") }) - println(countries.firstOrNull { it.length > 8 }) - return countries.firstOrNull { it.length > 8 } - } - - fun retrieveSubList(): List { - val subList = countries.subList(1, 4) - println(subList) - return subList - } - - fun retrieveListSliceUsingIndices(): List { - val sliceList = countries.slice(1..4) - println(sliceList) - return sliceList - } - - fun retrieveListSliceUsingIndicesList(): List { - val sliceList = countries.slice(listOf(1, 4)) - println(sliceList) - return sliceList - } - - fun countList(): Int { - val count = countries.count() - println(count) - return count - } - - fun countListUsingPredicate(): Int { - val count = countries.count { it.length > 5 } - println(count) - return count - } - - fun countListUsingProperty(): Int { - val size = countries.size - println(size) - return size - } - - fun addToList(): List { - cities.add("Barcelona") - println(cities) - cities.add(3, "London") - println(cities) - cities.addAll(listOf("Singapore", "Moscow")) - println(cities) - cities.addAll(2, listOf("Prague", "Amsterdam")) - println(cities) - return cities - } - - fun removeFromList(): List { - cities.remove("Seoul") - println(cities) - cities.removeAt(1) - println(cities) - return cities - } - - fun replaceFromList(): List { - cities.set(3, "Prague") - println(cities) - cities[4] = "Moscow" - println(cities) - cities.fill("Barcelona") - println(cities) - return cities - } - - fun sortMutableList(): List { - cities.sort() - println(cities) - cities.sortDescending() - println(cities) - return cities - } - - fun sortList(): List { - val sortedCountries = countries.sorted() - println("countries = $countries") - println("sortedCountries = $sortedCountries") - val sortedCountriesDescending = countries.sortedDescending() - println("countries = $countries") - println("sortedCountriesDescending = $sortedCountriesDescending") - return sortedCountriesDescending - } - - fun checkOneElementInList(): Boolean { - return countries.contains("Germany") - } - - fun checkOneElementInListUsingOperator(): Boolean { - return "Spain" in countries - } - - fun checkElementsInList(): Boolean { - return cities.containsAll(listOf("Calcutta", "Sao Paulo", "Sydney")) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting/SortingExample.kt deleted file mode 100644 index bf3163bc8f..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/sorting/SortingExample.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.sorting - -fun sortMethodUsage() { - val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) - sortedValues.sort() - println(sortedValues) -} - -fun sortByMethodUsage() { - val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") - sortedValues.sortBy { it.second } - println(sortedValues) -} - -fun sortWithMethodUsage() { - val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") - sortedValues.sortWith(compareBy({it.second}, {it.first})) - println(sortedValues) -} - -fun > getSimpleComparator() : Comparator { - val ascComparator = naturalOrder() - return ascComparator -} - -fun getComplexComparator() { - val complexComparator = compareBy>({it.first}, {it.second}) -} - -fun nullHandlingUsage() { - val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e") - sortedValues.sortWith(nullsLast(compareBy { it.second })) - println(sortedValues) -} - -fun extendedComparatorUsage() { - val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim") - - val ageComparator = compareBy> {it.first} - val ageAndNameComparator = ageComparator.thenByDescending {it.second} - println(students.sortedWith(ageAndNameComparator)) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt deleted file mode 100644 index 67fbb29026..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/CollectionsTest.kt +++ /dev/null @@ -1,212 +0,0 @@ -package com.baeldung.collections - -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class CollectionsTest { - - @Test - fun whenUseDifferentCollections_thenSuccess() { - val theList = listOf("one", "two", "three") - assertTrue(theList.contains("two")) - - val theMutableList = mutableListOf("one", "two", "three") - theMutableList.add("four") - assertTrue(theMutableList.contains("four")) - - val theSet = setOf("one", "two", "three") - assertTrue(theSet.contains("three")) - - val theMutableSet = mutableSetOf("one", "two", "three") - theMutableSet.add("four") - assertTrue(theMutableSet.contains("four")) - - val theMap = mapOf(1 to "one", 2 to "two", 3 to "three") - assertEquals(theMap[2], "two") - - val theMutableMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three") - theMutableMap[4] = "four" - assertEquals(theMutableMap[4], "four") - } - - @Test - fun whenSliceCollection_thenSuccess() { - val theList = listOf("one", "two", "three") - val resultList = theList.slice(1..2) - - assertEquals(2, resultList.size) - assertTrue(resultList.contains("two")) - } - - @Test - fun whenJoinTwoCollections_thenSuccess() { - val firstList = listOf("one", "two", "three") - val secondList = listOf("four", "five", "six") - val resultList = firstList + secondList - - assertEquals(6, resultList.size) - assertTrue(resultList.contains("two")) - assertTrue(resultList.contains("five")) - } - - @Test - fun whenFilterNullValues_thenSuccess() { - val theList = listOf("one", null, "two", null, "three") - val resultList = theList.filterNotNull() - - assertEquals(3, resultList.size) - } - - @Test - fun whenFilterNonPositiveValues_thenSuccess() { - val theList = listOf(1, 2, -3, -4, 5, -6) - val resultList = theList.filter { it > 0 } - //val resultList = theList.filter{ x -> x > 0} - - assertEquals(3, resultList.size) - assertTrue(resultList.contains(1)) - assertFalse(resultList.contains(-4)) - } - - @Test - fun whenDropFirstItems_thenRemoved() { - val theList = listOf("one", "two", "three", "four") - val resultList = theList.drop(2) - - assertEquals(2, resultList.size) - assertFalse(resultList.contains("one")) - assertFalse(resultList.contains("two")) - } - - @Test - fun whenDropFirstItemsBasedOnCondition_thenRemoved() { - val theList = listOf("one", "two", "three", "four") - val resultList = theList.dropWhile { it.length < 4 } - - assertEquals(2, resultList.size) - assertFalse(resultList.contains("one")) - assertFalse(resultList.contains("two")) - } - - @Test - fun whenExcludeItems_thenRemoved() { - val firstList = listOf("one", "two", "three") - val secondList = listOf("one", "three") - val resultList = firstList - secondList - - assertEquals(1, resultList.size) - assertTrue(resultList.contains("two")) - } - - @Test - fun whenSearchForExistingItem_thenFound() { - val theList = listOf("one", "two", "three") - - assertTrue("two" in theList) - } - - @Test - fun whenGroupItems_thenSuccess() { - val theList = listOf(1, 2, 3, 4, 5, 6) - val resultMap = theList.groupBy { it % 3 } - - assertEquals(3, resultMap.size) - print(resultMap[1]) - assertTrue(resultMap[1]!!.contains(1)) - assertTrue(resultMap[2]!!.contains(5)) - } - - @Test - fun whenApplyFunctionToAllItems_thenSuccess() { - val theList = listOf(1, 2, 3, 4, 5, 6) - val resultList = theList.map { it * it } - print(resultList) - assertEquals(4, resultList[1]) - assertEquals(9, resultList[2]) - } - - @Test - fun whenApplyMultiOutputFunctionToAllItems_thenSuccess() { - val theList = listOf("John", "Tom") - val resultList = theList.flatMap { it.toLowerCase().toList() } - print(resultList) - assertEquals(7, resultList.size) - assertTrue(resultList.contains('j')) - } - - @Test - fun whenApplyFunctionToAllItemsWithStartingValue_thenSuccess() { - val theList = listOf(1, 2, 3, 4, 5, 6) - val finalResult = theList.fold(1000, { oldResult, currentItem -> oldResult + (currentItem * currentItem) }) - print(finalResult) - assertEquals(1091, finalResult) - } - - @Test - fun whenApplyingChunked_thenShouldBreakTheCollection() { - val theList = listOf(1, 2, 3, 4, 5) - val chunked = theList.chunked(2) - - assertThat(chunked.size).isEqualTo(3) - assertThat(chunked.first()).contains(1, 2) - assertThat(chunked[1]).contains(3, 4) - assertThat(chunked.last()).contains(5) - } - - @Test - fun whenApplyingChunkedWithTransformation_thenShouldBreakTheCollection() { - val theList = listOf(1, 2, 3, 4, 5) - val chunked = theList.chunked(3) { it.joinToString(", ") } - - assertThat(chunked.size).isEqualTo(2) - assertThat(chunked.first()).isEqualTo("1, 2, 3") - assertThat(chunked.last()).isEqualTo("4, 5") - } - - @Test - fun whenApplyingWindowed_thenShouldCreateSlidingWindowsOfElements() { - val theList = (1..6).toList() - val windowed = theList.windowed(3) - - assertThat(windowed.size).isEqualTo(4) - assertThat(windowed.first()).contains(1, 2, 3) - assertThat(windowed[1]).contains(2, 3, 4) - assertThat(windowed[2]).contains(3, 4, 5) - assertThat(windowed.last()).contains(4, 5, 6) - } - - @Test - fun whenApplyingWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() { - val theList = (1..6).toList() - val windowed = theList.windowed(size = 3, step = 2) - - assertThat(windowed.size).isEqualTo(2) - assertThat(windowed.first()).contains(1, 2, 3) - assertThat(windowed.last()).contains(3, 4, 5) - } - - @Test - fun whenApplyingPartialWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() { - val theList = (1..6).toList() - val windowed = theList.windowed(size = 3, step = 2, partialWindows = true) - - assertThat(windowed.size).isEqualTo(3) - assertThat(windowed.first()).contains(1, 2, 3) - assertThat(windowed[1]).contains(3, 4, 5) - assertThat(windowed.last()).contains(5, 6) - } - - @Test - fun whenApplyingTransformingWindows_thenShouldCreateSlidingWindowsOfElements() { - val theList = (1..6).toList() - val windowed = theList.windowed(size = 3, step = 2, partialWindows = true) { it.joinToString(", ") } - - assertThat(windowed.size).isEqualTo(3) - assertThat(windowed.first()).isEqualTo("1, 2, 3") - assertThat(windowed[1]).isEqualTo("3, 4, 5") - assertThat(windowed.last()).isEqualTo("5, 6") - } -} diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt deleted file mode 100644 index 68f7040c4c..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/AssociateUnitTest.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class AssociateUnitTest { - @Test - fun testToMap() { - val input = listOf(Pair("one", 1), Pair("two", 2)) - val map = input.toMap() - assertEquals(mapOf("one" to 1, "two" to 2), map) - } - - @Test - fun testAssociateWith() { - val inputs = listOf("Hi", "there") - val map = inputs.associateWith { k -> k.length } - assertEquals(mapOf("Hi" to 2, "there" to 5), map) - } - - @Test - fun testAssociateBy() { - val inputs = listOf("Hi", "there") - val map = inputs.associateBy { v -> v.length } - assertEquals(mapOf(2 to "Hi", 5 to "there"), map) - } - - @Test - fun testAssociate() { - val inputs = listOf("Hi", "there") - val map = inputs.associate { e -> Pair(e.toUpperCase(), e.reversed()) } - assertEquals(mapOf("HI" to "iH", "THERE" to "ereht"), map) - } - - @Test - fun testAssociateByDuplicateKeys() { - val inputs = listOf("one", "two") - val map = inputs.associateBy { v -> v.length } - assertEquals(mapOf(3 to "two"), map) - } - - @Test - fun testGroupBy() { - val inputs = listOf("one", "two", "three") - val map = inputs.groupBy { v -> v.length } - assertEquals(mapOf(3 to listOf("one", "two"), 5 to listOf("three")), map) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt deleted file mode 100644 index 591577e4f3..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FilterUnitTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class FilterUnitTest { - @Test - fun testFilterWithLambda() { - val input = listOf(1, 2, 3, 4, 5) - val filtered = input.filter { it <= 3 } - assertEquals(listOf(1, 2, 3), filtered) - } - - @Test - fun testFilterWithMethodReference() { - val input = listOf(1, 2, 3, 4, 5) - val filtered = input.filter(this::isSmall) - assertEquals(listOf(1, 2, 3), filtered) - } - - @Test - fun testFilterNotWithMethodReference() { - val input = listOf(1, 2, 3, 4, 5) - val filtered = input.filterNot(this::isSmall) - assertEquals(listOf(4, 5), filtered) - } - - @Test - fun testFilterIndexed() { - val input = listOf(5, 4, 3, 2, 1) - val filtered = input.filterIndexed { index, element -> index < 3 } - assertEquals(listOf(5, 4, 3), filtered) - } - - @Test - fun testFilterNotNull() { - val nullable: List = listOf("Hello", null, "World") - val nonnull: List = nullable.filterNotNull() - assertEquals(listOf("Hello", "World"), nonnull) - } - - private fun isSmall(i: Int) = i <= 3 -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt deleted file mode 100644 index 69fbceb8e3..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/FlattenUnitTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class FlattenUnitTest { - @Test - fun testFlatten() { - val inputs = listOf("one", "two", "three") - val characters = inputs.map(String::toList) - val flattened = characters.flatten(); - assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), flattened) - } - - @Test - fun testFlatMap() { - val inputs = listOf("one", "two", "three") - val characters = inputs.flatMap(String::toList) - assertEquals(listOf('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e'), characters) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt deleted file mode 100644 index 2ac0cdca50..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/JoinToUnitTest.kt +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class JoinToUnitTest { - @Test - fun testJoinToString() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val simpleString = inputs.joinToString() - assertEquals("Jan, Feb, Mar, Apr, May", simpleString) - - val detailedString = inputs.joinToString(separator = ",", prefix="Months: ", postfix=".") - assertEquals("Months: Jan,Feb,Mar,Apr,May.", detailedString) - } - - @Test - fun testJoinToStringLimits() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val simpleString = inputs.joinToString(limit = 3) - assertEquals("Jan, Feb, Mar, ...", simpleString) - } - - @Test - fun testJoinToStringTransform() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val simpleString = inputs.joinToString(transform = String::toUpperCase) - assertEquals("JAN, FEB, MAR, APR, MAY", simpleString) - } - - @Test - fun testJoinTo() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val output = StringBuilder() - output.append("My ") - .append(inputs.size) - .append(" elements: ") - inputs.joinTo(output) - - assertEquals("My 5 elements: Jan, Feb, Mar, Apr, May", output.toString()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt deleted file mode 100644 index e22fcbe903..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/MapUnitTest.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class MapUnitTest { - @Test - fun testMapWithLambda() { - val input = listOf("one", "two", "three") - - val reversed = input.map { it.reversed() } - assertEquals(listOf("eno", "owt", "eerht"), reversed) - - val lengths = input.map { it.length } - assertEquals(listOf(3, 3, 5), lengths) - } - - @Test - fun testMapIndexed() { - val input = listOf(3, 2, 1) - val result = input.mapIndexed { index, value -> index * value } - assertEquals(listOf(0, 2, 2), result) - } - - @Test - fun testMapNotNull() { - val input = listOf(1, 2, 3, 4, 5) - val smallSquares = input.mapNotNull { - if (it <= 3) { - it * it - } else { - null - } - } - assertEquals(listOf(1, 4, 9), smallSquares) - } - - @Test - fun mapMapKeys() { - val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) - - val uppercases = inputs.mapKeys { it.key.toUpperCase() } - assertEquals(mapOf("ONE" to 1, "TWO" to 2, "THREE" to 3), uppercases) - } - - @Test - fun mapMapValues() { - val inputs = mapOf("one" to 1, "two" to 2, "three" to 3) - - val squares = inputs.mapValues { it.value * it.value } - assertEquals(mapOf("one" to 1, "two" to 4, "three" to 9), squares) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt deleted file mode 100644 index 6821b7cdb9..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ReduceUnitTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class ReduceUnitTest { - @Test - fun testJoinToStringAsReduce() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val result = inputs.reduce { acc, next -> "$acc, $next" } - assertEquals("Jan, Feb, Mar, Apr, May", result) - } - - @Test - fun testFoldToLength() { - val inputs = listOf("Jan", "Feb", "Mar", "Apr", "May") - - val result = inputs.fold(0) { acc, next -> acc + next.length } - assertEquals(15, result) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt deleted file mode 100644 index 66aeeceef4..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/transformations/ZipUnitTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.collections.transformations - -import org.junit.Assert.assertEquals -import org.junit.Test - -class ZipUnitTest { - @Test - fun testZip() { - val left = listOf("one", "two", "three") - val right = listOf(1, 2, 3) - val zipped = left.zip(right) - assertEquals (listOf(Pair("one", 1), Pair("two", 2), Pair("three", 3)), zipped) - } - - @Test - fun testZipShort() { - val left = listOf("one", "two") - val right = listOf(1, 2, 3) - val zipped = left.zip(right) - assertEquals (listOf(Pair("one", 1), Pair("two", 2)), zipped) - } - - @Test - fun testUnzip() { - val left = listOf("one", "two", "three") - val right = listOf(1, 2, 3) - val zipped = left.zip(right) - - val (newLeft, newRight) = zipped.unzip() - assertEquals(left, newLeft) - assertEquals(right, newRight) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt deleted file mode 100644 index 20797cc633..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/ChunkedTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.filter - -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Test - -internal class ChunkedTest { - - @Test - fun givenDNAFragmentString_whenChunking_thenProduceListOfChunks() { - val dnaFragment = "ATTCGCGGCCGCCAA" - - val fragments = dnaFragment.chunked(3) - - assertIterableEquals(listOf("ATT", "CGC", "GGC", "CGC", "CAA"), fragments) - } - - @Test - fun givenDNAString_whenChunkingWithTransformer_thenProduceTransformedList() { - val codonTable = mapOf("ATT" to "Isoleucine", "CAA" to "Glutamine", "CGC" to "Arginine", "GGC" to "Glycine") - val dnaFragment = "ATTCGCGGCCGCCAA" - - val proteins = dnaFragment.chunked(3) { codon -> - codonTable[codon.toString()] ?: error("Unknown codon") - } - - assertIterableEquals(listOf("Isoleucine", "Arginine", "Glycine", "Arginine", "Glutamine"), proteins) - } - - @Test - fun givenListOfValues_whenChunking_thenProduceListOfArrays() { - val whole = listOf(1, 4, 7, 4753, 2, 34, 62, 76, 5868, 0) - val chunks = whole.chunked(6) - - val expected = listOf(listOf(1, 4, 7, 4753, 2, 34), listOf(62, 76, 5868, 0)) - - assertIterableEquals(expected, chunks) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DistinctTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DistinctTest.kt deleted file mode 100644 index 4cc6f647e1..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DistinctTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.filter - -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Test - -internal class DistinctTest { - data class SmallClass(val key: String, val num: Int) - - @Test - fun whenApplyingDistinct_thenReturnListOfNoDuplicateValues() { - val array = arrayOf(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9) - val result = array.distinct() - val expected = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9) - - assertIterableEquals(expected, result) - } - - @Test - fun givenArrayOfClassObjects_whenApplyingDistinctOnClassProperty_thenReturnListDistinctOnThatValue() { - - val original = arrayOf( - SmallClass("key1", 1), - SmallClass("key2", 2), - SmallClass("key3", 3), - SmallClass("key4", 3), - SmallClass("er", 9), - SmallClass("er", 10), - SmallClass("er", 11)) - - val actual = original.distinctBy { it.key } - - val expected = listOf( - SmallClass("key1", 1), - SmallClass("key2", 2), - SmallClass("key3", 3), - SmallClass("key4", 3), - SmallClass("er", 9)) - - - assertIterableEquals(expected, actual) - } - - @Test - fun givenArrayOfClassObjects_whenApplyingComplicatedSelector_thenReturnFirstElementToMatchEachSelectorValue() { - val array = arrayOf( - SmallClass("key1", 1), - SmallClass("key2", 2), - SmallClass("key3", 3), - SmallClass("key4", 3), - SmallClass("er", 9), - SmallClass("er", 10), - SmallClass("er", 11), - SmallClass("er", 11), - SmallClass("er", 91), - SmallClass("blob", 22), - SmallClass("dob", 27), - SmallClass("high", 201_434_314)) - - val actual = array.distinctBy { Math.floor(it.num / 10.0) } - - val expected = listOf( - SmallClass("key1", 1), - SmallClass("er", 10), - SmallClass("er", 91), - SmallClass("blob", 22), - SmallClass("high", 201_434_314)) - - assertIterableEquals(expected, actual) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DropTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DropTest.kt deleted file mode 100644 index 7c2685f39b..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/DropTest.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.filter - -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Test - -internal class DropTest { - - @Test - fun whenDroppingFirstTwoItemsOfArray_thenTwoLess() { - val array = arrayOf(1, 2, 3, 4) - val result = array.drop(2) - val expected = listOf(3, 4) - - assertIterableEquals(expected, result) - } - - @Test - fun whenDroppingMoreItemsOfArray_thenEmptyList() { - val array = arrayOf(1, 2, 3, 4) - val result = array.drop(5) - val expected = listOf() - - assertIterableEquals(expected, result) - } - - @Test - fun givenArray_whenDroppingLastElement_thenReturnListWithoutLastElement() { - val array = arrayOf("1", "2", "3", "4") - val result = array.dropLast(1) - val expected = listOf("1", "2", "3") - - assertIterableEquals(expected, result) - } - - @Test - fun givenArrayOfFloats_whenDroppingLastUntilPredicateIsFalse_thenReturnSubsetListOfFloats() { - val array = arrayOf(1f, 1f, 1f, 1f, 1f, 2f, 1f, 1f, 1f) - val result = array.dropLastWhile { it == 1f } - val expected = listOf(1f, 1f, 1f, 1f, 1f, 2f) - - assertIterableEquals(expected, result) - } - - @Test - fun givenList_whenDroppingMoreThanAvailable_thenThrowException() { - val list = listOf('a', 'e', 'i', 'o', 'u') - val result = list.drop(6) - val expected: List = listOf() - - assertIterableEquals(expected, result) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/FilterTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/FilterTest.kt deleted file mode 100644 index efe6354f25..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/FilterTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.filter - -import org.apache.commons.math3.primes.Primes -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Test -import kotlin.test.assertTrue - -internal class FilterTest { - - @Test - fun givenAscendingValueMap_whenFilteringOnValue_ThenReturnSubsetOfMap() { - val originalMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3) - val filteredMap = originalMap.filter { it.value < 2 } - val expectedMap = mapOf("key1" to 1) - - assertTrue { expectedMap == filteredMap } - } - - @Test - fun givenSeveralCollections_whenFilteringToAccumulativeList_thenListContainsAllContents() { - val array1 = arrayOf(90, 92, 93, 94, 92, 95, 93) - val array2 = sequenceOf(51, 31, 83, 674_506_111, 256_203_161, 15_485_863) - val list1 = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) - val primes = mutableListOf() - - val expected = listOf(2, 3, 5, 7, 31, 83, 15_485_863, 256_203_161, 674_506_111) - - val primeCheck = { num: Int -> Primes.isPrime(num) } - - array1.filterTo(primes, primeCheck) - list1.filterTo(primes, primeCheck) - array2.filterTo(primes, primeCheck) - - primes.sort() - - assertIterableEquals(expected, primes) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/SliceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/SliceTest.kt deleted file mode 100644 index 793fe68427..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/SliceTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.filter - -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Assertions.assertThrows -import org.junit.jupiter.api.Test - -internal class SliceTest { - - @Test - fun whenSlicingAnArrayWithDotRange_ThenListEqualsTheSlice() { - val original = arrayOf(1, 2, 3, 2, 1) - val actual = original.slice(1..3) - val expected = listOf(2, 3, 2) - - assertIterableEquals(expected, actual) - } - - @Test - fun whenSlicingAnArrayWithDownToRange_thenListMadeUpOfReverseSlice() { - val original = arrayOf(1, 2, 3, 2, 1) - val actual = original.slice(3 downTo 0) - val expected = listOf(2, 3, 2, 1) - - assertIterableEquals(expected, actual) - } - -// From the 1.3 version of Kotlin APIs, slice doesn't return array of nulls but throw IndexOutOfBoundsException -// @Test -// fun whenSlicingBeyondTheRangeOfTheArray_thenContainManyNulls() { -// val original = arrayOf(12, 3, 34, 4) -// val actual = original.slice(3..8) -// val expected = listOf(4, null, null, null, null, null) -// -// assertIterableEquals(expected, actual) -// } - - @Test - fun whenSlicingBeyondRangeOfArrayWithStep_thenOutOfBoundsException() { - assertThrows(ArrayIndexOutOfBoundsException::class.java) { - val original = arrayOf(12, 3, 34, 4) - original.slice(3..8 step 2) - } - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/TakeTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/TakeTest.kt deleted file mode 100644 index d021177de8..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/filter/TakeTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.filter - -import org.junit.jupiter.api.Assertions.assertIterableEquals -import org.junit.jupiter.api.Test - -internal class TakeTest { - - @Test - fun `given array of alternating types, when predicating on 'is String', then produce list of array up until predicate is false`() { - val originalArray = arrayOf("val1", 2, "val3", 4, "val5", 6) - val actualList = originalArray.takeWhile { it is String } - val expectedList = listOf("val1") - - assertIterableEquals(expectedList, actualList) - } - - @Test - fun `given array of alternating types, when taking 4 items, then produce list of first 4 items`() { - val originalArray = arrayOf("val1", 2, "val3", 4, "val5", 6) - val actualList = originalArray.take(4) - val expectedList = listOf("val1", 2, "val3", 4) - - println(originalArray.drop(4)) - println(actualList) - - assertIterableEquals(expectedList, actualList) - } - - @Test - fun `when taking more items than available, then return all elements`() { - val originalArray = arrayOf(1, 2) - val actual = originalArray.take(10) - val expected = listOf(1, 2) - - assertIterableEquals(expected, actual) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt deleted file mode 100644 index 52e7e2a5b5..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/findelement/FindAnElementInAListUnitTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.findelement - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class FindAnElementInAListUnitTest { - - var batmans: List = listOf("Christian Bale", "Michael Keaton", "Ben Affleck", "George Clooney") - - @Test - fun whenFindASpecificItem_thenItemIsReturned() { - //Returns the first element matching the given predicate, or null if no such element was found. - val theFirstBatman = batmans.find { actor -> "Michael Keaton".equals(actor) } - assertEquals(theFirstBatman, "Michael Keaton") - } - - @Test - fun whenFilterWithPredicate_thenMatchingItemsAreReturned() { - //Returns a list containing only elements matching the given predicate. - val theCoolestBatmans = batmans.filter { actor -> actor.contains("a") } - assertTrue(theCoolestBatmans.contains("Christian Bale") && theCoolestBatmans.contains("Michael Keaton")) - } - - @Test - fun whenFilterNotWithPredicate_thenMatchingItemsAreReturned() { - //Returns a list containing only elements not matching the given predicate. - val theMehBatmans = batmans.filterNot { actor -> actor.contains("a") } - assertFalse(theMehBatmans.contains("Christian Bale") && theMehBatmans.contains("Michael Keaton")) - assertTrue(theMehBatmans.contains("Ben Affleck") && theMehBatmans.contains("George Clooney")) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt deleted file mode 100644 index 7b263914c6..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/foldvsreduce/FoldAndReduceTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.foldvsreduce - -import org.junit.Test -import org.junit.jupiter.api.assertThrows -import java.lang.RuntimeException -import kotlin.test.assertEquals - -class FoldAndReduceTest { - - @Test - fun testReduceLimitations() { - val numbers: List = listOf(1, 2, 3) - val sum: Number = numbers.reduce { acc, next -> acc + next } - assertEquals(6, sum) - - val emptyList = listOf() - assertThrows { emptyList.reduce { acc, next -> acc + next } } - - // doesn't compile - // val sum = numbers.reduce { acc, next -> acc.toLong() + next.toLong()} - } - - @Test - fun testFold() { - - val numbers: List = listOf(1, 2, 3) - val sum: Int = numbers.fold(0, { acc, next -> acc + next }) - assertEquals(6, sum) - - //change result type - val sumLong: Long = numbers.fold(0L, { acc, next -> acc + next.toLong() }) - assertEquals(6L, sumLong) - - val emptyList = listOf() - val emptySum = emptyList.fold(0, { acc, next -> acc + next }) - assertEquals(0, emptySum) - - //power of changing result type - val (even, odd) = numbers.fold(Pair(listOf(), listOf()), { acc, next -> - if (next % 2 == 0) Pair(acc.first + next, acc.second) - else Pair(acc.first, acc.second + next) - }) - - assertEquals(listOf(2), even) - assertEquals(listOf(1, 3), odd) - } - - @Test - fun testVariationsOfFold() { - val numbers = listOf(1, 2, 3) - val reversed = numbers.foldRight(listOf(), { next, acc -> acc + next}) - assertEquals(listOf(3,2,1), reversed) - - val reversedIndexes = numbers.foldRightIndexed(listOf(), { i, _, acc -> acc + i }) - assertEquals(listOf(2,1,0), reversedIndexes) - } - - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/ListExampleUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/ListExampleUnitTest.kt deleted file mode 100644 index 71fe3bf1e0..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/kotlin/collections/ListExampleUnitTest.kt +++ /dev/null @@ -1,126 +0,0 @@ -package com.baeldung.kotlin.collections - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.Assertions.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class ListExampleUnitTest { - - private val classUnderTest: ListExample = ListExample() - - @Test - fun whenListIsCreated_thenContainsElements() { - assertTrue(classUnderTest.createList().contains("India")) - assertTrue(classUnderTest.createMutableList().contains("Seoul")) - } - - @Test - fun whenIterateUsingForEachLoop_thenSuccess() { - assertEquals(7, classUnderTest.iterateUsingForEachLoop()[0]) - } - - @Test - fun whenIterateUsingForLoop_thenSuccess() { - assertEquals(5, classUnderTest.iterateUsingForLoop()[1]) - } - - @Test - fun whenIterateUsingForLoopRange_thenSuccess() { - assertEquals(6, classUnderTest.iterateUsingForLoopRange()[3]) - } - - @Test - fun whenIterateUsingForEachIndexedLoop_thenSuccess() { - assertEquals(9, classUnderTest.iterateUsingForEachIndexedLoop()[4]) - } - - @Test - fun whenRetrieveElementsInList_thenSuccess() { - assertEquals("Japan", classUnderTest.retrieveElementsInList()) - } - - @Test - fun whenRetrieveElementsUsingGet_thenSuccess() { - assertEquals("Brazil", classUnderTest.retrieveElementsUsingGet()) - } - - @Test - fun whenRetrieveElementsFirstAndLast_thenSuccess() { - assertEquals("Australia", classUnderTest.retrieveElementsFirstAndLast()) - } - - @Test - fun whenRetrieveSubList_thenSuccess() { - assertEquals(3, classUnderTest.retrieveSubList().size) - } - - @Test - fun whenRetrieveListSliceUsingIndices_thenSuccess() { - assertEquals(4, classUnderTest.retrieveListSliceUsingIndices().size) - } - - @Test - fun whenRetrieveListSliceUsingIndicesList_thenSuccess() { - assertEquals(2, classUnderTest.retrieveListSliceUsingIndicesList().size) - } - - @Test - fun whenCountList_thenSuccess() { - assertEquals(5, classUnderTest.countList()) - } - - @Test - fun whenCountListUsingPredicate_thenSuccess() { - assertEquals(3, classUnderTest.countListUsingPredicate()) - } - - @Test - fun whenCountListUsingProperty_thenSuccess() { - assertEquals(5, classUnderTest.countListUsingProperty()) - } - - @Test - fun whenAddToList_thenSuccess() { - assertEquals(11, classUnderTest.addToList().count()) - } - - @Test - fun whenRemoveFromList_thenSuccess() { - val list = classUnderTest.removeFromList() - assertEquals(3, list.size) - assertEquals("Sao Paulo", list[1]) - } - - @Test - fun whenReplaceFromList_thenSuccess() { - val list = classUnderTest.replaceFromList() - assertEquals(5, list.size) - assertEquals("Barcelona", list[1]) - } - - @Test - fun whenSortMutableList_thenSuccess() { - assertEquals("Sydney", classUnderTest.sortMutableList()[0]) - } - - @Test - fun whenSortList_thenSuccess() { - assertEquals("India", classUnderTest.sortList()[1]) - } - - @Test - fun whenCheckOneElementInList_thenSuccess() { - assertTrue(classUnderTest.checkOneElementInList()) - } - - @Test - fun whenCheckOneElementInListUsingOperator_thenSuccess() { - assertFalse(classUnderTest.checkOneElementInListUsingOperator()) - } - - @Test - fun whenCheckElementsInList_thenSuccess() { - assertTrue(classUnderTest.checkElementsInList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt deleted file mode 100644 index 93e4f11fdf..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/ListToMapTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.listtomap - -import org.junit.Test -import kotlin.test.assertTrue - -class ListToMapTest { - - val user1 = User("John", 18, listOf("Hiking, Swimming")) - val user2 = User("Sara", 25, listOf("Chess, Board Games")) - val user3 = User("Dave", 34, listOf("Games, Racing sports")) - val user4 = User("John", 30, listOf("Reading, Poker")) - - @Test - fun givenList_whenConvertToMap_thenResult() { - val myList = listOf(user1, user2, user3) - val myMap = myList.map { it.name to it.age }.toMap() - - assertTrue(myMap.get("John") == 18) - } - - @Test - fun givenList_whenAssociatedBy_thenResult() { - val myList = listOf(user1, user2, user3) - val myMap = myList.associateBy({ it.name }, { it.hobbies }) - - assertTrue(myMap.get("John")!!.contains("Hiking, Swimming")) - } - - @Test - fun givenStringList_whenConvertToMap_thenResult() { - val myList = listOf("a", "b", "c") - val myMap = myList.map { it to it }.toMap() - - assertTrue(myMap.get("a") == "a") - } - - @Test - fun givenStringList_whenAssociate_thenResult() { - val myList = listOf("a", "b", "c", "c", "b") - val myMap = myList.associate{ it to it } - - assertTrue(myMap.get("a") == "a") - } - - @Test - fun givenStringList_whenAssociateTo_thenResult() { - val myList = listOf("a", "b", "c", "c", "b") - val myMap = mutableMapOf() - - myList.associateTo(myMap) {it to it} - - assertTrue(myMap.get("a") == "a") - } - - @Test - fun givenStringList_whenAssociateByTo_thenResult() { - val myList = listOf(user1, user2, user3, user4) - val myMap = mutableMapOf() - - myList.associateByTo(myMap, {it.name}, {it.age}) - - assertTrue(myMap.get("Dave") == 34) - } - - @Test - fun givenStringList_whenAssociateByToUser_thenResult() { - val myList = listOf(user1, user2, user3, user4) - val myMap = mutableMapOf() - - myList.associateByTo(myMap) {it.name} - - assertTrue(myMap.get("Dave")!!.age == 34) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt deleted file mode 100644 index 89eb9ac701..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/listtomap/User.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.listtomap - -data class User(val name: String, val age: Int, val hobbies: List) diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt deleted file mode 100644 index 7ac0efa4ef..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.sorting - -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test - -class SortingExampleKtTest { - - @Test - fun naturalOrderComparator_ShouldBeAscendingTest() { - val resultingList = listOf(1, 5, 6, 6, 2, 3, 4).sortedWith(getSimpleComparator()) - assertTrue(listOf(1, 2, 3, 4, 5, 6, 6) == resultingList) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt deleted file mode 100644 index 627c7eaacf..0000000000 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/splitlist/SplitListIntoPartsTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.splitlist - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class SplitListIntoPartsTest { - private val evenList = listOf(0, "a", 1, "b", 2, "c"); - - private val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); - - private fun verifyList(resultList: List>) { - assertEquals("[[0, a], [1, b], [2, c]]", resultList.toString()) - } - - private fun verifyPartialList(resultList: List>) { - assertEquals("[[0, a], [1, b], [2, c], [3]]", resultList.toString()) - } - - @Test - fun whenChunked_thenListIsSplit() { - val resultList = evenList.chunked(2) - verifyList(resultList) - } - - @Test - fun whenUnevenChunked_thenListIsSplit() { - val resultList = unevenList.chunked(2) - verifyPartialList(resultList) - } - - @Test - fun whenWindowed_thenListIsSplit() { - val resultList = evenList.windowed(2, 2) - verifyList(resultList) - } - - @Test - fun whenUnevenPartialWindowed_thenListIsSplit() { - val resultList = unevenList.windowed(2, 2, partialWindows = true) - verifyPartialList(resultList) - } - - @Test - fun whenUnevenWindowed_thenListIsSplit() { - val resultList = unevenList.windowed(2, 2, partialWindows = false) - verifyList(resultList) - } - - @Test - fun whenGroupByWithAscendingNumbers_thenListIsSplit() { - val numberList = listOf(1, 2, 3, 4, 5, 6); - val resultList = numberList.groupBy { (it + 1) / 2 } - assertEquals("[[1, 2], [3, 4], [5, 6]]", resultList.values.toString()) - assertEquals("[1, 2, 3]", resultList.keys.toString()) - } - - @Test - fun whenGroupByWithAscendingNumbersUneven_thenListIsSplit() { - val numberList = listOf(1, 2, 3, 4, 5, 6, 7); - val resultList = numberList.groupBy { (it + 1) / 2 }.values - assertEquals("[[1, 2], [3, 4], [5, 6], [7]]", resultList.toString()) - } - - @Test - fun whenGroupByWithRandomNumbers_thenListIsSplitInWrongWay() { - val numberList = listOf(1, 3, 8, 20, 23, 30); - val resultList = numberList.groupBy { (it + 1) / 2 } - assertEquals("[[1], [3], [8], [20], [23], [30]]", resultList.values.toString()) - assertEquals("[1, 2, 4, 10, 12, 15]", resultList.keys.toString()) - } - - @Test - fun whenWithIndexGroupBy_thenListIsSplit() { - val resultList = evenList.withIndex() - .groupBy { it.index / 2 } - .map { it.value.map { it.value } } - verifyList(resultList) - } - - @Test - fun whenWithIndexGroupByUneven_thenListIsSplit() { - val resultList = unevenList.withIndex() - .groupBy { it.index / 2 } - .map { it.value.map { it.value } } - verifyPartialList(resultList) - } - - @Test - fun whenFoldIndexed_thenListIsSplit() { - val resultList = evenList.foldIndexed(ArrayList>(evenList.size / 2)) { index, acc, item -> - if (index % 2 == 0) { - acc.add(ArrayList(2)) - } - acc.last().add(item) - acc - } - verifyList(resultList) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/README.md b/core-kotlin-modules/core-kotlin-concurrency/README.md deleted file mode 100644 index 09d9055a2b..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Core Kotlin Concurrency - -This module contains articles about concurrency in Kotlin. - -### Relevant articles: -- [Threads vs Coroutines in Kotlin](https://www.baeldung.com/kotlin-threads-coroutines) -- [Introduction to Kotlin Coroutines](https://www.baeldung.com/kotlin-coroutines) diff --git a/core-kotlin-modules/core-kotlin-concurrency/pom.xml b/core-kotlin-modules/core-kotlin-concurrency/pom.xml deleted file mode 100644 index 7c3b0fb5b6..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - 4.0.0 - core-kotlin-concurrency - core-kotlin-concurrency - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 1.3.30 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/BufferedChannel.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/BufferedChannel.kt deleted file mode 100644 index 5fefc2f95e..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/BufferedChannel.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.cancelChildren -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking - -fun main() = runBlocking { - val basket = Channel(1) - - launch { // coroutine1 - val fruits = listOf("Apple", "Orange", "Banana") - for (fruit in fruits) { - println("coroutine1: Sending $fruit") - basket.send(fruit) - } - } - - launch { // coroutine2 - repeat(3) { - delay(100) - println("coroutine2: Received ${basket.receive()}") - } - } - - delay(2000) - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ConflatedChannel.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ConflatedChannel.kt deleted file mode 100644 index 6225eeb107..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ConflatedChannel.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.cancelChildren -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.channels.Channel.Factory.CONFLATED -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking - -fun main() = runBlocking { - val basket = Channel(CONFLATED) - - launch { // coroutine1 - val fruits = listOf("Apple", "Orange", "Banana") - for (fruit in fruits) { - println("coroutine1: Sending $fruit") - basket.send(fruit) - } - } - - launch { // coroutine2 - println("coroutine2: Received ${basket.receive()}") - } - - delay(2000) - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/PizzaPipeline.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/PizzaPipeline.kt deleted file mode 100644 index abc8be4d18..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/PizzaPipeline.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.channels - -import com.baeldung.channels.OrderStatus.* -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.ReceiveChannel -import kotlinx.coroutines.channels.produce - -enum class OrderStatus { ORDERED, BAKED, TOPPED, SERVED } - -data class PizzaOrder(val orderNumber: Int, val orderStatus: OrderStatus = ORDERED) - -@ExperimentalCoroutinesApi -fun CoroutineScope.baking(orders: ReceiveChannel) = produce { - for (order in orders) { - delay(200) - println("Baking ${order.orderNumber}") - send(order.copy(orderStatus = BAKED)) - } -} - -@ExperimentalCoroutinesApi -fun CoroutineScope.topping(orders: ReceiveChannel) = produce { - for (order in orders) { - delay(50) - println("Topping ${order.orderNumber}") - send(order.copy(orderStatus = TOPPED)) - } -} - -@ExperimentalCoroutinesApi -fun CoroutineScope.produceOrders(count: Int) = produce { - repeat(count) { - delay(50) - send(PizzaOrder(orderNumber = it + 1)) - } -} - -@ObsoleteCoroutinesApi -@ExperimentalCoroutinesApi -fun main() = runBlocking { - val orders = produceOrders(3) - - val readyOrders = topping(baking(orders)) - - for (order in readyOrders) { - println("Serving ${order.orderNumber}") - } - - delay(3000) - println("End!") - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ProducerConsumer.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ProducerConsumer.kt deleted file mode 100644 index 37f3c7d7bb..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/ProducerConsumer.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.channels.ReceiveChannel -import kotlinx.coroutines.channels.produce -import kotlinx.coroutines.runBlocking - -@ExperimentalCoroutinesApi -fun CoroutineScope.produceFruits(): ReceiveChannel = produce { - val fruits = listOf("Apple", "Orange", "Apple") - for (fruit in fruits) send(fruit) -} - -@ExperimentalCoroutinesApi -fun main() = runBlocking { - val fruitChannel = produceFruits() - for (fruit in fruitChannel) { - println(fruit) - } - println("End!") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/RendezvousChannel.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/RendezvousChannel.kt deleted file mode 100644 index d4b554bced..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/RendezvousChannel.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.Channel - -fun main() = runBlocking { - val basket = Channel() - - launch { // coroutine1 - val fruits = listOf("Apple", "Orange", "Banana") - for (fruit in fruits) { - println("coroutine1: Sending $fruit") - basket.send(fruit) - } - } - - launch { // coroutine2 - repeat(3) { - delay(100) - println("coroutine2: Received ${basket.receive()}") - } - } - - delay(2000) - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SeveralProducersOneConsumer.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SeveralProducersOneConsumer.kt deleted file mode 100644 index 5ed95debe8..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SeveralProducersOneConsumer.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.cancelChildren -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.channels.SendChannel -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking - -suspend fun fetchYoutubeVideos(channel: SendChannel) { - val videos = listOf("cat video", "food video") - for (video in videos) { - delay(100) - channel.send(video) - } -} - -suspend fun fetchTweets(channel: SendChannel) { - val tweets = listOf("tweet: Earth is round", "tweet: Coroutines and channels are cool") - for (tweet in tweets) { - delay(100) - channel.send(tweet) - } -} - -fun main() = runBlocking { - val aggregate = Channel() - launch { fetchYoutubeVideos(aggregate) } - launch { fetchTweets(aggregate) } - - repeat(4) { - println(aggregate.receive()) - } - - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SingleProducerSeveralConsumers.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SingleProducerSeveralConsumers.kt deleted file mode 100644 index f8f7b4b23b..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/SingleProducerSeveralConsumers.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.* -import kotlinx.coroutines.channels.ReceiveChannel -import kotlinx.coroutines.channels.produce - -@ExperimentalCoroutinesApi -fun CoroutineScope.producePizzaOrders(): ReceiveChannel = produce { - var x = 1 - while (true) { - send("Pizza Order No. ${x++}") - delay(100) - } -} - -fun CoroutineScope.pizzaOrderProcessor(id: Int, orders: ReceiveChannel) = launch { - for (order in orders) { - println("Processor #$id is processing $order") - } -} - -@ExperimentalCoroutinesApi -fun main() = runBlocking { - val pizzaOrders = producePizzaOrders() - repeat(3) { - pizzaOrderProcessor(it + 1, pizzaOrders) - } - - delay(1000) - pizzaOrders.cancel() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/TickerChannel.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/TickerChannel.kt deleted file mode 100644 index 85c0dc8d04..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/TickerChannel.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.channels.ticker -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import java.time.Duration -import kotlin.random.Random - -fun stockPrice(stock: String): Double { - log("Fetching stock price of $stock") - return Random.nextDouble(2.0, 3.0) -} - -fun main() = runBlocking { - val tickerChannel = ticker(Duration.ofSeconds(5).toMillis()) - - repeat(3) { - tickerChannel.receive() - log(stockPrice("TESLA")) - } - - delay(Duration.ofSeconds(11).toMillis()) - tickerChannel.cancel() -} diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/UnlimitedChannel.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/UnlimitedChannel.kt deleted file mode 100644 index e4725ca903..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/UnlimitedChannel.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.cancelChildren -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking - -fun main() = runBlocking { - val channel = Channel(UNLIMITED) - - launch { // coroutine1 - repeat(100) { - println("coroutine1: Sending $it") - channel.send(it) - } - } - - launch { // coroutine2 - repeat(100) { - println("coroutine2: Received ${channel.receive()}") - } - } - - delay(2000) - coroutineContext.cancelChildren() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/logger.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/logger.kt deleted file mode 100644 index 036a6a4504..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/channels/logger.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.channels - -import java.text.SimpleDateFormat -import java.util.* - -fun log(value: Any) { - println(SimpleDateFormat("HH:MM:ss").format(Date()) + " - $value") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt deleted file mode 100644 index 80ffb4077a..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleRunnable.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.threadsvscoroutines - -class SimpleRunnable: Runnable { - - override fun run() { - println("${Thread.currentThread()} has run.") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt b/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt deleted file mode 100644 index 6647dac0ef..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/main/kotlin/com/baeldung/threadsvscoroutines/SimpleThread.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.threadsvscoroutines - -class SimpleThread: Thread() { - - override fun run() { - println("${Thread.currentThread()} has run.") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/channels/ChannelsTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/channels/ChannelsTest.kt deleted file mode 100644 index 245282dafc..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/channels/ChannelsTest.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.channels - -import kotlinx.coroutines.async -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ChannelsTest { - @Test - fun should_pass_data_from_one_coroutine_to_another() { - runBlocking { - // given - val channel = Channel() - - // when - launch { // coroutine1 - channel.send("Hello World!") - } - val result = async { // coroutine 2 - channel.receive() - } - - // then - assertThat(result.await()).isEqualTo("Hello World!") - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt deleted file mode 100644 index 6b9437a8ab..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/coroutines/CoroutinesUnitTest.kt +++ /dev/null @@ -1,178 +0,0 @@ -package com.baeldung.coroutines - -import kotlinx.coroutines.* -import org.junit.Test -import java.util.concurrent.atomic.AtomicInteger -import kotlin.system.measureTimeMillis -import kotlin.test.assertEquals -import kotlin.test.assertTrue - - -class CoroutinesTest { - - @Test - fun givenBuildSequence_whenTakeNElements_thenShouldReturnItInALazyWay() { - //given - val fibonacciSeq = sequence { - var a = 0 - var b = 1 - - yield(1) - - while (true) { - yield(a + b) - - val tmp = a + b - a = b - b = tmp - } - } - - //when - val res = fibonacciSeq.take(5).toList() - - //then - assertEquals(res, listOf(1, 1, 2, 3, 5)) - } - - @Test - fun givenLazySeq_whenTakeNElements_thenShouldReturnAllElements() { - //given - val lazySeq = sequence { - print("START ") - for (i in 1..5) { - yield(i) - print("STEP ") - } - print("END") - } - //when - val res = lazySeq.take(10).toList() - - //then - assertEquals(res, listOf(1, 2, 3, 4, 5)) - } - - @Test - fun givenAsyncCoroutine_whenStartIt_thenShouldExecuteItInTheAsyncWay() { - //given - val res = mutableListOf() - - //when - runBlocking { - val promise = launch(Dispatchers.Default) { expensiveComputation(res) } - res.add("Hello,") - promise.join() - } - - //then - assertEquals(res, listOf("Hello,", "word!")) - } - - - suspend fun expensiveComputation(res: MutableList) { - delay(1000L) - res.add("word!") - } - - @Test - fun givenHugeAmountOfCoroutines_whenStartIt_thenShouldExecuteItWithoutOutOfMemory() { - runBlocking { - //given - val counter = AtomicInteger(0) - val numberOfCoroutines = 100_000 - - //when - val jobs = List(numberOfCoroutines) { - launch(Dispatchers.Default) { - delay(1L) - counter.incrementAndGet() - } - } - jobs.forEach { it.join() } - - //then - assertEquals(counter.get(), numberOfCoroutines) - } - } - - @Test - fun givenCancellableJob_whenRequestForCancel_thenShouldQuit() { - runBlocking { - //given - val job = launch(Dispatchers.Default) { - while (isActive) { - //println("is working") - } - } - - delay(1300L) - - //when - job.cancel() - - //then cancel successfully - - } - } - - @Test(expected = CancellationException::class) - fun givenAsyncAction_whenDeclareTimeout_thenShouldFinishWhenTimedOut() { - runBlocking { - withTimeout(1300L) { - repeat(1000) { i -> - println("Some expensive computation $i ...") - delay(500L) - } - } - } - } - - @Test - fun givenHaveTwoExpensiveAction_whenExecuteThemAsync_thenTheyShouldRunConcurrently() { - runBlocking { - val delay = 1000L - val time = measureTimeMillis { - //given - val one = async(Dispatchers.Default) { someExpensiveComputation(delay) } - val two = async(Dispatchers.Default) { someExpensiveComputation(delay) } - - //when - runBlocking { - one.await() - two.await() - } - } - - //then - assertTrue(time < delay * 2) - } - } - - @Test - fun givenTwoExpensiveAction_whenExecuteThemLazy_thenTheyShouldNotConcurrently() { - runBlocking { - val delay = 1000L - val time = measureTimeMillis { - //given - val one = async(Dispatchers.Default, CoroutineStart.LAZY) { someExpensiveComputation(delay) } - val two = async(Dispatchers.Default, CoroutineStart.LAZY) { someExpensiveComputation(delay) } - - //when - runBlocking { - one.await() - two.await() - } - } - - //then - assertTrue(time > delay * 2) - } - } - - suspend fun someExpensiveComputation(delayInMilliseconds: Long) { - delay(delayInMilliseconds) - } - - -} diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt deleted file mode 100644 index ff385d0869..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/CoroutineUnitTest.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.threadsvscoroutines - -import kotlinx.coroutines.* -import org.junit.jupiter.api.Test - -class CoroutineUnitTest { - - @Test - fun whenCreateCoroutineWithLaunchWithoutContext_thenRun() = runBlocking { - - val job = launch { - println("${Thread.currentThread()} has run.") - } - - } - - @Test - fun whenCreateCoroutineWithLaunchWithDefaultContext_thenRun() = runBlocking { - - val job = launch(Dispatchers.Default) { - println("${Thread.currentThread()} has run.") - } - } - - @Test - fun whenCreateCoroutineWithLaunchWithUnconfinedContext_thenRun() = runBlocking { - - val job = launch(Dispatchers.Unconfined) { - println("${Thread.currentThread()} has run.") - } - } - - @Test - fun whenCreateCoroutineWithLaunchWithDedicatedThread_thenRun() = runBlocking { - - val job = launch(newSingleThreadContext("dedicatedThread")) { - println("${Thread.currentThread()} has run.") - } - - } - - @Test - fun whenCreateAsyncCoroutine_thenRun() = runBlocking { - - val deferred = async(Dispatchers.IO) { - return@async "${Thread.currentThread()} has run." - } - - val result = deferred.await() - println(result) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt b/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt deleted file mode 100644 index 9503751fa3..0000000000 --- a/core-kotlin-modules/core-kotlin-concurrency/src/test/kotlin/com/baeldung/threadsvscoroutines/ThreadUnitTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.threadsvscoroutines - -import org.junit.jupiter.api.Test -import kotlin.concurrent.thread - -class ThreadUnitTest { - - @Test - fun whenCreateThread_thenRun() { - - val thread = SimpleThread() - thread.start() - } - - @Test - fun whenCreateThreadWithRunnable_thenRun() { - - val threadWithRunnable = Thread(SimpleRunnable()) - threadWithRunnable.start() - } - - @Test - fun whenCreateThreadWithSAMConversions_thenRun() { - - val thread = Thread { - println("${Thread.currentThread()} has run.") - } - thread.start() - } - - @Test - fun whenCreateThreadWithMethodExtension_thenRun() { - - thread(start = true) { - println("${Thread.currentThread()} has run.") - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-datastructures/README.md b/core-kotlin-modules/core-kotlin-datastructures/README.md deleted file mode 100644 index 3b22730a76..0000000000 --- a/core-kotlin-modules/core-kotlin-datastructures/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Core Kotlin - -This module contains articles about data structures in Kotlin - -### Relevant articles: -[Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree) diff --git a/core-kotlin-modules/core-kotlin-datastructures/pom.xml b/core-kotlin-modules/core-kotlin-datastructures/pom.xml deleted file mode 100644 index eae11c17cf..0000000000 --- a/core-kotlin-modules/core-kotlin-datastructures/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - core-kotlin-datastructures - core-kotlin-datastructures - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.1.1 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Main.kt b/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Main.kt deleted file mode 100644 index eee10fbd8b..0000000000 --- a/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Main.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.binarytree - -/** - * Example of how to use the {@link Node} class. - * - */ -fun main(args: Array) { - val tree = Node(4) - val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11) - for (key in keys) { - tree.insert(key) - } - val node = tree.find(4)!! - println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]") - println("Delete node with key = 3") - node.delete(3) - print("Tree content after the node elimination: ") - println(tree.visit().joinToString { it.toString() }) -} diff --git a/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Node.kt b/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Node.kt deleted file mode 100644 index 77bb98f828..0000000000 --- a/core-kotlin-modules/core-kotlin-datastructures/src/main/kotlin/com/baeldung/binarytree/Node.kt +++ /dev/null @@ -1,167 +0,0 @@ -package com.baeldung.binarytree - -/** - * An ADT for a binary search tree. - * Note that this data type is neither immutable nor thread safe. - */ -class Node( - var key: Int, - var left: Node? = null, - var right: Node? = null) { - - /** - * Return a node with given value. If no such node exists, return null. - * @param value - */ - fun find(value: Int): Node? = when { - this.key > value -> left?.find(value) - this.key < value -> right?.find(value) - else -> this - - } - - /** - * Insert a given value into the tree. - * After insertion, the tree should contain a node with the given value. - * If the tree already contains the given value, nothing is performed. - * @param value - */ - fun insert(value: Int) { - if (value > this.key) { - if (this.right == null) { - this.right = Node(value) - } else { - this.right?.insert(value) - } - } else if (value < this.key) { - if (this.left == null) { - this.left = Node(value) - } else { - this.left?.insert(value) - } - } - } - - /** - * Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged. - * @param value - */ - fun delete(value: Int) { - when { - value > key -> scan(value, this.right, this) - value < key -> scan(value, this.left, this) - else -> removeNode(this, null) - } - } - - /** - * Scan the tree in the search of the given value. - * @param value - * @param node sub-tree that potentially might contain the sought value - * @param parent node's parent - */ - private fun scan(value: Int, node: Node?, parent: Node?) { - if (node == null) { - System.out.println("value " + value - + " seems not present in the tree.") - return - } - when { - value > node.key -> scan(value, node.right, node) - value < node.key -> scan(value, node.left, node) - value == node.key -> removeNode(node, parent) - } - - } - - /** - * Remove the node. - * - * Removal process depends on how many children the node has. - * - * @param node node that is to be removed - * @param parent parent of the node to be removed - */ - private fun removeNode(node: Node, parent: Node?) { - node.left?.let { leftChild -> - run { - node.right?.let { - removeTwoChildNode(node) - } ?: removeSingleChildNode(node, leftChild) - } - } ?: run { - node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent) - } - - - } - - /** - * Remove the node without children. - * @param node - * @param parent - */ - private fun removeNoChildNode(node: Node, parent: Node?) { - parent?.let { p -> - if (node == p.left) { - p.left = null - } else if (node == p.right) { - p.right = null - } - } ?: throw IllegalStateException( - "Can not remove the root node without child nodes") - - } - - /** - * Remove a node that has two children. - * - * The process of elimination is to find the biggest key in the left sub-tree and replace the key of the - * node that is to be deleted with that key. - */ - private fun removeTwoChildNode(node: Node) { - val leftChild = node.left!! - leftChild.right?.let { - val maxParent = findParentOfMaxChild(leftChild) - maxParent.right?.let { - node.key = it.key - maxParent.right = null - } ?: throw IllegalStateException("Node with max child must have the right child!") - - } ?: run { - node.key = leftChild.key - node.left = leftChild.left - } - - } - - /** - * Return a node whose right child contains the biggest value in the given sub-tree. - * Assume that the node n has a non-null right child. - * - * @param n - */ - private fun findParentOfMaxChild(n: Node): Node { - return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n } - ?: throw IllegalArgumentException("Right child must be non-null") - - } - - /** - * Remove a parent that has only one child. - * Removal is effectively is just coping the data from the child parent to the parent parent. - * @param parent Node to be deleted. Assume that it has just one child - * @param child Assume it is a child of the parent - */ - private fun removeSingleChildNode(parent: Node, child: Node) { - parent.key = child.key - parent.left = child.left - parent.right = child.right - } - - fun visit(): Array { - val a = left?.visit() ?: emptyArray() - val b = right?.visit() ?: emptyArray() - return a + arrayOf(key) + b - } -} diff --git a/core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt b/core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt deleted file mode 100644 index 5a7f7fc50f..0000000000 --- a/core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/binarytree/NodeTest.kt +++ /dev/null @@ -1,320 +0,0 @@ -package com.binarytree - -import org.junit.After -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Before -import org.junit.Test - -class NodeTest { - - @Before - fun setUp() { - } - - @After - fun tearDown() { - } - - /** - * Test suit for finding the node by value - * Partition the tests as follows: - * 1. tree depth: 0, 1, > 1 - * 2. pivot depth location: not present, 0, 1, 2, > 2 - */ - - /** - * Find the node by value - * 1. tree depth: 0 - * 2. pivot depth location: not present - */ - @Test - fun givenDepthZero_whenPivotNotPresent_thenNull() { - val n = Node(1) - assertNull(n.find(2)) - } - - /** - * Find the node by value - * 1. tree depth: 0 - * 2. pivot depth location: 0 - */ - @Test - fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() { - val n = Node(1) - assertEquals(n, n.find(1)) - } - - /** - * Find the node by value - * 1. tree depth: 1 - * 2. pivot depth location: not present - */ - @Test - fun givenDepthOne_whenPivotNotPresent_thenNull() { - val n = Node(1, Node(0)) - assertNull(n.find(2)) - } - - /** - * Find the node by value - * 1. tree depth: 1 - * 2. pivot depth location: not present - */ - @Test - fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() { - val n = Node(1, Node(0)) - assertEquals(n.left, n.find(0) - ) - } - - @Test - fun givenDepthTwo_whenPivotAtDepth2_then_Success() { - val left = Node(1, Node(0), Node(2)) - val right = Node(5, Node(4), Node(6)) - val n = Node(3, left, right) - assertEquals(left.left, n.find(0)) - } - - - /** - * Test suit for inserting a value - * Partition the test as follows: - * 1. tree depth: 0, 1, 2, > 2 - * 2. depth to insert: 0, 1, > 1 - * 3. is duplicate: no, yes - * 4. sub-tree: left, right - */ - /** - * Test for inserting a value - * 1. tree depth: 0 - * 2. depth to insert: 1 - * 3. is duplicate: no - * 4. sub-tree: right - */ - @Test - fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() { - val n = Node(1) - n.insert(2) - assertEquals(1, n.key) - with(n.right!!) { - assertEquals(2, key) - assertNull(left) - assertNull(right) - } - assertNull(n.left) - } - - /** - * Test for inserting a value - * 1. tree depth: 0 - * 2. depth to insert: 1 - * 3. is duplicate: no - * 4. sub-tree: right - */ - @Test - fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() { - val n = Node(1) - n.insert(0) - assertEquals(1, n.key) - with(n.left!!) { - assertEquals(0, key) - assertNull(left) - assertNull(right) - } - assertNull(n.right) - } - - /** - * Test for inserting a value - * 1. tree depth: 0 - * 2. depth to insert: 1 - * 3. is duplicate: yes - */ - @Test - fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() { - val n = Node(1) - n.insert(1) - assertEquals(1, n.key) - assertNull(n.right) - assertNull(n.left) - } - - - /** - * Test suit for inserting a value - * Partition the test as follows: - * 1. tree depth: 0, 1, 2, > 2 - * 2. depth to insert: 0, 1, > 1 - * 3. is duplicate: no, yes - * 4. sub-tree: left, right - */ - /** - * Test for inserting a value - * 1. tree depth: 1 - * 2. depth to insert: 1 - * 3. is duplicate: no - * 4. sub-tree: right - */ - @Test - fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() { - val n = Node(10, Node(3)) - n.insert(15) - assertEquals(10, n.key) - with(n.right!!) { - assertEquals(15, key) - assertNull(left) - assertNull(right) - } - with(n.left!!) { - assertEquals(3, key) - assertNull(left) - assertNull(right) - } - } - - /** - * Test for inserting a value - * 1. tree depth: 1 - * 2. depth to insert: 1 - * 3. is duplicate: no - * 4. sub-tree: left - */ - @Test - fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() { - val n = Node(10, null, Node(15)) - n.insert(3) - assertEquals(10, n.key) - with(n.right!!) { - assertEquals(15, key) - assertNull(left) - assertNull(right) - } - with(n.left!!) { - assertEquals(3, key) - assertNull(left) - assertNull(right) - } - } - - /** - * Test for inserting a value - * 1. tree depth: 1 - * 2. depth to insert: 1 - * 3. is duplicate: yes - */ - @Test - fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() { - val n = Node(10, null, Node(15)) - n.insert(15) - assertEquals(10, n.key) - with(n.right!!) { - assertEquals(15, key) - assertNull(left) - assertNull(right) - } - assertNull(n.left) - } - - /** - * Test suit for removal - * Partition the input as follows: - * 1. tree depth: 0, 1, 2, > 2 - * 2. value to delete: absent, present - * 3. # child nodes: 0, 1, 2 - */ - /** - * Test for removal value - * 1. tree depth: 0 - * 2. value to delete: absent - */ - @Test - fun givenTreeDepthZero_whenValueAbsent_thenNoChange() { - val n = Node(1) - n.delete(0) - assertEquals(1, n.key) - assertNull(n.left) - assertNull(n.right) - } - - /** - * Test for removal - * 1. tree depth: 1 - * 2. value to delete: absent - */ - @Test - fun givenTreeDepthOne_whenValueAbsent_thenNoChange() { - val n = Node(1, Node(0), Node(2)) - n.delete(3) - assertEquals(1, n.key) - assertEquals(2, n.right!!.key) - with(n.left!!) { - assertEquals(0, key) - assertNull(left) - assertNull(right) - } - with(n.right!!) { - assertNull(left) - assertNull(right) - } - } - - /** - * Test suit for removal - * 1. tree depth: 1 - * 2. value to delete: present - * 3. # child nodes: 0 - */ - @Test - fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() { - val n = Node(1, Node(0)) - n.delete(0) - assertEquals(1, n.key) - assertNull(n.left) - assertNull(n.right) - } - - /** - * Test suit for removal - * 1. tree depth: 2 - * 2. value to delete: present - * 3. # child nodes: 1 - */ - @Test - fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() { - val n = Node(2, Node(0, null, Node(1)), Node(3)) - n.delete(0) - assertEquals(2, n.key) - with(n.right!!) { - assertEquals(3, key) - assertNull(left) - assertNull(right) - } - with(n.left!!) { - assertEquals(1, key) - assertNull(left) - assertNull(right) - } - } - - @Test - fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() { - val l = Node(2, Node(1), Node(5, Node(4), Node(6))) - val r = Node(10, Node(9), Node(11)) - val n = Node(8, l, r) - n.delete(8) - assertEquals(6, n.key) - with(n.left!!) { - assertEquals(2, key) - assertEquals(1, left!!.key) - assertEquals(5, right!!.key) - assertEquals(4, right!!.left!!.key) - } - with(n.right!!) { - assertEquals(10, key) - assertEquals(9, left!!.key) - assertEquals(11, right!!.key) - } - } - -} diff --git a/core-kotlin-modules/core-kotlin-date-time/README.md b/core-kotlin-modules/core-kotlin-date-time/README.md deleted file mode 100644 index a3e358d4e3..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Core Kotlin Date and Time - -This module contains articles about Kotlin core date/time features. - -### Relevant articles: -[Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates) diff --git a/core-kotlin-modules/core-kotlin-date-time/pom.xml b/core-kotlin-modules/core-kotlin-date-time/pom.xml deleted file mode 100644 index f3cacefc19..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - 4.0.0 - core-kotlin-date-time - core-kotlin-date-time - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.assertj - assertj-core - ${org.assertj.core.version} - test - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.1.1 - 3.9.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt deleted file mode 100644 index 922c3a1988..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseDuration.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.Duration -import java.time.LocalTime - -class UseDuration { - - fun modifyDates(localTime: LocalTime, duration: Duration): LocalTime { - return localTime.plus(duration) - } - - fun getDifferenceBetweenDates(localTime1: LocalTime, localTime2: LocalTime): Duration { - return Duration.between(localTime1, localTime2) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt deleted file mode 100644 index 81d50a70b2..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDate.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.DayOfWeek -import java.time.LocalDate -import java.time.LocalDateTime -import java.time.temporal.ChronoUnit -import java.time.temporal.TemporalAdjusters - -class UseLocalDate { - - fun getLocalDateUsingFactoryOfMethod(year: Int, month: Int, dayOfMonth: Int): LocalDate { - return LocalDate.of(year, month, dayOfMonth) - } - - fun getLocalDateUsingParseMethod(representation: String): LocalDate { - return LocalDate.parse(representation) - } - - fun getLocalDateFromClock(): LocalDate { - return LocalDate.now() - } - - fun getNextDay(localDate: LocalDate): LocalDate { - return localDate.plusDays(1) - } - - fun getPreviousDay(localDate: LocalDate): LocalDate { - return localDate.minus(1, ChronoUnit.DAYS) - } - - fun getDayOfWeek(localDate: LocalDate): DayOfWeek { - return localDate.dayOfWeek - } - - fun getFirstDayOfMonth(): LocalDate { - return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()) - } - - fun getStartOfDay(localDate: LocalDate): LocalDateTime { - return localDate.atStartOfDay() - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt deleted file mode 100644 index 5d0eb6a911..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalDateTime.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.LocalDateTime - -class UseLocalDateTime { - - fun getLocalDateTimeUsingParseMethod(representation: String): LocalDateTime { - return LocalDateTime.parse(representation) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt deleted file mode 100644 index 24402467e8..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseLocalTime.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.LocalTime -import java.time.temporal.ChronoUnit - -class UseLocalTime { - - fun getLocalTimeUsingFactoryOfMethod(hour: Int, min: Int, seconds: Int): LocalTime { - return LocalTime.of(hour, min, seconds) - } - - fun getLocalTimeUsingParseMethod(timeRepresentation: String): LocalTime { - return LocalTime.parse(timeRepresentation) - } - - fun getLocalTimeFromClock(): LocalTime { - return LocalTime.now() - } - - fun addAnHour(localTime: LocalTime): LocalTime { - return localTime.plus(1, ChronoUnit.HOURS) - } - - fun getHourFromLocalTime(localTime: LocalTime): Int { - return localTime.hour - } - - fun getLocalTimeWithMinuteSetToValue(localTime: LocalTime, minute: Int): LocalTime { - return localTime.withMinute(minute) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt deleted file mode 100644 index d15e02eb37..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UsePeriod.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.LocalDate -import java.time.Period - -class UsePeriod { - - fun modifyDates(localDate: LocalDate, period: Period): LocalDate { - return localDate.plus(period) - } - - fun getDifferenceBetweenDates(localDate1: LocalDate, localDate2: LocalDate): Period { - return Period.between(localDate1, localDate2) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt b/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt deleted file mode 100644 index e2f3a207c4..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/main/kotlin/com/baeldung/dates/datetime/UseZonedDateTime.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.dates.datetime - -import java.time.LocalDateTime -import java.time.ZoneId -import java.time.ZonedDateTime - -class UseZonedDateTime { - - fun getZonedDateTime(localDateTime: LocalDateTime, zoneId: ZoneId): ZonedDateTime { - return ZonedDateTime.of(localDateTime, zoneId) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt deleted file mode 100644 index af5e08ea2d..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/CreateDateUnitTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class CreateDateUnitTest { - - @Test - fun givenString_whenDefaultFormat_thenCreated() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenString_whenCustomFormat_thenCreated() { - - var formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy") - var date = LocalDate.parse("31-12-2018", formatter) - - assertThat(date).isEqualTo("2018-12-31") - } - - @Test - fun givenYMD_whenUsingOf_thenCreated() { - var date = LocalDate.of(2018, 12, 31) - - assertThat(date).isEqualTo("2018-12-31") - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt deleted file mode 100644 index d297f4b6c3..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/ExtractDateUnitTest.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.DayOfWeek -import java.time.LocalDate -import java.time.Month - -class ExtractDateUnitTest { - - @Test - fun givenDate_thenExtractedYMD() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.year).isEqualTo(2018) - assertThat(date.month).isEqualTo(Month.DECEMBER) - assertThat(date.dayOfMonth).isEqualTo(31) - } - - @Test - fun givenDate_thenExtractedEraDowDoy() { - var date = LocalDate.parse("2018-12-31") - - assertThat(date.era.toString()).isEqualTo("CE") - assertThat(date.dayOfWeek).isEqualTo(DayOfWeek.MONDAY) - assertThat(date.dayOfYear).isEqualTo(365) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt deleted file mode 100644 index f7ca414aee..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/FormatDateUnitTest.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.format.DateTimeFormatter - -class FormatDateUnitTest { - - @Test - fun givenDate_whenDefaultFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - assertThat(date.toString()).isEqualTo("2018-12-31") - } - - @Test - fun givenDate_whenCustomFormat_thenFormattedString() { - - var date = LocalDate.parse("2018-12-31") - - var formatter = DateTimeFormatter.ofPattern("dd-MMMM-yyyy") - var formattedDate = date.format(formatter) - - assertThat(formattedDate).isEqualTo("31-December-2018") - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt deleted file mode 100644 index e8ca2971e8..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/PeriodDateUnitTest.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.kotlin.dates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test -import java.time.LocalDate -import java.time.Period - -class PeriodDateUnitTest { - - @Test - fun givenYMD_thenCreatePeriod() { - var period = Period.of(1, 2, 3) - - assertThat(period.toString()).isEqualTo("P1Y2M3D") - } - - @Test - fun givenPeriod_whenAdd_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.plus(period) - - assertThat(modifiedDate).isEqualTo("2019-08-28") - } - - @Test - fun givenPeriod_whenSubtracted_thenModifiedDate() { - var period = Period.of(1, 2, 3) - - var date = LocalDate.of(2018, 6, 25) - var modifiedDate = date.minus(period) - - assertThat(modifiedDate).isEqualTo("2017-04-22") - } - - @Test - fun givenTwoDate_whenUsingBetween_thenDiffOfDates() { - - var date1 = LocalDate.parse("2018-06-25") - var date2 = LocalDate.parse("2018-12-25") - - var period = Period.between(date1, date2) - - assertThat(period.toString()).isEqualTo("P6M") - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt deleted file mode 100644 index f3615a527c..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateTimeUnitTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kotlin.datetime - -import com.baeldung.dates.datetime.UseLocalDateTime -import org.junit.Assert.assertEquals -import org.junit.Test -import java.time.LocalDate -import java.time.LocalTime -import java.time.Month - -class UseLocalDateTimeUnitTest { - - var useLocalDateTime = UseLocalDateTime() - - @Test - fun givenString_whenUsingParse_thenLocalDateTime() { - assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") - .toLocalDate()) - assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") - .toLocalTime()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt deleted file mode 100644 index e6353c9dab..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalDateUnitTest.kt +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.kotlin.datetime - -import com.baeldung.dates.datetime.UseLocalDate -import org.junit.Assert -import org.junit.Test -import java.time.DayOfWeek -import java.time.LocalDate -import java.time.LocalDateTime - -class UseLocalDateUnitTest { - - var useLocalDate = UseLocalDate() - - @Test - fun givenValues_whenUsingFactoryOf_thenLocalDate() { - Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10) - .toString()) - } - - @Test - fun givenString_whenUsingParse_thenLocalDate() { - Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10") - .toString()) - } - - @Test - fun whenUsingClock_thenLocalDate() { - Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock()) - } - - @Test - fun givenDate_whenUsingPlus_thenNextDay() { - Assert.assertEquals(LocalDate.now() - .plusDays(1), useLocalDate.getNextDay(LocalDate.now())) - } - - @Test - fun givenDate_whenUsingMinus_thenPreviousDay() { - Assert.assertEquals(LocalDate.now() - .minusDays(1), useLocalDate.getPreviousDay(LocalDate.now())) - } - - @Test - fun givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() { - Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22"))) - } - - @Test - fun givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() { - Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth() - .dayOfMonth.toLong()) - } - - @Test - fun givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() { - Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt deleted file mode 100644 index 1afe03ca48..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseLocalTimeUnitTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.kotlin.datetime - -import com.baeldung.dates.datetime.UseLocalTime -import org.junit.Assert -import org.junit.Test -import java.time.LocalTime - -class UseLocalTimeUnitTest { - - internal var useLocalTime = UseLocalTime() - - @Test - fun givenValues_whenUsingFactoryOf_thenLocalTime() { - Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString()) - } - - @Test - fun givenString_whenUsingParse_thenLocalTime() { - Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString()) - } - - @Test - fun givenTime_whenAddHour_thenLocalTime() { - Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString()) - } - - @Test - fun getHourFromLocalTime() { - Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)).toLong()) - } - - @Test - fun getLocalTimeWithMinuteSetToValue() { - Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20)) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt deleted file mode 100644 index 36e1e5533a..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UsePeriodUnitTest.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.kotlin.datetime - -import com.baeldung.dates.datetime.UsePeriod -import org.junit.Assert -import org.junit.Test -import java.time.LocalDate -import java.time.Period - -class UsePeriodUnitTest { - - var usingPeriod = UsePeriod() - - @Test - fun givenPeriodAndLocalDate_thenCalculateModifiedDate() { - val period = Period.ofDays(1) - val localDate = LocalDate.parse("2007-05-10") - Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period)) - } - - @Test - fun givenDates_thenGetPeriod() { - val localDate1 = LocalDate.parse("2007-05-10") - val localDate2 = LocalDate.parse("2007-05-15") - - Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2)) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt b/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt deleted file mode 100644 index aa2cdaa4f3..0000000000 --- a/core-kotlin-modules/core-kotlin-date-time/src/test/kotlin/com/baeldung/dates/datetime/UseZonedDateTimeUnitTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.kotlin.datetime - -import com.baeldung.dates.datetime.UseZonedDateTime -import org.junit.Assert -import org.junit.Test -import java.time.LocalDateTime -import java.time.ZoneId - -class UseZonedDateTimeUnitTest { - - internal var zonedDateTime = UseZonedDateTime() - - @Test - fun givenZoneId_thenZonedDateTime() { - val zoneId = ZoneId.of("Europe/Paris") - val zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId) - Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-design-patterns/README.md b/core-kotlin-modules/core-kotlin-design-patterns/README.md deleted file mode 100644 index 4bdc164a47..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Core Kotlin Design Patterns - -This module contains articles about design patterns in Kotlin - -### Relevant articles: -- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern) diff --git a/core-kotlin-modules/core-kotlin-design-patterns/pom.xml b/core-kotlin-modules/core-kotlin-design-patterns/pom.xml deleted file mode 100644 index c112602bc2..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - core-kotlin-design-patterns - core-kotlin-design-patterns - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.1.1 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrder.kt deleted file mode 100644 index 3a8a4b9857..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrder.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.builder - -class FoodOrder private constructor( - val bread: String?, - val condiments: String?, - val meat: String?, - val fish: String? -) { - data class Builder( - var bread: String? = null, - var condiments: String? = null, - var meat: String? = null, - var fish: String? = null) { - - fun bread(bread: String) = apply { this.bread = bread } - fun condiments(condiments: String) = apply { this.condiments = condiments } - fun meat(meat: String) = apply { this.meat = meat } - fun fish(fish: String) = apply { this.fish = fish } - fun build() = FoodOrder(bread, condiments, meat, fish) - } -} - diff --git a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt deleted file mode 100644 index 0a68832b00..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.builder - -class FoodOrderApply { - var bread: String? = null - var condiments: String? = null - var meat: String? = null - var fish: String? = null -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt deleted file mode 100644 index 0e4219b40e..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.builder - -data class FoodOrderNamed( - val bread: String? = null, - val condiments: String? = null, - val meat: String? = null, - val fish: String? = null) diff --git a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/Main.kt deleted file mode 100644 index cc348e3fbf..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/src/main/kotlin/com/baeldung/builder/Main.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.builder - -fun main(args: Array) { - FoodOrder.Builder() - .bread("bread") - .condiments("condiments") - .meat("meat") - .fish("bread").let { println(it) } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-design-patterns/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin-modules/core-kotlin-design-patterns/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt deleted file mode 100644 index a6687b6e0a..0000000000 --- a/core-kotlin-modules/core-kotlin-design-patterns/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt +++ /dev/null @@ -1,140 +0,0 @@ -package com.baeldung.builder - -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Test - -internal class BuilderPatternUnitTest { - - @Test - fun whenBuildingFoodOrderSettingValues_thenFieldsNotNull() { - - val foodOrder = FoodOrder.Builder() - .bread("white bread") - .meat("bacon") - .fish("salmon") - .condiments("olive oil") - .build() - - Assertions.assertNotNull(foodOrder.bread) - Assertions.assertNotNull(foodOrder.meat) - Assertions.assertNotNull(foodOrder.condiments) - Assertions.assertNotNull(foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderSettingValues_thenFieldsContainsValues() { - - val foodOrder = FoodOrder.Builder() - .bread("white bread") - .meat("bacon") - .fish("salmon") - .condiments("olive oil") - .build() - - Assertions.assertEquals("white bread", foodOrder.bread) - Assertions.assertEquals("bacon", foodOrder.meat) - Assertions.assertEquals("olive oil", foodOrder.condiments) - Assertions.assertEquals("salmon", foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderWithoutSettingValues_thenFieldsNull() { - - val foodOrder = FoodOrder.Builder() - .build() - - Assertions.assertNull(foodOrder.bread) - Assertions.assertNull(foodOrder.meat) - Assertions.assertNull(foodOrder.condiments) - Assertions.assertNull(foodOrder.fish) - } - - - @Test - fun whenBuildingFoodOrderNamedSettingValues_thenFieldsNotNull() { - - val foodOrder = FoodOrderNamed( - meat = "bacon", - fish = "salmon", - condiments = "olive oil", - bread = "white bread" - ) - - Assertions.assertNotNull(foodOrder.bread) - Assertions.assertNotNull(foodOrder.meat) - Assertions.assertNotNull(foodOrder.condiments) - Assertions.assertNotNull(foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderNamedSettingValues_thenFieldsContainsValues() { - - val foodOrder = FoodOrderNamed( - meat = "bacon", - fish = "salmon", - condiments = "olive oil", - bread = "white bread" - ) - - Assertions.assertEquals("white bread", foodOrder.bread) - Assertions.assertEquals("bacon", foodOrder.meat) - Assertions.assertEquals("olive oil", foodOrder.condiments) - Assertions.assertEquals("salmon", foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderNamedWithoutSettingValues_thenFieldsNull() { - - val foodOrder = FoodOrderNamed() - - Assertions.assertNull(foodOrder.bread) - Assertions.assertNull(foodOrder.meat) - Assertions.assertNull(foodOrder.condiments) - Assertions.assertNull(foodOrder.fish) - } - - - @Test - fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() { - - val foodOrder = FoodOrderApply().apply { - meat = "bacon" - fish = "salmon" - condiments = "olive oil" - bread = "white bread" - } - - Assertions.assertNotNull(foodOrder.bread) - Assertions.assertNotNull(foodOrder.meat) - Assertions.assertNotNull(foodOrder.condiments) - Assertions.assertNotNull(foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderApplySettingValues_thenFieldsContainsValues() { - - val foodOrder = FoodOrderApply().apply { - meat = "bacon" - fish = "salmon" - condiments = "olive oil" - bread = "white bread" - } - - Assertions.assertEquals("white bread", foodOrder.bread) - Assertions.assertEquals("bacon", foodOrder.meat) - Assertions.assertEquals("olive oil", foodOrder.condiments) - Assertions.assertEquals("salmon", foodOrder.fish) - } - - @Test - fun whenBuildingFoodOrderApplyWithoutSettingValues_thenFieldsNull() { - - val foodOrder = FoodOrderApply() - - Assertions.assertNull(foodOrder.bread) - Assertions.assertNull(foodOrder.meat) - Assertions.assertNull(foodOrder.condiments) - Assertions.assertNull(foodOrder.fish) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/README.md b/core-kotlin-modules/core-kotlin-io/README.md deleted file mode 100644 index 89f9534d4b..0000000000 --- a/core-kotlin-modules/core-kotlin-io/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Core Kotlin I/O - -This module contains articles about core Kotlin I/O. - -### Relevant articles: -- [InputStream to String in Kotlin](https://www.baeldung.com/kotlin-inputstream-to-string) -- [Console I/O in Kotlin](https://www.baeldung.com/kotlin-console-io) -- [Reading from a File in Kotlin](https://www.baeldung.com/kotlin-read-file) -- [Writing to a File in Kotlin](https://www.baeldung.com/kotlin-write-file) diff --git a/core-kotlin-modules/core-kotlin-io/pom.xml b/core-kotlin-modules/core-kotlin-io/pom.xml deleted file mode 100644 index 9443cd0d5b..0000000000 --- a/core-kotlin-modules/core-kotlin-io/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - 4.0.0 - core-kotlin-io - core-kotlin-io - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.junit.jupiter - junit-jupiter - ${junit-jupiter.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - 5.4.2 - 2.27.0 - 3.10.0 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileReader.kt b/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileReader.kt deleted file mode 100644 index 886a3fc51e..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileReader.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.filesystem - -import java.io.File - -class FileReader { - - fun readFileLineByLineUsingForEachLine(fileName: String) = File(fileName).forEachLine { println(it) } - - fun readFileAsLinesUsingUseLines(fileName: String): List = File(fileName) - .useLines { it.toList() } - - fun readFileAsLinesUsingBufferedReader(fileName: String): List = File(fileName).bufferedReader().readLines() - - fun readFileAsLinesUsingReadLines(fileName: String): List = File(fileName).readLines() - - fun readFileAsTextUsingInputStream(fileName: String) = - File(fileName).inputStream().readBytes().toString(Charsets.UTF_8) - - fun readFileDirectlyAsText(fileName: String): String = File(fileName).readText(Charsets.UTF_8) - - fun readFileUsingGetResource(fileName: String) = this::class.java.getResource(fileName).readText(Charsets.UTF_8) - - fun readFileAsLinesUsingGetResourceAsStream(fileName: String) = this::class.java.getResourceAsStream(fileName).bufferedReader().readLines() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt b/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt deleted file mode 100644 index 6dc9b95f1f..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/filesystem/FileWriter.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.filesystem - -import java.io.File - -class FileWriter { - - fun writeFileUsingPrintWriter(fileName: String, fileContent: String) = - File(fileName).printWriter().use { out -> out.print(fileContent) } - - fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) = - File(fileName).bufferedWriter().use { out -> out.write(fileContent) } - - fun writeFileDirectly(fileName: String, fileContent: String) = - File(fileName).writeText(fileContent) - - fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) = - File(fileName).writeBytes(fileContent.toByteArray()) - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/inputstream/InputStreamExtension.kt b/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/inputstream/InputStreamExtension.kt deleted file mode 100644 index e94a2e84ee..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/main/kotlin/com/baeldung/inputstream/InputStreamExtension.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.inputstream - -import java.io.InputStream - -fun InputStream.readUpToChar(stopChar: Char): String { - val stringBuilder = StringBuilder() - var currentChar = this.read().toChar() - while (currentChar != stopChar) { - stringBuilder.append(currentChar) - currentChar = this.read().toChar() - if (this.available() <= 0) { - stringBuilder.append(currentChar) - break - } - } - return stringBuilder.toString() -} - diff --git a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/console/ConsoleIOUnitTest.kt b/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/console/ConsoleIOUnitTest.kt deleted file mode 100644 index c73096fce6..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/console/ConsoleIOUnitTest.kt +++ /dev/null @@ -1,79 +0,0 @@ -package com.baeldung.console - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Test -import org.mockito.Mockito.`when` -import org.mockito.Mockito.mock -import java.io.BufferedReader -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.Console -import java.io.InputStreamReader -import java.io.PrintStream -import java.util.* - - -class ConsoleIOUnitTest { - - @Test - fun givenText_whenPrint_thenPrintText() { - val expectedTest = "Hello from Kotlin" - val out = ByteArrayOutputStream() - System.setOut(PrintStream(out)) - - print(expectedTest) - out.flush() - val printedText = String(out.toByteArray()) - - assertThat(printedText).isEqualTo(expectedTest) - } - - @Test - fun givenInput_whenRead_thenReadText() { - val expectedTest = "Hello from Kotlin" - val input = ByteArrayInputStream(expectedTest.toByteArray()) - System.setIn(input) - - val readText = readLine() - - assertThat(readText).isEqualTo(expectedTest) - } - - @Test - fun givenInput_whenReadWithScanner_thenReadText() { - val expectedTest = "Hello from Kotlin" - val scanner = Scanner(ByteArrayInputStream(expectedTest.toByteArray())) - - val readText = scanner.nextLine() - - assertThat(readText).isEqualTo(expectedTest) - } - - @Test - fun givenInput_whenReadWithBufferedReader_thenReadText() { - val expectedTest = "Hello from Kotlin" - val reader = BufferedReader(InputStreamReader(ByteArrayInputStream(expectedTest.toByteArray()))) - - val readText = reader.readLine() - - assertThat(readText).isEqualTo(expectedTest) - } - - @Test - fun givenInput_whenReadWithConsole_thenReadText() { - val expectedTest = "Hello from Kotlin" - val console = mock(Console::class.java) - `when`(console.readLine()).thenReturn(expectedTest) - - val readText = console.readLine() - - assertThat(readText).isEqualTo(expectedTest) - } - - @AfterEach - fun resetIO() { - System.setOut(System.out) - System.setIn(System.`in`) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileReaderTest.kt b/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileReaderTest.kt deleted file mode 100644 index ad541c446e..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileReaderTest.kt +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.filesystem - -import org.junit.jupiter.api.Test -import kotlin.test.assertTrue - -internal class FileReaderTest { - - private val fileName = "src/test/resources/Kotlin.in" - - private val fileReader = FileReader() - - @Test - fun whenReadFileLineByLineUsingForEachLine_thenCorrect() { - fileReader.readFileLineByLineUsingForEachLine(fileName) - } - - @Test - fun whenReadFileAsLinesUsingUseLines_thenCorrect() { - val lines = fileReader.readFileAsLinesUsingUseLines(fileName) - - assertTrue { lines.contains("1. Concise") } - } - - @Test - fun whenReadFileAsLinesUsingBufferedReader_thenCorrect() { - val lines = fileReader.readFileAsLinesUsingBufferedReader(fileName) - - assertTrue { lines.contains("2. Safe") } - } - - @Test - fun whenReadFileAsLinesUsingReadLines_thenCorrect() { - val lines = fileReader.readFileAsLinesUsingReadLines(fileName) - - assertTrue { lines.contains("3. Interoperable") } - } - - @Test - fun whenReadFileAsTextUsingInputStream_thenCorrect() { - val text = fileReader.readFileAsTextUsingInputStream(fileName) - - assertTrue { text.contains("4. Tool-friendly") } - } - - @Test - fun whenReadDirectlyAsText_thenCorrect() { - val text = fileReader.readFileDirectlyAsText(fileName) - - assertTrue { text.contains("Hello to Kotlin") } - } - - @Test - fun whenReadFileAsTextUsingGetResource_thenCorrect() { - val text = fileReader.readFileUsingGetResource("/Kotlin.in") - - assertTrue { text.contains("1. Concise") } - } - - @Test - fun whenReadFileUsingGetResourceAsStream_thenCorrect() { - val lines = fileReader.readFileAsLinesUsingGetResourceAsStream("/Kotlin.in") - - assertTrue { lines.contains("3. Interoperable") } - } - - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt b/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt deleted file mode 100644 index 91c66a4fee..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/filesystem/FileWriterTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.filesystem - -import org.junit.jupiter.api.Test -import java.io.File -import kotlin.test.assertEquals - -internal class FileWriterTest { - - private val fileName = "src/test/resources/Kotlin.out" - - private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly" - - private val fileWriter = FileWriter() - - @Test - fun whenWrittenWithPrintWriter_thenCorrect() { - fileWriter.writeFileUsingPrintWriter(fileName, fileContent) - - assertEquals(fileContent, File(fileName).readText()) - } - - @Test - fun whenWrittenWithBufferedWriter_thenCorrect() { - fileWriter.writeFileUsingBufferedWriter(fileName, fileContent) - - assertEquals(fileContent, File(fileName).readText()) - } - - @Test - fun whenWrittenDirectly_thenCorrect() { - fileWriter.writeFileDirectly(fileName, fileContent) - - assertEquals(fileContent, File(fileName).readText()) - } - - @Test - fun whenWrittenDirectlyAsBytes_thenCorrect() { - fileWriter.writeFileDirectlyAsBytes(fileName, fileContent) - - assertEquals(fileContent, File(fileName).readText()) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/inputstream/InputStreamToStringTest.kt b/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/inputstream/InputStreamToStringTest.kt deleted file mode 100644 index a0eb26b762..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/kotlin/com/baeldung/inputstream/InputStreamToStringTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.inputstream - -import kotlinx.io.core.use -import org.junit.Test -import java.io.BufferedReader -import java.io.File -import kotlin.test.assertEquals - -class InputStreamToStringTest { - - private val fileName = "src/test/resources/inputstream2string.txt" - private val endOfLine = System.lineSeparator() - private val fileFullContent = "Computer programming can be a hassle$endOfLine" + - "It's like trying to take a defended castle" - - @Test - fun whenReadFileWithBufferedReader_thenFullFileContentIsReadAsString() { - val file = File(fileName) - val inputStream = file.inputStream() - val content = inputStream.bufferedReader().use(BufferedReader::readText) - assertEquals(fileFullContent, content) - } - - @Test - fun whenReadFileWithBufferedReaderReadText_thenFullFileContentIsReadAsString() { - val file = File(fileName) - val inputStream = file.inputStream() - val reader = BufferedReader(inputStream.reader()) - var content: String - try { - content = reader.readText() - } finally { - reader.close() - } - assertEquals(fileFullContent, content) - } - - @Test - fun whenReadFileWithBufferedReaderManually_thenFullFileContentIsReadAsString() { - val file = File(fileName) - val inputStream = file.inputStream() - val reader = BufferedReader(inputStream.reader()) - val content = StringBuilder() - try { - var line = reader.readLine() - while (line != null) { - content.append(line) - line = reader.readLine() - } - } finally { - reader.close() - } - assertEquals(fileFullContent.replace(endOfLine, ""), content.toString()) - - } - - @Test - fun whenReadFileUpToStopChar_thenPartBeforeStopCharIsReadAsString() { - val file = File(fileName) - val inputStream = file.inputStream() - val content = inputStream.use { it.readUpToChar(' ') } - assertEquals("Computer", content) - } - - @Test - fun whenReadFileWithoutContainingStopChar_thenFullFileContentIsReadAsString() { - val file = File(fileName) - val inputStream = file.inputStream() - val content = inputStream.use { it.readUpToChar('-') } - assertEquals(fileFullContent, content) - } - -} - diff --git a/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.in b/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.in deleted file mode 100644 index d140d4429e..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.in +++ /dev/null @@ -1,5 +0,0 @@ -Hello to Kotlin. Its: -1. Concise -2. Safe -3. Interoperable -4. Tool-friendly \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.out b/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.out deleted file mode 100644 index 63d15d2528..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/resources/Kotlin.out +++ /dev/null @@ -1,2 +0,0 @@ -Kotlin -Concise, Safe, Interoperable, Tool-friendly \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/resources/inputstream2string.txt b/core-kotlin-modules/core-kotlin-io/src/test/resources/inputstream2string.txt deleted file mode 100644 index 40ef9fc5f3..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/resources/inputstream2string.txt +++ /dev/null @@ -1,2 +0,0 @@ -Computer programming can be a hassle -It's like trying to take a defended castle \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-io/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/core-kotlin-modules/core-kotlin-io/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker deleted file mode 100644 index ca6ee9cea8..0000000000 --- a/core-kotlin-modules/core-kotlin-io/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker +++ /dev/null @@ -1 +0,0 @@ -mock-maker-inline \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/README.md b/core-kotlin-modules/core-kotlin-lang-2/README.md deleted file mode 100644 index e7f232856b..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Kotlin Lang - -This module contains articles about core features in the Kotlin language. - -### Relevant articles: -- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue) -- [Infix Functions in Kotlin](https://www.baeldung.com/kotlin-infix-functions) -- [Lambda Expressions in Kotlin](https://www.baeldung.com/kotlin-lambda-expressions) -- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final) -- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization) -- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety) -- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions) -- [If-Else Expression in Kotlin](https://www.baeldung.com/kotlin/if-else-expression) -- [Checking Whether a lateinit var Is Initialized in Kotlin](https://www.baeldung.com/kotlin/checking-lateinit) -- [Not-Null Assertion (!!) Operator in Kotlin](https://www.baeldung.com/kotlin/not-null-assertion) -- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang) diff --git a/core-kotlin-modules/core-kotlin-lang-2/pom.xml b/core-kotlin-modules/core-kotlin-lang-2/pom.xml deleted file mode 100644 index 753147728d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - core-kotlin-lang-2 - core-kotlin-lang-2 - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java b/core-kotlin-modules/core-kotlin-lang-2/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java deleted file mode 100644 index 273749e17e..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/java/com/baeldung/lazy/ClassWithHeavyInitialization.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.lazy; - -public class ClassWithHeavyInitialization { - private ClassWithHeavyInitialization() { - } - - private static class LazyHolder { - public static final ClassWithHeavyInitialization INSTANCE = new ClassWithHeavyInitialization(); - } - - public static ClassWithHeavyInitialization getInstance() { - return LazyHolder.INSTANCE; - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt deleted file mode 100644 index f4e42a4f4f..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.ifelseexpression - -fun ifStatementUsage(): String { - val number = 15 - - if (number > 0) { - return "Positive number" - } - return "Positive number not found" -} - -fun ifElseStatementUsage(): String { - val number = -50 - - if (number > 0) { - return "Positive number" - } else { - return "Negative number" - } -} - -fun ifElseExpressionUsage(): String { - val number = -50 - - val result = if (number > 0) { - "Positive number" - } else { - "Negative number" - } - return result -} - -fun ifElseExpressionSingleLineUsage(): String { - val number = -50 - val result = if (number > 0) "Positive number" else "Negative number" - - return result -} - -fun ifElseMultipleExpressionUsage(): Int { - val x = 24 - val y = 73 - - val result = if (x > y) { - println("$x is greater than $y") - x - } else { - println("$x is less than or equal to $y") - y - } - return result -} - -fun ifElseLadderExpressionUsage(): String { - val number = 60 - - val result = if (number < 0) { - "Negative number" - } else if (number in 0..9) { - "Single digit number" - } else if (number in 10..99) { - "Double digit number" - } else { - "Number has more digits" - } - return result -} - -fun ifElseNestedExpressionUsage(): Int { - val x = 37 - val y = 89 - val z = 6 - - val result = if (x > y) { - if (x > z) - x - else - z - } else { - if (y > z) - y - else - z - } - return result -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/lambda/Lambda.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/lambda/Lambda.kt deleted file mode 100644 index f35f9cdac2..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/lambda/Lambda.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.baeldung.lambda - -fun inferredType(input: Int): Int { - val square = { number: Int -> number * number } - - return square(input) -} - -fun intToBiggerString(argument: Int): String { - - val magnitude100String = { input: Int -> - val magnitude = input * 100 - magnitude.toString() - } - - return magnitude100String(argument) -} - -fun manyLambda(nums: Array): List { - val newList = nums.map { intToBiggerString(it) } - - return newList -} - -fun empty() { - val noReturn: (Int) -> Unit = { num -> println(num) } - - noReturn(5) -} - -fun invokeLambda(lambda: (Double) -> Boolean): Boolean { - return lambda(4.329) -} - -fun extendString(arg: String, num: Int): String { - val another: String.(Int) -> String = { this + it } - - return arg.another(num) -} - -fun getCalculationLambda(): (Int) -> Any { - val calculateGrade = { grade: Int -> - when (grade) { - in 0..40 -> "Fail" - in 41..70 -> "Pass" - in 71..100 -> "Distinction" - else -> false - } - } - - return calculateGrade -} - -fun getCalculationLambdaWithReturn(): (Int) -> String { - val calculateGrade: Int.() -> String = lambda@{ - if (this < 0 || this > 100) { - return@lambda "Error" - } else if (this < 40) { - return@lambda "Fail" - } else if (this < 70) { - return@lambda "Pass" - } - - "Distinction" - } - - return calculateGrade -} - -fun getCalculationAnonymousFunction(): (Int) -> String { - val calculateGrade = fun(grade: Int): String { - if (grade < 0 || grade > 100) { - return "Error" - } else if (grade < 40) { - return "Fail" - } else if (grade < 70) { - return "Pass" - } - - return "Distinction" - } - - return calculateGrade -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt deleted file mode 100644 index 37ad8c65e2..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/scope/ScopeFunctions.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.scope - -data class Student(var studentId: String = "", var name: String = "", var surname: String = "") { -} - -data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") { - fun setId(anId: Int): Teacher = apply { teacherId = anId } - fun setName(aName: String): Teacher = apply { name = aName } - fun setSurname(aSurname: String): Teacher = apply { surname = aSurname } -} - -data class Headers(val headerInfo: String) - -data class Response(val headers: Headers) - -data class RestClient(val url: String) { - fun getResponse() = Response(Headers("some header info")) -} - -data class BankAccount(val id: Int) { - fun checkAuthorization(username: String) = Unit - fun addPayee(payee: String) = Unit - fun makePayment(paymentDetails: String) = Unit - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java b/core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java deleted file mode 100644 index 01c87d9543..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/java/com/baeldung/lazy/LazyJavaUnitTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.lazy; - -import org.junit.Test; - -import static junit.framework.TestCase.assertTrue; - -public class LazyJavaUnitTest { - - @Test - public void giveHeavyClass_whenInitLazy_thenShouldReturnInstanceOnFirstCall() { - //when - ClassWithHeavyInitialization classWithHeavyInitialization = ClassWithHeavyInitialization.getInstance(); - ClassWithHeavyInitialization classWithHeavyInitialization2 = ClassWithHeavyInitialization.getInstance(); - - //then - assertTrue(classWithHeavyInitialization == classWithHeavyInitialization2); - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt deleted file mode 100644 index d9bf433208..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/ConstantUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.constant - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class ConstantUnitTest { - - @Test - fun givenConstant_whenCompareWithActualValue_thenReturnTrue() { - assertEquals(10, TestKotlinConstantObject.COMPILE_TIME_CONST) - assertEquals(30, TestKotlinConstantObject.RUN_TIME_CONST) - assertEquals(20, TestKotlinConstantObject.JAVA_STATIC_FINAL_FIELD) - - assertEquals(40, TestKotlinConstantClass.COMPANION_OBJECT_NUMBER) - } -} - diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt deleted file mode 100644 index 3c4d4db220..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantClass.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.constant - - -class TestKotlinConstantClass { - companion object { - const val COMPANION_OBJECT_NUMBER = 40 - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt deleted file mode 100644 index a6951b4481..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/constant/TestKotlinConstantObject.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.constant - - -object TestKotlinConstantObject { - const val COMPILE_TIME_CONST = 10 - - val RUN_TIME_CONST: Int - - @JvmField - val JAVA_STATIC_FINAL_FIELD = 20 - - init { - RUN_TIME_CONST = TestKotlinConstantObject.COMPILE_TIME_CONST + 20; - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt deleted file mode 100644 index 266e41e07b..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.ifelseexpression - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNotEquals - -class IfElseExpressionExampleTest { - - @Test - fun givenNumber_whenIfStatementCalled_thenReturnsString() { - assertEquals("Positive number", ifStatementUsage()) - } - - @Test - fun givenNumber_whenIfElseStatementCalled_thenReturnsString() { - assertEquals("Negative number", ifElseStatementUsage()) - } - - @Test - fun givenNumber_whenIfElseExpressionCalled_thenReturnsString() { - assertEquals("Negative number", ifElseExpressionUsage()) - } - - @Test - fun givenNumber_whenIfElseExpressionSingleLineCalled_thenReturnsString() { - assertEquals("Negative number", ifElseExpressionSingleLineUsage()) - } - - @Test - fun givenNumber_whenIfElseMultipleExpressionCalled_thenReturnsNumber() { - assertEquals(73, ifElseMultipleExpressionUsage()) - } - - @Test - fun givenNumber_whenIfElseLadderExpressionCalled_thenReturnsString() { - assertEquals("Double digit number", ifElseLadderExpressionUsage()) - } - - @Test - fun givenNumber_whenIfElseNestedExpressionCalled_thenReturnsNumber() { - assertEquals(89, ifElseNestedExpressionUsage()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt deleted file mode 100644 index 0b09d34013..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/infixfunctions/InfixFunctionsTest.kt +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.infixfunctions - -import org.junit.Assert -import org.junit.Test - -class InfixFunctionsTest { - @Test - fun testColours() { - val color = 0x123456 - val red = (color and 0xff0000) shr 16 - val green = (color and 0x00ff00) shr 8 - val blue = (color and 0x0000ff) shr 0 - - Assert.assertEquals(0x12, red) - Assert.assertEquals(0x34, green) - Assert.assertEquals(0x56, blue) - } - - @Test - fun testNewAssertions() { - class Assertion(private val target: T) { - infix fun isEqualTo(other: T) { - Assert.assertEquals(other, target) - } - - infix fun isDifferentFrom(other: T) { - Assert.assertNotEquals(other, target) - } - } - - val result = Assertion(5) - - result isEqualTo 5 - - // The following two lines are expected to fail - // result isEqualTo 6 - // result isDifferentFrom 5 - } - - @Test - fun testNewStringMethod() { - infix fun String.substringMatches(r: Regex) : List { - return r.findAll(this) - .map { it.value } - .toList() - } - - val matches = "a bc def" substringMatches ".*? ".toRegex() - Assert.assertEquals(listOf("a ", "bc "), matches) - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaKotlinUnitTest.java b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaKotlinUnitTest.java deleted file mode 100644 index 91c777c036..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaKotlinUnitTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.lambda; - -import kotlin.jvm.functions.Function1; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * Created by Paul Jervis on 24/04/2018. - */ -class LambdaKotlinUnitTest { - - @Test - void givenJava6_whenUsingAnonnymousClass_thenReturnLambdaResult() { - assertTrue(LambdaKt.invokeLambda(new Function1() { - @Override - public Boolean invoke(Double c) { - return c >= 0; - } - })); - } - - @Test - void givenJava8_whenUsingLambda_thenReturnLambdaResult() { - assertTrue(LambdaKt.invokeLambda(c -> c >= 0)); - } - - @Test - void givenJava8_whenCallingMethodWithStringExtension_thenImplementExtension() { - String actual = LambdaKt.extendString("Word", 90); - String expected = "Word90"; - - assertEquals(expected, actual); - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt deleted file mode 100644 index bddabee462..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lambda/LambdaTest.kt +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.lambda - -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class LambdaTest { - - @Test - fun whenCallingALambda_thenPerformTheAction() { - assertEquals(9, inferredType(3)) - } - - @Test - fun whenCallingAMoreComplicatedLambda_thenPerformTheAction() { - assertEquals("500", intToBiggerString(5)) - } - - @Test - fun whenPassingALambdaObject_thenCallTriggerLambda() { - val lambda = { arg: Double -> - arg == 4.329 - } - - val result = invokeLambda(lambda) - - assertTrue(result) - } - - @Test - fun whenPassingALambdaLiteral_thenCallTriggerLambda() { - val result = invokeLambda({ - true - }) - - assertTrue(result) - } - - @Test - fun whenPassingALambdaLiteralOutsideBrackets_thenCallTriggerLambda() { - val result = invokeLambda { arg -> arg.isNaN() } - - assertFalse(result) - } - - @Test - fun whenPassingAnAnonymousFunction_thenCallTriggerLambda() { - val result = invokeLambda(fun(arg: Double): Boolean { - return arg >= 0 - }) - - assertTrue(result) - } - - @Test - fun whenUsingLambda_thenCalculateGrade() { - val gradeCalculation = getCalculationLambda() - - assertEquals(false, gradeCalculation(-40)) - assertEquals("Pass", gradeCalculation(50)) - } - - @Test - fun whenUsingReturnStatementLambda_thenCalculateGrade() { - val gradeCalculation: Int.() -> String = getCalculationLambdaWithReturn() - - assertEquals("Distinction", 80.gradeCalculation()) - assertEquals("Error", 244_234_324.gradeCalculation()) - } - - @Test - fun whenUsingAnonymousFunction_thenCalculateGrade() { - val gradeCalculation = getCalculationAnonymousFunction() - - assertEquals("Error", gradeCalculation(244_234_324)) - assertEquals("Pass", gradeCalculation(50)) - } - - @Test - fun whenPassingAFunctionReference_thenCallTriggerLambda() { - val reference = Double::isFinite - val result = invokeLambda(reference) - - assertTrue(result) - } - - @Test - fun givenArray_whenMappingArray_thenPerformCalculationOnAllElements() { - val expected = listOf("100", "200", "300", "400", "500") - val actual = manyLambda(arrayOf(1, 2, 3, 4, 5)) - - assertEquals(expected, actual) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt deleted file mode 100644 index c99e438742..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.late - -import org.junit.Test -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class LateInitUnitTest { - - private lateinit var answer: String - - @Test(expected = UninitializedPropertyAccessException::class) - fun givenLateInit_WhenNotInitialized_ShouldThrowAnException() { - answer.length - } - - @Test - fun givenLateInit_TheIsInitialized_ReturnsTheInitializationStatus() { - assertFalse { this::answer.isInitialized } - answer = "42" - assertTrue { this::answer.isInitialized } - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt deleted file mode 100644 index b9b21ed4d9..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/lazy/LazyUnitTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.lazy - -import org.junit.Test -import java.util.concurrent.CountDownLatch -import java.util.concurrent.Executors -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicInteger -import kotlin.test.assertEquals - -class LazyUnitTest { - @Test - fun givenLazyValue_whenGetIt_thenShouldInitializeItOnlyOnce() { - //given - val numberOfInitializations: AtomicInteger = AtomicInteger() - val lazyValue: ClassWithHeavyInitialization by lazy { - numberOfInitializations.incrementAndGet() - ClassWithHeavyInitialization() - } - //when - println(lazyValue) - println(lazyValue) - - //then - assertEquals(numberOfInitializations.get(), 1) - } - - @Test - fun givenLazyValue_whenGetItUsingPublication_thenCouldInitializeItMoreThanOnce() { - //given - val numberOfInitializations: AtomicInteger = AtomicInteger() - val lazyValue: ClassWithHeavyInitialization by lazy(LazyThreadSafetyMode.PUBLICATION) { - numberOfInitializations.incrementAndGet() - ClassWithHeavyInitialization() - } - val executorService = Executors.newFixedThreadPool(2) - val countDownLatch = CountDownLatch(1) - //when - executorService.submit { countDownLatch.await(); println(lazyValue) } - executorService.submit { countDownLatch.await(); println(lazyValue) } - countDownLatch.countDown() - - //then - executorService.shutdown() - executorService.awaitTermination(5, TimeUnit.SECONDS) - //assertEquals(numberOfInitializations.get(), 2) - } - - class ClassWithHeavyInitialization { - - } - - - lateinit var a: String - @Test - fun givenLateInitProperty_whenAccessItAfterInit_thenPass() { - //when - a = "it" - println(a) - - //then not throw - } - - @Test(expected = UninitializedPropertyAccessException::class) - fun givenLateInitProperty_whenAccessItWithoutInit_thenThrow() { - //when - println(a) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt deleted file mode 100644 index 66fc043581..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/nullsafety/NullSafetyTest.kt +++ /dev/null @@ -1,161 +0,0 @@ -package com.baeldung.nullsafety - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNull -import kotlin.test.assertTrue - - -class NullSafetyTest { - - @Test - fun givenNonNullableField_whenAssignValueToIt_thenNotNeedToCheckAgainstNull() { - //given - var a: String = "value" - //a = null compilation error - - //then - assertEquals(a.length, 5) - } - - @Test - fun givenNullableField_whenReadValue_thenNeedToCheckAgainstNull() { - //given - var b: String? = "value" - b = null - - //when - if (b != null) { - - } else { - assertNull(b) - } - } - - @Test - fun givenComplexObject_whenUseSafeCall_thenShouldChainCallsResultingWithValue() { - //given - val p: Person? = Person(Country("ENG")) - - //when - val res = p?.country?.code - - //then - assertEquals(res, "ENG") - } - - @Test - fun givenComplexObject_whenUseSafeCall_thenShouldChainCallsResultingWithNull() { - //given - val p: Person? = Person(Country(null)) - - //when - val res = p?.country?.code - - //then - assertNull(res) - } - - @Test - fun givenCollectionOfObjects_whenUseLetOperator_thenShouldApplyActionOnlyOnNonNullValue() { - //given - val firstName = "Tom" - val secondName = "Michael" - val names: List = listOf(firstName, null, secondName) - - //when - var res = listOf() - for (item in names) { - item?.let { res = res.plus(it); it } - ?.also{it -> println("non nullable value: $it")} - } - - //then - assertEquals(2, res.size) - assertTrue { res.contains(firstName) } - assertTrue { res.contains(secondName) } - } - - @Test - fun fivenCollectionOfObject_whenUseRunOperator_thenExecuteActionOnNonNullValue(){ - //given - val firstName = "Tom" - val secondName = "Michael" - val names: List = listOf(firstName, null, secondName) - - //when - var res = listOf() - for (item in names) { - item?.run{res = res.plus(this)} - } - - //then - assertEquals(2, res.size) - assertTrue { res.contains(firstName) } - assertTrue { res.contains(secondName) } - } - - @Test - fun givenNullableReference_whenUseElvisOperator_thenShouldReturnValueIfReferenceIsNotNull() { - //given - val value: String? = "name" - - //when - val res = value?.length ?: -1 - - //then - assertEquals(res, 4) - } - - @Test - fun givenNullableReference_whenUseElvisOperator_thenShouldReturnDefaultValueIfReferenceIsNull() { - //given - val value: String? = null - - //when - val res = value?.length ?: -1 - - //then - assertEquals(res, -1) - } - - @Test - fun givenNullableField_whenUsingDoubleExclamationMarkOperatorOnNull_thenThrowNPE() { - //given - var b: String? = "value" - b = null - - //when - assertFailsWith { - b!!.length - } - } - - @Test - fun givenNullableField_whenUsingDoubleExclamationMarkOperatorOnNotNull_thenReturnValue() { - //given - val b: String? = "value" - - //then - assertEquals(b!!.length, 5) - } - - @Test - fun givenNullableList_whenUseFilterNotNullMethod_thenRemoveALlNullValues() { - //given - val list: List = listOf("a", null, "b") - - //when - val res = list.filterNotNull() - - //then - assertEquals(res.size, 2) - assertTrue { res.contains("a") } - assertTrue { res.contains("b") } - } -} - -data class Person(val country: Country?) - -data class Country(val code: String?) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt deleted file mode 100644 index cb3ed98006..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/scope/ScopeFunctionsUnitTest.kt +++ /dev/null @@ -1,143 +0,0 @@ -package com.baeldung.scope - -import org.junit.Test -import kotlin.test.assertTrue - - -class ScopeFunctionsUnitTest { - - class Logger { - - var called : Boolean = false - - fun info(message: String) { - called = true - } - - fun wasCalled() = called - } - - @Test - fun shouldTransformWhenLetFunctionUsed() { - val stringBuider = StringBuilder() - val numberOfCharacters = stringBuider.let { - it.append("This is a transformation function.") - it.append("It takes a StringBuilder instance and returns the number of characters in the generated String") - it.length - } - - assertTrue { - numberOfCharacters == 128 - } - } - - @Test - fun shouldHandleNullabilityWhenLetFunctionUsed() { - - val message: String? = "hello there!" - val charactersInMessage = message?.let { - "At this point is safe to reference the variable. Let's print the message: $it" - } ?: "default value" - - assertTrue { - charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") - } - - val aNullMessage = null - val thisIsNull = aNullMessage?.let { - "At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it" - } ?: "default value" - - assertTrue { - thisIsNull.equals("default value") - } - } - - @Test - fun shouldInitializeObjectWhenUsingApply() { - val aStudent = Student().apply { - studentId = "1234567" - name = "Mary" - surname = "Smith" - } - - assertTrue { - aStudent.name.equals("Mary") - } - } - - @Test - fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() { - val teacher = Teacher() - .setId(1000) - .setName("Martha") - .setSurname("Spector") - - assertTrue { - teacher.surname.equals("Spector") - } - } - - @Test - fun shouldAllowSideEffectWhenUsingAlso() { - val restClient = RestClient("http://www.someurl.com") - - val logger = Logger() - - val headers = restClient - .getResponse() - .also { logger.info(it.toString()) } - .headers - - assertTrue { - logger.wasCalled() && headers.headerInfo.equals("some header info") - } - - } - - @Test - fun shouldInitializeFieldWhenAlsoUsed() { - val aStudent = Student().also { it.name = "John"} - - assertTrue { - aStudent.name.equals("John") - } - } - - @Test - fun shouldLogicallyGroupObjectCallsWhenUsingWith() { - val bankAccount = BankAccount(1000) - with (bankAccount) { - checkAuthorization("someone") - addPayee("some payee") - makePayment("payment information") - } - } - - @Test - fun shouldConvertObjectWhenRunUsed() { - val stringBuider = StringBuilder() - val numberOfCharacters = stringBuider.run { - append("This is a transformation function.") - append("It takes a StringBuilder instance and returns the number of characters in the generated String") - length - } - - assertTrue { - numberOfCharacters == 128 - } - } - - @Test - fun shouldHandleNullabilityWhenRunIsUsed() { - val message: String? = "hello there!" - val charactersInMessage = message?.run { - "At this point is safe to reference the variable. Let's print the message: $this" - } ?: "default value" - - assertTrue { - charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!") - } - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt deleted file mode 100644 index 88011ab396..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/structuraljump/StructuralJumpUnitTest.kt +++ /dev/null @@ -1,121 +0,0 @@ -package com.baeldung.structuraljump - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse - -class StructuralJumpUnitTest { - - @Test - fun givenLoop_whenBreak_thenComplete() { - var value = "" - for (i in "hello_world") { - if (i == '_') - break - value += i.toString() - } - assertEquals("hello", value) - } - @Test - fun givenLoop_whenBreakWithLabel_thenComplete() { - var value = "" - outer_loop@ for (i in 'a'..'d') { - for (j in 1..3) { - value += "" + i + j - if (i == 'b' && j == 1) - break@outer_loop - } - } - assertEquals("a1a2a3b1", value) - } - - @Test - fun givenLoop_whenContinue_thenComplete() { - var result = "" - for (i in "hello_world") { - if (i == '_') - continue - result += i - } - assertEquals("helloworld", result) - } - @Test - fun givenLoop_whenContinueWithLabel_thenComplete() { - var result = "" - outer_loop@ for (i in 'a'..'c') { - for (j in 1..3) { - if (i == 'b') - continue@outer_loop - result += "" + i + j - } - } - assertEquals("a1a2a3c1c2c3", result) - } - - @Test - fun givenLambda_whenReturn_thenComplete() { - var result = returnInLambda(); - assertEquals("hello", result) - } - - private fun returnInLambda(): String { - var result = "" - "hello_world".forEach { - // non-local return directly to the caller - if (it == '_') return result - result += it.toString() - } - //this line won't be reached - return result; - } - - @Test - fun givenLambda_whenReturnWithExplicitLabel_thenComplete() { - var result = "" - "hello_world".forEach lit@{ - if (it == '_') { - // local return to the caller of the lambda, i.e. the forEach loop - return@lit - } - result += it.toString() - } - assertEquals("helloworld", result) - } - - @Test - fun givenLambda_whenReturnWithImplicitLabel_thenComplete() { - var result = "" - "hello_world".forEach { - if (it == '_') { - // local return to the caller of the lambda, i.e. the forEach loop - return@forEach - } - result += it.toString() - } - assertEquals("helloworld", result) - } - - @Test - fun givenAnonymousFunction_return_thenComplete() { - var result = "" - "hello_world".forEach(fun(element) { - // local return to the caller of the anonymous fun, i.e. the forEach loop - if (element == '_') return - result += element.toString() - }) - assertEquals("helloworld", result) - } - - @Test - fun givenAnonymousFunction_returnToLabel_thenComplete() { - var result = "" - run loop@{ - "hello_world".forEach { - // non-local return from the lambda passed to run - if (it == '_') return@loop - result += it.toString() - } - } - assertEquals("hello", result) - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md b/core-kotlin-modules/core-kotlin-lang-oop-2/README.md deleted file mode 100644 index a62a25c01d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Core Kotlin Lang OOP - -This module contains articles about Object-Oriented Programming in Kotlin - -### Relevant articles: - -- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) -- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) -- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) -- [Anonymous Inner Classes in Kotlin](https://www.baeldung.com/kotlin/anonymous-inner-classes) -- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop) diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml b/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml deleted file mode 100644 index f952911ae1..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - 4.0.0 - core-kotlin-lang-oop-2 - core-kotlin-lang-oop-2 - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk7 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-stdlib-common - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-stdlib - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-reflect - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test-junit - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test-common - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test-annotations-common - ${kotlin.version} - - - - - - 1.4.10 - - diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt deleted file mode 100644 index ea471f5d00..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/anonymous/Anonymous.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.anonymous - -import java.io.Serializable -import java.nio.channels.Channel - -fun main() { - val channel = object : Channel { - override fun isOpen() = false - - override fun close() { - } - } - - val maxEntries = 10 - val lruCache = object : LinkedHashMap(10, 0.75f) { - - override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean { - return size > maxEntries - } - } - - val map = object : LinkedHashMap() { - // omitted - } - - val serializableChannel = object : Channel, Serializable { - override fun isOpen(): Boolean { - TODO("Not yet implemented") - } - - override fun close() { - TODO("Not yet implemented") - } - } - - val obj = object { - val question = "answer" - val answer = 42 - } - println("The ${obj.question} is ${obj.answer}") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/generic/Reified.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/generic/Reified.kt deleted file mode 100644 index 37a632fe41..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/generic/Reified.kt +++ /dev/null @@ -1,6 +0,0 @@ -inline fun Iterable<*>.filterIsInstance() = filter { it is T } - -fun main(args: Array) { - val set = setOf("1984", 2, 3, "Brave new world", 11) - println(set.filterIsInstance()) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt deleted file mode 100644 index 9ea9f027fc..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/Database.kt +++ /dev/null @@ -1,35 +0,0 @@ -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/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt deleted file mode 100644 index c1c0f8823c..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegate.kt +++ /dev/null @@ -1,13 +0,0 @@ -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/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt deleted file mode 100644 index 8e261aacf2..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegation.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.kotlin.delegates - -import java.util.concurrent.locks.ReentrantLock -import kotlin.concurrent.withLock - -interface Producer { - - fun produce(): String -} - -class ProducerImpl : Producer { - - override fun produce() = "ProducerImpl" -} - -class EnhancedProducer(private val delegate: Producer) : Producer by delegate { - - override fun produce() = "${delegate.produce()} and EnhancedProducer" -} - -interface MessageService { - - fun processMessage(message: String): String -} - -class MessageServiceImpl : MessageService { - override fun processMessage(message: String): String { - return "MessageServiceImpl: $message" - } -} - -interface UserService { - - fun processUser(userId: String): String -} - -class UserServiceImpl : UserService { - - override fun processUser(userId: String): String { - return "UserServiceImpl: $userId" - } -} - -class CompositeService : UserService by UserServiceImpl(), MessageService by MessageServiceImpl() - -interface Service { - - val seed: Int - - fun serve(action: (Int) -> Unit) -} - -class ServiceImpl : Service { - - override val seed = 1 - - override fun serve(action: (Int) -> Unit) { - action(seed) - } -} - -class ServiceDecorator : Service by ServiceImpl() { - override val seed = 2 -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt deleted file mode 100644 index 7788305ea1..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/main/kotlin/com/baeldung/kotlin/delegates/User.kt +++ /dev/null @@ -1,6 +0,0 @@ -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/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/GenericsTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/GenericsTest.kt deleted file mode 100644 index b189d0f483..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/GenericsTest.kt +++ /dev/null @@ -1,143 +0,0 @@ -package com.baeldung.kotlin - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class GenericsTest { - - @Test - fun givenParametrizeClass_whenInitializeItWithSpecificType_thenShouldBeParameterized() { - //given - val parameterizedClass = ParameterizedClass("string-value") - - //when - val res = parameterizedClass.getValue() - - //then - assertTrue(res is String) - } - - @Test - fun givenParametrizeClass_whenInitializeIt_thenShouldBeParameterizedByInferredType() { - //given - val parameterizedClass = ParameterizedClass("string-value") - - //when - val res = parameterizedClass.getValue() - - //then - assertTrue(res is String) - } - - @Test - fun givenParameterizedProducerByOutKeyword_whenGetValue_thenCanAssignItToSuperType() { - //given - val parameterizedProducer = ParameterizedProducer("string") - - //when - val ref: ParameterizedProducer = parameterizedProducer - - //then - assertTrue(ref is ParameterizedProducer) - } - - @Test - fun givenParameterizedConsumerByInKeyword_whenGetValue_thenCanAssignItToSubType() { - //given - val parameterizedConsumer = ParameterizedConsumer() - - //when - val ref: ParameterizedConsumer = parameterizedConsumer - - //then - assertTrue(ref is ParameterizedConsumer) - } - - @Test - fun givenTypeProjections_whenOperateOnTwoList_thenCanAcceptListOfSubtypes() { - //given - val ints: Array = arrayOf(1, 2, 3) - val any: Array = arrayOfNulls(3) - - //when - copy(ints, any) - - //then - assertEquals(any[0], 1) - assertEquals(any[1], 2) - assertEquals(any[2], 3) - - } - - fun copy(from: Array, to: Array) { - assert(from.size == to.size) - for (i in from.indices) - to[i] = from[i] - } - - @Test - fun givenTypeProjection_whenHaveArrayOfIn_thenShouldAddElementsOfSubtypesToIt() { - //given - val objects: Array = arrayOfNulls(1) - - //when - fill(objects, 1) - - //then - assertEquals(objects[0], 1) - } - - fun fill(dest: Array, value: Int) { - dest[0] = value - } - - @Test - fun givenStartProjection_whenPassAnyType_thenCompile() { - //given - val array = arrayOf(1,2,3) - - //then - printArray(array) - - } - - fun printArray(array: Array<*>) { - array.forEach { println(it) } - } - - @Test - fun givenFunctionWithDefinedGenericConstraints_whenCallWithProperType_thenCompile(){ - //given - val listOfInts = listOf(5,2,3,4,1) - - //when - val sorted = sort(listOfInts) - - //then - assertEquals(sorted, listOf(1,2,3,4,5)) - } - - fun > sort(list: List): List{ - return list.sorted() - } - - class ParameterizedClass(private val value: A) { - - fun getValue(): A { - return value - } - } - - class ParameterizedProducer(private val value: T) { - fun get(): T { - return value - } - } - - class ParameterizedConsumer { - fun toString(value: T): String { - return value.toString() - } - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt deleted file mode 100644 index fc50730dfa..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DatabaseDelegatesTest.kt +++ /dev/null @@ -1,26 +0,0 @@ -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/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DelegateProviderTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DelegateProviderTest.kt deleted file mode 100644 index 2959ea0e3c..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/DelegateProviderTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.kotlin.delegates - -import org.junit.Test -import kotlin.properties.PropertyDelegateProvider -import kotlin.reflect.KProperty -import kotlin.test.assertEquals - -class DelegateProvider(private val field: String, private val id: Int) - : PropertyDelegateProvider> { - override operator fun provideDelegate(thisRef: T, prop: KProperty<*>): DatabaseDelegate { - println("Providing delegate for field $field and ID $id") - prop.returnType.isMarkedNullable - return DatabaseDelegate(field, id) - } -} - -class DelegateProvidingUser(val id: Int) { - var name: String by DelegateProvider("name", id) - var age: Int by DelegateProvider("age", id) -} - -class DelegateProviderTest { - @Test - fun testGetKnownFields() { - val user = DelegateProvidingUser(1) - assertEquals("George", user.name) - assertEquals(4, user.age) - } - - @Test - fun testSetKnownFields() { - val user = DelegateProvidingUser(2) - user.age = 3 - assertEquals(3, user.age) - } - - @Test(expected = NoRecordFoundException::class) - fun testGetKnownField() { - val user = DelegateProvidingUser(3) - user.name - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt b/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt deleted file mode 100644 index e65032acd4..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop-2/src/test/kotlin/com/baeldung/kotlin/delegates/InterfaceDelegationTest.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.kotlin.delegates - -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test - -class InterfaceDelegationTest { - - @Test - fun `when delegated implementation is used then it works as expected`() { - val producer = EnhancedProducer(ProducerImpl()) - assertThat(producer.produce()).isEqualTo("ProducerImpl and EnhancedProducer") - } - - @Test - fun `when composite delegation is used then it works as expected`() { - val service = CompositeService() - assertThat(service.processMessage("message")).isEqualTo("MessageServiceImpl: message") - assertThat(service.processUser("user")).isEqualTo("UserServiceImpl: user") - } - - @Test - fun `when decoration is used then delegate knows nothing about it`() { - val service = ServiceDecorator() - service.serve { - assertThat(it).isEqualTo(1) - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/README.md b/core-kotlin-modules/core-kotlin-lang-oop/README.md deleted file mode 100644 index 0c1aeb7850..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/README.md +++ /dev/null @@ -1,17 +0,0 @@ -## Core Kotlin Lang OOP - -This module contains articles about Object-Oriented Programming in Kotlin - -### Relevant articles: - -- [Data Classes in Kotlin](https://www.baeldung.com/kotlin-data-classes) -- [Sealed Classes in Kotlin](https://www.baeldung.com/kotlin-sealed-classes) -- [Extension Methods in Kotlin](https://www.baeldung.com/kotlin-extension-methods) -- [Objects in Kotlin](https://www.baeldung.com/kotlin-objects) -- [Working with Enums in Kotlin](https://www.baeldung.com/kotlin-enum) -- [Kotlin Constructors](https://www.baeldung.com/kotlin-constructors) -- [Kotlin Nested and Inner Classes](https://www.baeldung.com/kotlin-inner-classes) -- [Guide to Kotlin Interfaces](https://www.baeldung.com/kotlin-interfaces) -- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes) -- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods) -- More articles: [[next -->]](/core-kotlin-modules/core-kotlin-lang-oop-2) diff --git a/core-kotlin-modules/core-kotlin-lang-oop/pom.xml b/core-kotlin-modules/core-kotlin-lang-oop/pom.xml deleted file mode 100644 index 03fc80f07d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - 4.0.0 - core-kotlin-lang-oop - core-kotlin-lang-oop - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.assertj - assertj-core - ${assertj.version} - test - - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt deleted file mode 100644 index 72b8d330e8..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Car.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.constructor - -class Car { - val id: String - val type: String - - constructor(id: String, type: String) { - this.id = id - this.type = type - } - -} - -fun main(args: Array) { - val car = Car("1", "sport") - val s= Car("2", "suv") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt deleted file mode 100644 index 4483bfcf08..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Employee.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.constructor - -class Employee(name: String, val salary: Int): Person(name) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java deleted file mode 100644 index 57911b24ee..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/constructor/Person.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.constructor; - -class PersonJava { - final String name; - final String surname; - final Integer age; - - public PersonJava(String name, String surname) { - this.name = name; - this.surname = surname; - this.age = null; - } - - public PersonJava(String name, String surname, Integer age) { - this.name = name; - this.surname = surname; - this.age = age; - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java b/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java deleted file mode 100644 index 7eac98fe2a..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/java/com/baeldung/dataclass/Movie.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.dataclass; - -public class Movie { - - private String name; - private String studio; - private float rating; - - public Movie(String name, String studio, float rating) { - this.name = name; - this.studio = studio; - this.rating = rating; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getStudio() { - return studio; - } - - public void setStudio(String studio) { - this.studio = studio; - } - - public float getRating() { - return rating; - } - - public void setRating(float rating) { - this.rating = rating; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + Float.floatToIntBits(rating); - result = prime * result + ((studio == null) ? 0 : studio.hashCode()); - - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - - if (obj == null) - return false; - - if (getClass() != obj.getClass()) - return false; - - Movie other = (Movie) obj; - - if (name == null) { - if (other.name != null) - return false; - - } else if (!name.equals(other.name)) - return false; - - if (Float.floatToIntBits(rating) != Float.floatToIntBits(other.rating)) - return false; - - if (studio == null) { - if (other.studio != null) - return false; - - } else if (!studio.equals(other.studio)) - return false; - - return true; - } - - @Override - public String toString() { - return "Movie [name=" + name + ", studio=" + studio + ", rating=" + rating + "]"; - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt deleted file mode 100644 index 3779d74541..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/constructor/Person.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.constructor - -open class Person( - val name: String, - val age: Int? = null -) { - val upperCaseName: String = name.toUpperCase() - - init { - println("Hello, I'm $name") - - if (age != null && age < 0) { - throw IllegalArgumentException("Age cannot be less than zero!") - } - } - - init { - println("upperCaseName is $upperCaseName") - } - -} - -fun main(args: Array) { - val person = Person("John") - val personWithAge = Person("John", 22) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt deleted file mode 100644 index c0c15b2516..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Movie.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.dataclass - -data class Movie(val name: String, val studio: String, var rating: Float) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt deleted file mode 100644 index d47909bf29..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/dataclass/Sandbox.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.dataclass - -fun main(args: Array) { - - val movie = Movie("Whiplash", "Sony Pictures", 8.5F) - - println(movie.name) //Whiplash - println(movie.studio) //Sony Pictures - println(movie.rating) //8.5 - - movie.rating = 9F - - println(movie.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.0) - - val betterRating = movie.copy(rating = 9.5F) - println(betterRating.toString()) //Movie(name=Whiplash, studio=Sony Pictures, rating=9.5) - - movie.component1() //name - movie.component2() //studio - movie.component3() //rating - - val(name, studio, rating) = movie - - fun getMovieInfo() = movie - val(namef, studiof, ratingf) = getMovieInfo() -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt deleted file mode 100644 index 69cfce5601..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/CardType.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.enums - -enum class CardType(val color: String) : ICardLimit { - SILVER("gray") { - override fun getCreditLimit() = 100000 - override fun calculateCashbackPercent() = 0.25f - }, - GOLD("yellow") { - override fun getCreditLimit() = 200000 - override fun calculateCashbackPercent(): Float = 0.5f - }, - PLATINUM("black") { - override fun getCreditLimit() = 300000 - override fun calculateCashbackPercent() = 0.75f - }; - - companion object { - fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color } - fun getCardTypeByName(name: String) = valueOf(name.toUpperCase()) - } - - abstract fun calculateCashbackPercent(): Float -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt deleted file mode 100644 index 7994822a52..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/enums/ICardLimit.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.enums - -interface ICardLimit { - fun getCreditLimit(): Int -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt deleted file mode 100644 index 5b46b9570f..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/CircleRadius.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.inline.classes - -interface Drawable { - fun draw() -} - -inline class CircleRadius(private val circleRadius : Double) : Drawable { - val diameterOfCircle get() = 2 * circleRadius - fun areaOfCircle() = 3.14 * circleRadius * circleRadius - - override fun draw() { - println("Draw my circle") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt deleted file mode 100644 index 430fa509da..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/inline/classes/InlineDoubleWrapper.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.inline.classes - -inline class InlineDoubleWrapper(val doubleValue : Double) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt deleted file mode 100644 index 630afbdae7..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.interfaces - -interface BaseInterface { - fun someMethod(): String -} - -interface FirstChildInterface : BaseInterface { - override fun someMethod(): String { - return("Hello, from someMethod in FirstChildInterface") - } -} - -interface SecondChildInterface : BaseInterface { - override fun someMethod(): String { - return("Hello, from someMethod in SecondChildInterface") - } -} - -class ChildClass : FirstChildInterface, SecondChildInterface { - override fun someMethod(): String { - return super.someMethod() - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt deleted file mode 100644 index 591fde0689..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.interfaces - -interface MyInterface { - fun someMethod(): String -} - -class MyClass() : MyInterface { - override fun someMethod(): String { - return("Hello, World!") - } -} - -class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt deleted file mode 100644 index 105a85cbb3..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.interfaces - -interface FirstInterface { - fun someMethod(): String - - fun anotherMethod(): String { - return("Hello, from anotherMethod in FirstInterface") - } -} - -interface SecondInterface { - fun someMethod(): String { - return("Hello, from someMethod in SecondInterface") - } - - fun anotherMethod(): String { - return("Hello, from anotherMethod in SecondInterface") - } -} - -class SomeClass: FirstInterface, SecondInterface { - override fun someMethod(): String { - return("Hello, from someMethod in SomeClass") - } - - override fun anotherMethod(): String { - return("Hello, from anotherMethod in SomeClass") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt deleted file mode 100644 index 0758549dde..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.interfaces - -interface SimpleInterface { - val firstProp: String - val secondProp: String - get() = "Second Property" - fun firstMethod(): String - fun secondMethod(): String { - println("Hello, from: " + secondProp) - return "" - } -} - -class SimpleClass: SimpleInterface { - override val firstProp: String = "First Property" - override val secondProp: String - get() = "Second Property, Overridden!" - override fun firstMethod(): String { - return("Hello, from: " + firstProp) - } - override fun secondMethod(): String { - return("Hello, from: " + secondProp + firstProp) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt deleted file mode 100644 index 96e54716b3..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/Sealed.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.kotlin - -sealed class Result { - abstract fun map(func: (S) -> R) : Result - abstract fun mapFailure(func: (F) -> R) : Result - abstract fun get() : S? -} - -data class Success(val success: S) : Result() { - override fun map(func: (S) -> R) : Result = Success(func(success)) - override fun mapFailure(func: (F) -> R): Result = Success(success) - override fun get(): S? = success -} - -data class Failure(val failure: F) : Result() { - override fun map(func: (S) -> R) : Result = Failure(failure) - override fun mapFailure(func: (F) -> R): Result = Failure(func(failure)) - override fun get(): S? = null -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt deleted file mode 100644 index ca57b2965e..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/kotlin/StringUtil.kt +++ /dev/null @@ -1,9 +0,0 @@ -@file:JvmName("Strings") -package com.baeldung.kotlin - -fun String.escapeForXml() : String { - return this - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt deleted file mode 100644 index ee01c06646..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/nested/Computer.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.nested - -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -class Computer(val model: String) { - - companion object { - const val originCountry = "China" - fun getBuiltDate(): String { - return "2018-05-23" - } - - val log: Logger = LoggerFactory.getLogger(Computer::class.java) - } - - //Nested class - class MotherBoard(val manufacturer: String) { - fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}" - } - - //Inner class - inner class HardDisk(val sizeInGb: Int) { - fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB" - } - - interface Switcher { - fun on(): String - } - - interface Protector { - fun smart() - } - - fun powerOn(): String { - //Local class - var defaultColor = "Blue" - - class Led(val color: String) { - fun blink(): String { - return "blinking $color" - } - - fun changeDefaultPowerOnColor() { - defaultColor = "Violet" - } - } - - val powerLed = Led("Green") - log.debug("defaultColor is $defaultColor") - powerLed.changeDefaultPowerOnColor() - log.debug("defaultColor changed inside Led class to $defaultColor") - //Anonymous object - val powerSwitch = object : Switcher, Protector { - override fun on(): String { - return powerLed.blink() - } - - override fun smart() { - log.debug("Smart protection is implemented") - } - - fun changeDefaultPowerOnColor() { - defaultColor = "Yellow" - } - } - powerSwitch.changeDefaultPowerOnColor() - log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor") - return powerSwitch.on() - } - - override fun toString(): String { - return "Computer(model=$model)" - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt deleted file mode 100644 index 23c7cfb11a..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/ConsoleUtils.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.static - -class ConsoleUtils { - companion object { - @JvmStatic - fun debug(debugMessage : String) { - println("[DEBUG] $debugMessage") - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt deleted file mode 100644 index e67addc9ea..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/main/kotlin/com/baeldung/static/LoggingUtils.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.static - -fun debug(debugMessage : String) { - println("[DEBUG] $debugMessage") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java b/core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java deleted file mode 100644 index c7ef18b879..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/java/com/baeldung/kotlin/StringUtilUnitTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.kotlin; - -import kotlin.text.StringsKt; -import org.junit.Assert; -import org.junit.Test; - -import static com.baeldung.kotlin.Strings.*; - - -public class StringUtilUnitTest { - - @Test - public void shouldEscapeXmlTagsInString() { - String xml = "hi"; - - String escapedXml = escapeForXml(xml); - - Assert.assertEquals("<a>hi</a>", escapedXml); - } - - @Test - public void callingBuiltInKotlinExtensionMethod() { - String name = "john"; - - String capitalizedName = StringsKt.capitalize(name); - - Assert.assertEquals("John", capitalizedName); - } - -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt deleted file mode 100644 index 525faebd55..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.baeldung.enums - -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Test - -internal class CardTypeUnitTest { - - @Test - fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { - assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent()) - } - - @Test - fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { - assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent()) - } - - @Test - fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { - assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent()) - } - - @Test - fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() { - assertEquals(100000, CardType.SILVER.getCreditLimit()) - } - - @Test - fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() { - assertEquals(200000, CardType.GOLD.getCreditLimit()) - } - - @Test - fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() { - assertEquals(300000, CardType.PLATINUM.getCreditLimit()) - } - - @Test - fun givenSilverCardType_whenCheckColor_thenReturnColor() { - assertEquals("gray", CardType.SILVER.color) - } - - @Test - fun givenGoldCardType_whenCheckColor_thenReturnColor() { - assertEquals("yellow", CardType.GOLD.color) - } - - @Test - fun givenPlatinumCardType_whenCheckColor_thenReturnColor() { - assertEquals("black", CardType.PLATINUM.color) - } - - @Test - fun whenGetCardTypeByColor_thenSilverCardType() { - Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray")) - } - - @Test - fun whenGetCardTypeByColor_thenGoldCardType() { - Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow")) - } - - @Test - fun whenGetCardTypeByColor_thenPlatinumCardType() { - Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black")) - } - - @Test - fun whenGetCardTypeByName_thenSilverCardType() { - Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver")) - } - - @Test - fun whenGetCardTypeByName_thenGoldCardType() { - Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold")) - } - - @Test - fun whenGetCardTypeByName_thenPlatinumCardType() { - Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum")) - } - -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt deleted file mode 100644 index 8de378b6dd..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/CircleRadiusTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.inline.classes - -import org.junit.Test -import kotlin.test.assertEquals - -class CircleRadiusTest { - - @Test - fun givenRadius_ThenDiameterIsCorrectlyCalculated() { - val radius = CircleRadius(5.0) - assertEquals(10.0, radius.diameterOfCircle) - } - - @Test - fun givenRadius_ThenAreaIsCorrectlyCalculated() { - val radius = CircleRadius(5.0) - assertEquals(78.5, radius.areaOfCircle()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt deleted file mode 100644 index 349c90d6f4..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/inline/classes/InlineDoubleWrapperTest.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.inline.classes - -import org.junit.Test -import kotlin.test.assertEquals - -class InlineDoubleWrapperTest { - - @Test - fun whenInclineClassIsUsed_ThenPropertyIsReadCorrectly() { - val piDoubleValue = InlineDoubleWrapper(3.14) - assertEquals(3.14, piDoubleValue.doubleValue) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt deleted file mode 100644 index 96b99948b7..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.interfaces - -import org.junit.Test -import kotlin.test.assertEquals - -class InterfaceExamplesUnitTest { - @Test - fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() { - val simpleClass = SimpleClass() - assertEquals("Hello, from: First Property", simpleClass.firstMethod()) - assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod()) - } - - @Test - fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() { - val someClass = SomeClass() - assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod()) - assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod()) - } - - @Test - fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() { - val childClass = ChildClass() - assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod()) - } - - @Test - fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() { - val myClass = MyClass() - assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt deleted file mode 100644 index 44c5cd0ece..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/ExtensionMethods.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.kotlin - -import org.junit.Assert -import org.junit.Test - -class ExtensionMethods { - @Test - fun simpleExtensionMethod() { - Assert.assertEquals("Nothing", "Nothing".escapeForXml()) - Assert.assertEquals("<Tag>", "".escapeForXml()) - Assert.assertEquals("a&b", "a&b".escapeForXml()) - } - - @Test - fun genericExtensionMethod() { - fun T.concatAsString(b: T) : String { - return this.toString() + b.toString() - } - - Assert.assertEquals("12", "1".concatAsString("2")) - Assert.assertEquals("12", 1.concatAsString(2)) - // This doesn't compile - // Assert.assertEquals("12", 1.concatAsString(2.0)) - } - - @Test - fun infixExtensionMethod() { - infix fun Number.toPowerOf(exponent: Number): Double { - return Math.pow(this.toDouble(), exponent.toDouble()) - } - - Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1) - Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1) - } - - @Test - fun operatorExtensionMethod() { - operator fun List.times(by: Int): List { - return this.map { it * by } - } - - Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2) - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt deleted file mode 100644 index 8c7509f653..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/SealedTest.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.baeldung.kotlin - -import org.junit.Assert -import org.junit.Test - -class SealedTest { - fun divide(a: Int, b: Int) : Result = when (b) { - 0 -> Failure("Division by zero") - else -> Success(a.toFloat() / b) - } - - @Test - fun testSuccess() { - val result = divide(10, 5) - Assert.assertEquals(Success(2.0f), result) - } - - @Test - fun testError() { - val result = divide(10, 0) - Assert.assertEquals(Failure("Division by zero"), result) - } - - @Test - fun testMatchOnSuccess() { - val result = divide(10, 5) - when (result) { - is Success -> { - // Expected - } - is Failure -> Assert.fail("Expected Success") - } - } - - @Test - fun testMatchOnError() { - val result = divide(10, 0) - when (result) { - is Failure -> { - // Expected - } - } - } - - @Test - fun testGetSuccess() { - val result = divide(10, 5) - Assert.assertEquals(2.0f, result.get()) - } - - @Test - fun testGetError() { - val result = divide(10, 0) - Assert.assertNull(result.get()) - } - - @Test - fun testMapOnSuccess() { - val result = divide(10, 5) - .map { "Result: $it" } - Assert.assertEquals(Success("Result: 2.0"), result) - } - - @Test - fun testMapOnError() { - val result = divide(10, 0) - .map { "Result: $it" } - Assert.assertEquals(Failure("Division by zero"), result) - } - - @Test - fun testMapFailureOnSuccess() { - val result = divide(10, 5) - .mapFailure { "Failure: $it" } - Assert.assertEquals(Success(2.0f), result) - } - - @Test - fun testMapFailureOnError() { - val result = divide(10, 0) - .mapFailure { "Failure: $it" } - Assert.assertEquals(Failure("Failure: Division by zero"), result) - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt deleted file mode 100644 index 46ba42e1e5..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/Counter.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.kotlin.objects - -object Counter { - private var count: Int = 0 - - fun currentCount() = count - - fun increment() { - ++count - } - - fun decrement() { - --count - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt deleted file mode 100644 index 0bbb1c741d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ObjectsTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.kotlin.objects - -import org.junit.Assert -import org.junit.Test - -class ObjectsTest { - @Test - fun singleton() { - - Assert.assertEquals(42, SimpleSingleton.answer) - Assert.assertEquals("Hello, world!", SimpleSingleton.greet("world")) - } - - @Test - fun counter() { - Assert.assertEquals(0, Counter.currentCount()) - Counter.increment() - Assert.assertEquals(1, Counter.currentCount()) - Counter.decrement() - Assert.assertEquals(0, Counter.currentCount()) - } - - @Test - fun comparator() { - val strings = listOf("Hello", "World") - val sortedStrings = strings.sortedWith(ReverseStringComparator) - - Assert.assertEquals(listOf("World", "Hello"), sortedStrings) - } - - @Test - fun companion() { - Assert.assertEquals("You can see me", OuterClass.public) - // Assert.assertEquals("You can't see me", OuterClass.secret) // Cannot access 'secret' - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt deleted file mode 100644 index 4abb7a668d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/OuterClass.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.kotlin.objects - -class OuterClass { - companion object { - private val secret = "You can't see me" - val public = "You can see me" - } - - fun getSecretValue() = secret -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt deleted file mode 100644 index 20dc2d8c5b..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/ReverseStringComparator.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.kotlin.objects - -object ReverseStringComparator : Comparator { - override fun compare(o1: String, o2: String) = o1.reversed().compareTo(o2.reversed()) -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt deleted file mode 100644 index bfafd8183f..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/SimpleSingleton.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.kotlin.objects - -object SimpleSingleton { - val answer = 42; - - fun greet(name: String) = "Hello, $name!" -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt deleted file mode 100644 index 36cd476110..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/kotlin/objects/StaticClass.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.kotlin.objects - -class StaticClass { - companion object { - @JvmStatic - val staticField = 42 - } -} diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt deleted file mode 100644 index 7882d85b3c..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.nested - -import org.assertj.core.api.Assertions.assertThat -import org.junit.jupiter.api.Test - -class ComputerUnitTest { - - @Test - fun givenComputer_whenPowerOn_thenBlink() { - val computer = Computer("Desktop") - - assertThat(computer.powerOn()).isEqualTo("blinking Green") - } - - @Test - fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() { - val motherBoard = Computer.MotherBoard("MotherBoard Inc.") - - assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23") - } - - @Test - fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() { - val hardDisk = Computer("Desktop").HardDisk(1000) - - assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt deleted file mode 100644 index 8abed144eb..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/ConsoleUtilsUnitTest.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.static - -import org.junit.Test - -class ConsoleUtilsUnitTest { - @Test - fun givenAStaticMethod_whenCalled_thenNoErrorIsThrown() { - ConsoleUtils.debug("test message") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt deleted file mode 100644 index 59587ff009..0000000000 --- a/core-kotlin-modules/core-kotlin-lang-oop/src/test/kotlin/com/baeldung/static/LoggingUtilsUnitTest.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.static - -import org.junit.Test - -class LoggingUtilsUnitTest { - @Test - fun givenAPackageMethod_whenCalled_thenNoErrorIsThrown() { - debug("test message") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/README.md b/core-kotlin-modules/core-kotlin-lang/README.md deleted file mode 100644 index eaeae76854..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Core Kotlin Lang - -This module contains articles about core features in the Kotlin language. - -### Relevant articles: -- [Guide to the “when{}” Block in Kotlin](https://www.baeldung.com/kotlin-when) -- [Difference Between “==” and “===” Operators in Kotlin](https://www.baeldung.com/kotlin-equality-operators) -- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach) -- [Destructuring Declarations in Kotlin](https://www.baeldung.com/kotlin-destructuring-declarations) -- [Try-with-resources in Kotlin](https://www.baeldung.com/kotlin-try-with-resources) -- [Operator Overloading in Kotlin](https://www.baeldung.com/kotlin-operator-overloading) -- [Inline Functions in Kotlin](https://www.baeldung.com/kotlin-inline-functions) -- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type) -- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges) -- [Creating a Kotlin Range Iterator on a Custom Object](https://www.baeldung.com/kotlin-custom-range-iterator) -- [[More --> ]](/core-kotlin-modules/core-kotlin-lang-2) diff --git a/core-kotlin-modules/core-kotlin-lang/pom.xml b/core-kotlin-modules/core-kotlin-lang/pom.xml deleted file mode 100644 index d3ac7f690c..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - core-kotlin-lang - core-kotlin-lang - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt deleted file mode 100644 index d3167ce033..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Person.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.destructuringdeclarations - -data class Person(var id: Int, var name: String, var age: Int) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt deleted file mode 100644 index e3da9b46a4..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Result.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.destructuringdeclarations - -data class Result(val result: Int, val status: String) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt deleted file mode 100644 index f845d01539..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/destructuringdeclarations/Sandbox.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.destructuringdeclarations - -fun main(args: Array) { - - //2.1. Objects - val person = Person(1, "Jon Snow", 20) - val(id, name, age) = person - - println(id) //1 - println(name) //Jon Snow - println(age) //20 - - //2.2. Functions - fun getPersonInfo() = Person(2, "Ned Stark", 45) - val(idf, namef, agef) = getPersonInfo() - - fun twoValuesReturn(): Pair { - - // needed code - - return Pair(1, "success") - } - - // Now, to use this function: - val (result, status) = twoValuesReturn() - - //2.3. Collections and For-loops - var map: HashMap = HashMap() - map.put(1, person) - - for((key, value) in map){ - println("Key: $key, Value: $value") - } - - //2.4. Underscore and Destructuring in Lambdas - val (_, name2, age2) = person - val (id3, name3) = person - - map.mapValues { entry -> "${entry.value}!" } - map.mapValues { (key, value) -> "$value!" } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt deleted file mode 100644 index 030169bb8a..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/equalityoperators/User.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.equalityoperators - -data class User(val name: String, val age: Int, val hobbies: List) diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/forEach/forEach.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/forEach/forEach.kt deleted file mode 100644 index 20eda4e64f..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/forEach/forEach.kt +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.forEach - - -class Country(val name : String, val cities : List) - -class City(val name : String, val streets : List) - -fun City.getStreetsWithCityName() : List { - return streets.map { "$name, $it" }.toList() -} - -fun Country.getCitiesWithCountryName() : List { - return cities.flatMap { it.getStreetsWithCityName() } - .map { "$name, $it" } -} - -class World { - - private val streetsOfAmsterdam = listOf("Herengracht", "Prinsengracht") - private val streetsOfBerlin = listOf("Unter den Linden","Tiergarten") - private val streetsOfMaastricht = listOf("Grote Gracht", "Vrijthof") - private val countries = listOf( - Country("Netherlands", listOf(City("Maastricht", streetsOfMaastricht), - City("Amsterdam", streetsOfAmsterdam))), - Country("Germany", listOf(City("Berlin", streetsOfBerlin)))) - - fun allCountriesIt() { - countries.forEach { println(it.name) } - } - - fun allCountriesItExplicit() { - countries.forEach { it -> println(it.name) } - } - - //here we cannot refer to 'it' anymore inside the forEach - fun allCountriesExplicit() { - countries.forEach { c -> println(c.name) } - } - - fun allNested() { - countries.forEach { - println(it.name) - it.cities.forEach { - println(" ${it.name}") - it.streets.forEach { println(" $it") } - } - } - } - - fun allTable() { - countries.forEach { c -> - c.cities.forEach { p -> - p.streets.forEach { println("${c.name} ${p.name} $it") } - } - } - } - - fun allStreetsFlatMap() { - - countries.flatMap { it.cities} - .flatMap { it.streets} - .forEach { println(it) } - } - - fun allFlatMapTable() { - - countries.flatMap { it.getCitiesWithCountryName() } - .forEach { println(it) } - } -} - -fun main(args : Array) { - - val world = World() - - world.allCountriesExplicit() - - world.allNested() - - world.allTable() - - world.allStreetsFlatMap() - - world.allFlatMapTable() -} - - diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt deleted file mode 100644 index 3b179642ba..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.inline - -import kotlin.random.Random - -/** - * An extension function on all collections to apply a function to all collection - * elements. - */ -fun Collection.each(block: (T) -> Unit) { - for (e in this) block(e) -} - -/** - * In order to see the the JVM bytecode: - * 1. Compile the Kotlin file using `kotlinc Inline.kt` - * 2. Take a peek at the bytecode using the `javap -c InlineKt` - */ -fun main() { - val numbers = listOf(1, 2, 3, 4, 5) - val random = random() - - numbers.each { println(random * it) } // capturing the random variable -} - -/** - * Generates a random number. - */ -private fun random(): Int = Random.nextInt() \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Money.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Money.kt deleted file mode 100644 index 93eb78c5b6..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Money.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.operators - -import java.math.BigDecimal - -enum class Currency { - DOLLARS, EURO -} - -class Money(val amount: BigDecimal, val currency: Currency) : Comparable { - - override fun compareTo(other: Money): Int = - convert(Currency.DOLLARS).compareTo(other.convert(Currency.DOLLARS)) - - fun convert(currency: Currency): BigDecimal = TODO() - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other !is Money) return false - - if (amount != other.amount) return false - if (currency != other.currency) return false - - return true - } - - override fun hashCode(): Int { - var result = amount.hashCode() - result = 31 * result + currency.hashCode() - return result - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Page.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Page.kt deleted file mode 100644 index 8a0ee48a36..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Page.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.operators - -interface Page { - fun pageNumber(): Int - fun pageSize(): Int - fun elements(): MutableList -} - -operator fun Page.invoke(index: Int): T = elements()[index] -operator fun Page.get(index: Int): T = elements()[index] -operator fun Page.get(start: Int, endExclusive: Int): List = elements().subList(start, endExclusive) -operator fun Page.set(index: Int, value: T) { - elements()[index] = value -} - -operator fun Page.contains(element: T): Boolean = element in elements() -operator fun Page.iterator() = elements().iterator() \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt deleted file mode 100644 index e3282e64cc..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.operators - -data class Point(val x: Int, val y: Int) - -operator fun Point.unaryMinus() = Point(-x, -y) -operator fun Point.not() = Point(y, x) -operator fun Point.inc() = Point(x + 1, y + 1) -operator fun Point.dec() = Point(x - 1, y - 1) - -operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y) -operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y) -operator fun Point.times(other: Point): Point = Point(x * other.x, y * other.y) -operator fun Point.div(other: Point): Point = Point(x / other.x, y / other.y) -operator fun Point.rem(other: Point): Point = Point(x % other.x, y % other.y) -operator fun Point.times(factor: Int): Point = Point(x * factor, y * factor) -operator fun Int.times(point: Point): Point = Point(point.x * this, point.y * this) - -class Shape { - val points = mutableListOf() - - operator fun Point.unaryPlus() { - points.add(this) - } -} - -fun shape(init: Shape.() -> Unit): Shape { - val shape = Shape() - shape.init() - - return shape -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Utils.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Utils.kt deleted file mode 100644 index 0f16544f38..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Utils.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.operators - -import java.math.BigInteger - -operator fun MutableCollection.plusAssign(element: T) { - add(element) -} -operator fun BigInteger.plus(other: Int): BigInteger = add(BigInteger("$other")) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/CharRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/CharRange.kt deleted file mode 100644 index 3151674d61..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/CharRange.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - for (ch in 'a'..'f') { - print(ch) - } - println() - - for (ch in 'f' downTo 'a') { - print(ch) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Color.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Color.kt deleted file mode 100644 index ef7adf06b5..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Color.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.range - -enum class Color(val rgb: Int) { - BLUE(0x0000FF), - GREEN(0x008000), - RED(0xFF0000), - MAGENTA(0xFF00FF), - YELLOW(0xFFFF00); -} - -fun main(args: Array) { - - println(Color.values().toList()); - val red = Color.RED - val yellow = Color.YELLOW - val range = red..yellow - - println(range.contains(Color.MAGENTA)) - println(range.contains(Color.BLUE)) - println(range.contains(Color.GREEN)) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Filter.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Filter.kt deleted file mode 100644 index 0e611b14cf..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Filter.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - val r = 1..10 - - //Apply filter - val f = r.filter { it -> it % 2 == 0 } - println(f) - - //Map - val m = r.map { it -> it * it } - println(m) - - //Reduce - val rdc = r.reduce { a, b -> a + b } - println(rdc) - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/FirstLast.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/FirstLast.kt deleted file mode 100644 index b82f5a8b9b..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/FirstLast.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - println((1..9).first) - println((1..9 step 2).step) - println((3..9).reversed().last) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt deleted file mode 100644 index 19dcab89b2..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/OtherRangeFunctions.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - val r = 1..20 - println(r.min()) - println(r.max()) - println(r.sum()) - println(r.average()) - println(r.count()) - - val repeated = listOf(1, 1, 2, 4, 4, 6, 10) - println(repeated.distinct()) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Range.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Range.kt deleted file mode 100644 index c313181599..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Range.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - for (i in 1..9) { - print(i) - } - println() - - for (i in 9 downTo 1) { - print(i) - } - println() - - for (i in 1.rangeTo(9)) { - print(i) - } - println() - - for (i in 9.downTo(1)) { - print(i) - } - println() - - for (i in 1 until 9) { - print(i) - } -} diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/ReverseRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/ReverseRange.kt deleted file mode 100644 index 875cf62200..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/ReverseRange.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - (1..9).reversed().forEach { - print(it) - } - - println() - - (1..9).reversed().step(3).forEach { - print(it) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Step.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Step.kt deleted file mode 100644 index b9c5d48588..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/Step.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - for(i in 1..9 step 2){ - print(i) - } - - println() - - for (i in 9 downTo 1 step 2){ - print(i) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/UntilRange.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/UntilRange.kt deleted file mode 100644 index 2c116a286f..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/range/UntilRange.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.range - -fun main(args: Array) { - - for (i in 1 until 9) { - print(i) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt deleted file mode 100644 index c1ab8e1610..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/rangeiterator/CustomColor.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.rangeiterator - -import java.lang.IllegalStateException - -class CustomColor(val rgb: Int): Comparable { - - override fun compareTo(other: CustomColor): Int { - return this.rgb.compareTo(other.rgb) - } - - operator fun rangeTo(that: CustomColor) = ColorRange(this, that) - - operator fun inc(): CustomColor { - return CustomColor(rgb + 1) - } - - init { - if(rgb < 0x000000 || rgb > 0xFFFFFF){ - throw IllegalStateException("RGB must be between 0 and 16777215") - } - } - - override fun toString(): String { - return "CustomColor(rgb=$rgb)" - } -} -class ColorRange(override val start: CustomColor, - override val endInclusive: CustomColor) : ClosedRange, Iterable{ - - override fun iterator(): Iterator { - return ColorIterator(start, endInclusive) - } -} - -class ColorIterator(val start: CustomColor, val endInclusive: CustomColor) : Iterator { - - var initValue = start - - override fun hasNext(): Boolean { - return initValue <= endInclusive - } - - override fun next(): CustomColor { - return initValue++ - } -} - -fun main(args: Array) { - val a = CustomColor(0xABCDEF) - val b = CustomColor(-1) - val c = CustomColor(0xABCDFF) - - for(color in a..c){ - println(color) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt deleted file mode 100644 index a4cd7b98f0..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/whenblock/WhenBlockTypes.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.whenblock - -enum class UnixFileType { - D, HYPHEN_MINUS, L -} - -sealed class UnixFile { - - abstract fun getFileType(): UnixFileType - - class RegularFile(val content: String) : UnixFile() { - override fun getFileType(): UnixFileType { - return UnixFileType.HYPHEN_MINUS - } - } - - class Directory(val children: List) : UnixFile() { - override fun getFileType(): UnixFileType { - return UnixFileType.D - } - } - - class SymbolicLink(val originalFile: UnixFile) : UnixFile() { - override fun getFileType(): UnixFileType { - return UnixFileType.L - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt deleted file mode 100644 index 0728d55b73..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/equalityoperators/EqualityTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.equalityoperators - -import org.junit.Test -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class EqualityTest { - - // Checks referential equality - @Test - fun givenTwoIntegers_whenCheckReference_thenEqualReference() { - val a = Integer(10) - val b = Integer(10) - - assertFalse(a === b) - } - - // Checks structural equality - @Test - fun givenTwoIntegers_whenCheckValue_thenStructurallyEqual() { - val a = Integer(10) - val b = Integer(10) - - assertTrue(a == b) - } - - @Test - fun givenUser_whenCheckReference_thenEqualReference() { - val user = User("John", 30, listOf("Hiking, Chess")) - val user2 = User("Sarah", 28, listOf("Shopping, Gymnastics")) - - assertFalse(user === user2) - } - - @Test - fun givenUser_whenCheckValue_thenStructurallyEqual() { - val user = User("John", 30, listOf("Hiking, Chess")) - val user2 = User("John", 30, listOf("Hiking, Chess")) - - assertTrue(user == user2) - } - - @Test - fun givenArray_whenCheckReference_thenEqualReference() { - val hobbies = arrayOf("Riding motorcycle, Video games") - val hobbies2 = arrayOf("Riding motorcycle, Video games") - - assertFalse(hobbies === hobbies2) - } - - @Test - fun givenArray_whenCheckContent_thenStructurallyEqual() { - val hobbies = arrayOf("Hiking, Chess") - val hobbies2 = arrayOf("Hiking, Chess") - - assertTrue(hobbies contentEquals hobbies2) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PageTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PageTest.kt deleted file mode 100644 index fa6e1773bd..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PageTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.operators - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class PageTest { - - private val page = PageImpl(1, 10, "Java", "Kotlin", "Scala") - - @Test - fun `Get convention should work as expected`() { - assertEquals(page[1], "Kotlin") - assertEquals(page[1, 3], listOf("Kotlin", "Scala")) - } - - @Test - fun `Invoke convention should work as expected`() { - assertEquals(page(1), "Kotlin") - } - - @Test - fun `In convention should work on a page as expected`() { - assertTrue("Kotlin" in page) - } - -} - -private class PageImpl(val page: Int, val size: Int, vararg val elements: T) : Page { - override fun pageNumber(): Int = page - override fun pageSize(): Int = size - override fun elements(): MutableList = mutableListOf(*elements) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PointTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PointTest.kt deleted file mode 100644 index 168ab6431d..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/PointTest.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.operators - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class PointTest { - - private val p1 = Point(1, 2) - private val p2 = Point(2, 3) - - @Test - fun `We should be able to add two points together using +`() { - assertEquals(p1 + p2, Point(3, 5)) - } - - @Test - fun `We shoud be able to subtract one point from another using -`() { - assertEquals(p1 - p2, Point(-1, -1)) - } - - @Test - fun `We should be able to multiply two points together with *`() { - assertEquals(p1 * p2, Point(2, 6)) - } - - @Test - fun `We should be able to divide one point by another`() { - assertEquals(p1 / p2, Point(0, 0)) - } - - @Test - fun `We should be able to scale a point by an integral factor`() { - assertEquals(p1 * 2, Point(2, 4)) - assertEquals(2 * p1, Point(2, 4)) - } - - @Test - fun `We should be able to add points to an empty shape`() { - val line = shape { - +Point(0, 0) - +Point(1, 3) - } - - assertTrue(Point(0, 0) in line.points) - assertTrue(Point(1, 3) in line.points) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/UtilsTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/UtilsTest.kt deleted file mode 100644 index 4abe962cb5..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/operators/UtilsTest.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.operators - -import java.math.BigInteger -import org.junit.Test -import kotlin.test.assertEquals - -class UtilsTest { - - @Test - fun `We should be able to add an int value to an existing BigInteger using +`() { - assertEquals(BigInteger.ZERO + 1, BigInteger.ONE) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/CharRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/CharRangeTest.kt deleted file mode 100644 index 0e23f508b6..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/CharRangeTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class CharRangeTest { - - @Test - fun testCharRange() { - assertEquals(listOf('a', 'b', 'c'), ('a'..'c').toList()) - } - - @Test - fun testCharDownRange() { - assertEquals(listOf('c', 'b', 'a'), ('c'.downTo('a')).toList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ColorTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ColorTest.kt deleted file mode 100644 index 4ac3270fcc..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ColorTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class ColorTest { - - @Test - fun testEnumRange() { - - println(Color.values().toList()); - val red = Color.RED - val yellow = Color.YELLOW - val range = red..yellow - - assertTrue { range.contains(Color.MAGENTA) } - assertFalse { range.contains(Color.BLUE) } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FilterTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FilterTest.kt deleted file mode 100644 index d0e2df8860..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FilterTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class FilterTest { - - val r = 1..10 - - @Test - fun filterTest() { - assertEquals(listOf(2, 4, 6, 8, 10), r.filter { it -> it % 2 == 0 }.toList()) - } - - @Test - fun mapTest() { - assertEquals(listOf(1, 4, 9, 16, 25, 36, 49, 64, 81, 100), r.map { it -> it * it }.toList()) - } - - @Test - fun reduceTest() { - assertEquals(55, r.reduce { a, b -> a + b }) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FirstLastTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FirstLastTest.kt deleted file mode 100644 index ca797e9c9b..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/FirstLastTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class FirstLastTest { - - @Test - fun testFirst() { - assertEquals(1, (1..9).first) - } - - @Test - fun testLast() { - assertEquals(9, (1..9).last) - } - - @Test - fun testStep() { - assertEquals(2, (1..9 step 2).step) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt deleted file mode 100644 index d2d36bbfae..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/OtherRangeFunctionsTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class OtherRangeFunctionsTest { - - val r = 1..20 - val repeated = listOf(1, 1, 2, 4, 4, 6, 10) - - @Test - fun testMin() { - assertEquals(1, r.min()) - } - - @Test - fun testMax() { - assertEquals(20, r.max()) - } - - @Test - fun testSum() { - assertEquals(210, r.sum()) - } - - @Test - fun testAverage() { - assertEquals(10.5, r.average()) - } - - @Test - fun testCount() { - assertEquals(20, r.count()) - } - - @Test - fun testDistinct() { - assertEquals(listOf(1, 2, 4, 6, 10), repeated.distinct()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/RangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/RangeTest.kt deleted file mode 100644 index 48fa483924..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/RangeTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class RangeTest { - - @Test - fun testRange() { - assertEquals(listOf(1,2,3), (1.rangeTo(3).toList())) - } - - @Test - fun testDownTo(){ - assertEquals(listOf(3,2,1), (3.downTo(1).toList())) - } - - @Test - fun testUntil(){ - assertEquals(listOf(1,2), (1.until(3).toList())) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt deleted file mode 100644 index 7e1c7badb7..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/ReverseRangeTest.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class ReverseRangeTest { - - @Test - fun reversedTest() { - assertEquals(listOf(9, 6, 3), (1..9).reversed().step(3).toList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/StepTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/StepTest.kt deleted file mode 100644 index 4570ceeb0a..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/StepTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class StepTest { - - @Test - fun testStep() { - assertEquals(listOf(1, 3, 5, 7, 9), (1..9 step 2).toList()) - } - - @Test - fun testStepDown() { - assertEquals(listOf(9, 7, 5, 3, 1), (9 downTo 1 step 2).toList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt deleted file mode 100644 index f941c7f1e6..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/range/UntilRangeTest.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.range - -import org.junit.Test -import kotlin.test.assertEquals - -class UntilRangeTest { - - @Test - fun testUntil() { - assertEquals(listOf(1, 2, 3, 4), (1 until 5).toList()) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt deleted file mode 100644 index 676b47ae7a..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/rangeiterator/CustomColorTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.rangeiterator - -import org.junit.Test -import java.lang.IllegalStateException -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue - -class CustomColorTest { - - @Test - fun testInvalidConstructor(){ - assertFailsWith(IllegalStateException::class){ - CustomColor(-1) - } - } - - @Test - fun assertHas10Colors(){ - assertTrue { - val a = CustomColor(1) - val b = CustomColor(10) - val range = a..b - for(cc in range){ - println(cc) - } - range.toList().size == 10 - } - } - - @Test - fun assertContains0xCCCCCC(){ - assertTrue { - val a = CustomColor(0xBBBBBB) - val b = CustomColor(0xDDDDDD) - val range = a..b - range.contains(CustomColor(0xCCCCCC)) - } - } - -} - diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt deleted file mode 100644 index d17832b380..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/trywithresource/UseTest.kt +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.trywithresource - -import org.junit.Test -import java.beans.ExceptionListener -import java.beans.XMLEncoder -import java.io.* -import java.lang.Exception -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import kotlin.test.fail - -class UseTest { - - @Test - fun givenCloseable_whenUseIsCalled_thenItIsClosed() { - val stringWriter = StringWriter() - val writer = BufferedWriter(stringWriter) //Using a BufferedWriter because after close() it throws. - writer.use { - assertEquals(writer, it) - - it.write("something") - } - try { - writer.write("something else") - - fail("write() should have thrown an exception because the writer is closed.") - } catch (e: IOException) { - //Ok - } - - assertEquals("something", stringWriter.toString()) - } - - @Test - fun givenAutoCloseable_whenUseIsCalled_thenItIsClosed() { - val baos = ByteArrayOutputStream() - val encoder = XMLEncoder(PrintStream(baos)) //XMLEncoder is AutoCloseable but not Closeable. - //Here, we use a PrintStream because after close() it throws. - encoder.exceptionListener = ThrowingExceptionListener() - encoder.use { - assertEquals(encoder, it) - - it.writeObject("something") - } - try { - encoder.writeObject("something else") - encoder.flush() - - fail("write() should have thrown an exception because the encoder is closed.") - } catch (e: IOException) { - //Ok - } - } - - @Test - fun whenSimpleFormIsUsed_thenItWorks() { - StringWriter().use { it.write("something") } - } -} - -class ThrowingExceptionListener : ExceptionListener { - override fun exceptionThrown(e: Exception?) { - if(e != null) { - throw e - } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt deleted file mode 100644 index 468352dbed..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/voidtypes/VoidTypesUnitTest.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.voidtypes - -import org.junit.jupiter.api.Test -import kotlin.test.assertNull -import kotlin.test.assertTrue - -class VoidTypesUnitTest { - - // Un-commenting below methods will result into compilation error - // as the syntax used is incorrect and is used for explanation in tutorial. - - // fun returnTypeAsVoidAttempt1(): Void { - // println("Trying with Void as return type") - // } - - // fun returnTypeAsVoidAttempt2(): Void { - // println("Trying with Void as return type") - // return null - // } - - fun returnTypeAsVoidSuccess(): Void? { - println("Function can have Void as return type") - return null - } - - fun unitReturnTypeForNonMeaningfulReturns(): Unit { - println("No meaningful return") - } - - fun unitReturnTypeIsImplicit() { - println("Unit Return type is implicit") - } - - fun alwaysThrowException(): Nothing { - throw IllegalArgumentException() - } - - fun invokeANothingOnlyFunction() { - alwaysThrowException() - - var name = "Tom" - } - - @Test - fun givenJavaVoidFunction_thenMappedToKotlinUnit() { - assertTrue(System.out.println() is Unit) - } - - @Test - fun givenVoidReturnType_thenReturnsNullOnly() { - assertNull(returnTypeAsVoidSuccess()) - } - - @Test - fun givenUnitReturnTypeDeclared_thenReturnsOfTypeUnit() { - assertTrue(unitReturnTypeForNonMeaningfulReturns() is Unit) - } - - @Test - fun givenUnitReturnTypeNotDeclared_thenReturnsOfTypeUnit() { - assertTrue(unitReturnTypeIsImplicit() is Unit) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt b/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt deleted file mode 100644 index 31b6ad69f5..0000000000 --- a/core-kotlin-modules/core-kotlin-lang/src/test/kotlin/com/baeldung/whenblock/WhenBlockUnitTest.kt +++ /dev/null @@ -1,136 +0,0 @@ -package com.baeldung.whenblock - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Test - -class WhenBlockUnitTest { - - @Test - fun testWhenExpression() { - val directoryType = UnixFileType.D - - val objectType = when (directoryType) { - UnixFileType.D -> "d" - UnixFileType.HYPHEN_MINUS -> "-" - UnixFileType.L -> "l" - } - - assertEquals("d", objectType) - } - - @Test - fun testWhenExpressionWithDefaultCase() { - val fileType = UnixFileType.L - - val result = when (fileType) { - UnixFileType.L -> "linking to another file" - else -> "not a link" - } - - assertEquals("linking to another file", result) - } - - @Test(expected = IllegalArgumentException::class) - fun testWhenExpressionWithThrowException() { - val fileType = UnixFileType.L - - val result: Boolean = when (fileType) { - UnixFileType.HYPHEN_MINUS -> true - else -> throw IllegalArgumentException("Wrong type of file") - } - } - - @Test - fun testWhenStatement() { - val fileType = UnixFileType.HYPHEN_MINUS - - when (fileType) { - UnixFileType.HYPHEN_MINUS -> println("Regular file type") - UnixFileType.D -> println("Directory file type") - } - } - - @Test - fun testCaseCombination() { - val fileType = UnixFileType.D - - val frequentFileType: Boolean = when (fileType) { - UnixFileType.HYPHEN_MINUS, UnixFileType.D -> true - else -> false - } - - assertTrue(frequentFileType) - } - - @Test - fun testWhenWithoutArgument() { - val fileType = UnixFileType.L - - val objectType = when { - fileType === UnixFileType.L -> "l" - fileType === UnixFileType.HYPHEN_MINUS -> "-" - fileType === UnixFileType.D -> "d" - else -> "unknown file type" - } - - assertEquals("l", objectType) - } - - @Test - fun testDynamicCaseExpression() { - val unixFile = UnixFile.SymbolicLink(UnixFile.RegularFile("Content")) - - when { - unixFile.getFileType() == UnixFileType.D -> println("It's a directory!") - unixFile.getFileType() == UnixFileType.HYPHEN_MINUS -> println("It's a regular file!") - unixFile.getFileType() == UnixFileType.L -> println("It's a soft link!") - } - } - - @Test - fun testCollectionCaseExpressions() { - val regularFile = UnixFile.RegularFile("Test Content") - val symbolicLink = UnixFile.SymbolicLink(regularFile) - val directory = UnixFile.Directory(listOf(regularFile, symbolicLink)) - - val isRegularFileInDirectory = when (regularFile) { - in directory.children -> true - else -> false - } - - val isSymbolicLinkInDirectory = when { - symbolicLink in directory.children -> true - else -> false - } - - assertTrue(isRegularFileInDirectory) - assertTrue(isSymbolicLinkInDirectory) - } - - @Test - fun testRangeCaseExpressions() { - val fileType = UnixFileType.HYPHEN_MINUS - - val isCorrectType = when (fileType) { - in UnixFileType.D..UnixFileType.L -> true - else -> false - } - - assertTrue(isCorrectType) - } - - @Test - fun testWhenWithIsOperatorWithSmartCase() { - val unixFile: UnixFile = UnixFile.RegularFile("Test Content") - - val result = when (unixFile) { - is UnixFile.RegularFile -> unixFile.content - is UnixFile.Directory -> unixFile.children.map { it.getFileType() }.joinToString(", ") - is UnixFile.SymbolicLink -> unixFile.originalFile.getFileType() - } - - assertEquals("Test Content", result) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-strings/README.md b/core-kotlin-modules/core-kotlin-strings/README.md deleted file mode 100644 index 0e3d8ea57f..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Core Kotlin Strings - -This module contains articles about core Kotlin strings. - -### Relevant articles: -- [Generate a Random Alphanumeric String in Kotlin](https://www.baeldung.com/kotlin-random-alphanumeric-string) -- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison) -- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings) -- [Kotlin String Templates](https://www.baeldung.com/kotlin-string-template) diff --git a/core-kotlin-modules/core-kotlin-strings/pom.xml b/core-kotlin-modules/core-kotlin-strings/pom.xml deleted file mode 100644 index fb2998e9e1..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - core-kotlin-strings - core-kotlin-strings - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-strings/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt b/core-kotlin-modules/core-kotlin-strings/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt deleted file mode 100644 index 4b2d863618..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/src/main/kotlin/com/baeldung/stringtemplates/Templates.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.baeldung.stringtemplates - -/** - * Example of a useful function defined in Kotlin String class - */ -fun padExample(): String { - return "Hello".padEnd(10, '!') -} - -/** - * Example of a simple string template usage - */ -fun simpleTemplate(n: Int): String { - val message = "n = $n" - return message -} - -/** - * Example of a string template with a simple expression - */ -fun templateWithExpression(n: Int): String { - val message = "n + 1 = ${n + 1}" - return message -} - -/** - * Example of a string template with expression containing some logic - */ -fun templateWithLogic(n: Int): String { - val message = "$n is ${if (n > 0) "positive" else "not positive"}" - return message -} - -/** - * Example of nested string templates - */ -fun nestedTemplates(n: Int): String { - val message = "$n is ${if (n > 0) "positive" else if (n < 0) "negative and ${if (n % 2 == 0) "even" else "odd"}" else "zero"}" - return message -} - -/** - * Example of joining array's element into a string with a default separator - */ -fun templateJoinArray(): String { - val numbers = listOf(1, 1, 2, 3, 5, 8) - val message = "first Fibonacci numbers: ${numbers.joinToString()}" - return message -} - -/** - * Example of escaping the dollar sign - */ -fun notAStringTemplate(): String { - val message = "n = \$n" - return message -} - -/** - * Example of a simple triple quoted string - */ -fun showFilePath(): String { - val path = """C:\Repository\read.me""" - return path -} - -/** - * Example of a multiline string - */ -fun showMultiline(): String { - val receipt = """Item 1: $1.00 -Item 2: $0.50""" - return receipt -} - -/** - * Example of a multiline string with indentation - */ -fun showMultilineIndent(): String { - val receipt = """Item 1: $1.00 - >Item 2: $0.50""".trimMargin(">") - return receipt -} - -/** - * Example of a triple quoted string with a not-working escape sequence - */ -fun showTripleQuotedWrongEscape(): String { - val receipt = """Item 1: $1.00\nItem 2: $0.50""" - return receipt -} - -/** - * Example of a triple quoted string with a correctly working escape sequence - */ - -fun showTripleQuotedCorrectEscape(): String { - val receipt = """Item 1: $1.00${"\n"}Item 2: $0.50""" - return receipt -} - -fun main(args: Array) { - println(padExample()) - println(simpleTemplate(10)) - println(templateWithExpression(5)) - println(templateWithLogic(7)) - println(nestedTemplates(-5)) - println(templateJoinArray()) - println(notAStringTemplate()) - println(showFilePath()) - println(showMultiline()) - println(showMultilineIndent()) - println(showTripleQuotedWrongEscape()) - println(showTripleQuotedCorrectEscape()) -} diff --git a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/randomstring/RandomStringUnitTest.kt b/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/randomstring/RandomStringUnitTest.kt deleted file mode 100644 index 5b84d1f67d..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/randomstring/RandomStringUnitTest.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.randomstring - -import org.apache.commons.lang3.RandomStringUtils -import org.junit.Before -import org.junit.jupiter.api.BeforeAll -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import java.security.SecureRandom -import java.util.concurrent.ThreadLocalRandom -import kotlin.experimental.and -import kotlin.streams.asSequence -import kotlin.test.assertEquals - -const val STRING_LENGTH = 10 -const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" - -class RandomStringUnitTest { - private val charPool : List = ('a'..'z') + ('A'..'Z') + ('0'..'9') - - @Test - fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() { - var randomString = ThreadLocalRandom.current() - .ints(STRING_LENGTH.toLong(), 0, charPool.size) - .asSequence() - .map(charPool::get) - .joinToString("") - - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) - assertEquals(STRING_LENGTH, randomString.length) - } - - @Test - fun givenAStringLength_whenUsingKotlin_thenReturnAlphanumericString() { - var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) } - .map(charPool::get) - .joinToString("") - - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) - assertEquals(STRING_LENGTH, randomString.length) - } - - @Test - fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString() { - var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH) - - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) - assertEquals(STRING_LENGTH, randomString.length) - } - - @Test - fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() { - val random = SecureRandom() - val bytes = ByteArray(STRING_LENGTH) - random.nextBytes(bytes) - - var randomString = (0..bytes.size - 1).map { i -> - charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt()) - }.joinToString("") - - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) - assertEquals(STRING_LENGTH, randomString.length) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringcomparison/StringComparisonTest.kt b/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringcomparison/StringComparisonTest.kt deleted file mode 100644 index 49ff798faa..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringcomparison/StringComparisonTest.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.stringcomparison - -import org.junit.Test -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -class StringComparisonUnitTest { - - @Test - fun `compare using equals operator`() { - val first = "kotlin" - val second = "kotlin" - val firstCapitalized = "KOTLIN" - assertTrue { first == second } - assertFalse { first == firstCapitalized } - } - - @Test - fun `compare using referential equals operator`() { - val first = "kotlin" - val second = "kotlin" - val third = String("kotlin".toCharArray()) - assertTrue { first === second } - assertFalse { first === third } - } - - @Test - fun `compare using equals method`() { - val first = "kotlin" - val second = "kotlin" - val firstCapitalized = "KOTLIN" - assertTrue { first.equals(second) } - assertFalse { first.equals(firstCapitalized) } - assertTrue { first.equals(firstCapitalized, true) } - } - - @Test - fun `compare using compare method`() { - val first = "kotlin" - val second = "kotlin" - val firstCapitalized = "KOTLIN" - assertTrue { first.compareTo(second) == 0 } - assertTrue { first.compareTo(firstCapitalized) == 32 } - assertTrue { firstCapitalized.compareTo(first) == -32 } - assertTrue { first.compareTo(firstCapitalized, true) == 0 } - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringconcatenation/StringConcatenationTest.kt b/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringconcatenation/StringConcatenationTest.kt deleted file mode 100644 index 9ac011f7d2..0000000000 --- a/core-kotlin-modules/core-kotlin-strings/src/test/kotlin/com/baeldung/stringconcatenation/StringConcatenationTest.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.stringconcatenation - -import org.junit.Test -import kotlin.test.assertEquals - -class StringConcatenationTest { - - @Test - fun givenTwoStrings_concatenateWithTemplates_thenEquals() { - val a = "Hello" - val b = "Baeldung" - val c = "$a $b" - - assertEquals("Hello Baeldung", c) - } - - @Test - fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() { - val a = "Hello" - val b = "Baeldung" - val c = a + " " + b - - assertEquals("Hello Baeldung", c) - } - - @Test - fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() { - val a = "Hello" - val b = "Baeldung" - - val builder = StringBuilder() - builder.append(a).append(" ").append(b) - - val c = builder.toString() - - assertEquals("Hello Baeldung", c) - } - - @Test - fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() { - val a = "Hello" - val b = "Baeldung" - val c = a.plus(" ").plus(b) - - assertEquals("Hello Baeldung", c) - } - -} diff --git a/core-kotlin-modules/core-kotlin-testing/README.md b/core-kotlin-modules/core-kotlin-testing/README.md deleted file mode 100644 index f4d89593a7..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Core Kotlin Testing - -This module contains articles about testing in Kotlin - -### Relevant articles: -- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin) \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-testing/pom.xml b/core-kotlin-modules/core-kotlin-testing/pom.xml deleted file mode 100644 index d38bc62409..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - core-kotlin-testing - core-kotlin-testing - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.1.1 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/Calculator.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/Calculator.kt deleted file mode 100644 index 9f6e3ab2b9..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/Calculator.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.junit5 - -class Calculator { - fun add(a: Int, b: Int) = a + b - - fun divide(a: Int, b: Int) = if (b == 0) { - throw DivideByZeroException(a) - } else { - a / b - } - - fun square(a: Int) = a * a - - fun squareRoot(a: Int) = Math.sqrt(a.toDouble()) - - fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble()) -} diff --git a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt deleted file mode 100644 index 07cab3b76e..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/CalculatorUnitTest.kt +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.junit5 - -import org.junit.jupiter.api.* -import org.junit.jupiter.api.function.Executable - -class CalculatorUnitTest { - private val calculator = Calculator() - - @Test - fun `Adding 1 and 3 should be equal to 4`() { - Assertions.assertEquals(4, calculator.add(1, 3)) - } - - @Test - fun `Dividing by zero should throw the DivideByZeroException`() { - val exception = Assertions.assertThrows(DivideByZeroException::class.java) { - calculator.divide(5, 0) - } - - Assertions.assertEquals(5, exception.numerator) - } - - @Test - fun `The square of a number should be equal to that number multiplied in itself`() { - Assertions.assertAll( - Executable { Assertions.assertEquals(1, calculator.square(1)) }, - Executable { Assertions.assertEquals(4, calculator.square(2)) }, - Executable { Assertions.assertEquals(9, calculator.square(3)) } - ) - } - - @TestFactory - fun testSquaresFactory() = listOf( - DynamicTest.dynamicTest("when I calculate 1^2 then I get 1") { Assertions.assertEquals(1,calculator.square(1))}, - DynamicTest.dynamicTest("when I calculate 2^2 then I get 4") { Assertions.assertEquals(4,calculator.square(2))}, - DynamicTest.dynamicTest("when I calculate 3^2 then I get 9") { Assertions.assertEquals(9,calculator.square(3))} - ) - - @TestFactory - fun testSquaresFactory2() = listOf( - 1 to 1, - 2 to 4, - 3 to 9, - 4 to 16, - 5 to 25) - .map { (input, expected) -> - DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { - Assertions.assertEquals(expected, calculator.square(input)) - } - } - - private val squaresTestData = listOf( - 1 to 1, - 2 to 4, - 3 to 9, - 4 to 16, - 5 to 25) - - @TestFactory - fun testSquaresFactory3() = squaresTestData - .map { (input, expected) -> - DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") { - Assertions.assertEquals(expected, calculator.square(input)) - } - } - @TestFactory - fun testSquareRootsFactory3() = squaresTestData - .map { (expected, input) -> - DynamicTest.dynamicTest("I calculate the square root of $input then I get $expected") { - Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input)) - } - } - - @Tags( - Tag("slow"), - Tag("logarithms") - ) - @Test - fun `Log to base 2 of 8 should be equal to 3`() { - Assertions.assertEquals(3.0, calculator.log(2, 8)) - } -} diff --git a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt deleted file mode 100644 index 5675367fd5..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/DivideByZeroException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.junit5 - -class DivideByZeroException(val numerator: Int) : Exception() diff --git a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt b/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt deleted file mode 100644 index e3fe998efd..0000000000 --- a/core-kotlin-modules/core-kotlin-testing/src/test/kotlin/com/baeldung/junit5/SimpleUnitTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.junit5 - -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Disabled -import org.junit.jupiter.api.Test - -class SimpleUnitTest { - - @Test - fun `isEmpty should return true for empty lists`() { - val list = listOf() - Assertions.assertTrue(list::isEmpty) - } - - @Test - @Disabled - fun `3 is equal to 4`() { - Assertions.assertEquals(3, 4) { - "Three does not equal four" - } - } -} diff --git a/core-kotlin-modules/core-kotlin/README.md b/core-kotlin-modules/core-kotlin/README.md deleted file mode 100644 index a890658e95..0000000000 --- a/core-kotlin-modules/core-kotlin/README.md +++ /dev/null @@ -1,15 +0,0 @@ -## Core Kotlin - -This module contains articles about Kotlin core features. - -### Relevant articles: - -- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro) -- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) -- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) -- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) -- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator) -- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences) -- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) -- [Exception Handling in Kotlin](https://www.baeldung.com/kotlin/exception-handling) -- [Quick Guide to Kotlin Default and Named Arguments](https://www.baeldung.com/kotlin/default-named-arguments) diff --git a/core-kotlin-modules/core-kotlin/pom.xml b/core-kotlin-modules/core-kotlin/pom.xml deleted file mode 100644 index 6e36b7c8ef..0000000000 --- a/core-kotlin-modules/core-kotlin/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - core-kotlin - core-kotlin - jar - - - com.baeldung.core-kotlin-modules - core-kotlin-modules - 1.0.0-SNAPSHOT - - - - - org.junit.platform - junit-platform-runner - ${junit.platform.version} - test - - - - - 1.1.1 - - - \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java deleted file mode 100644 index 93b9a3984a..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/ArrayExample.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.interoperability; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -public class ArrayExample { - - public int sumValues(int[] nums) { - int res = 0; - - for (int x:nums) { - res += x; - } - - return res; - } - - public void writeList() throws IOException { - File file = new File("E://file.txt"); - FileReader fr = new FileReader(file); - fr.close(); - } -} diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java deleted file mode 100644 index 4a070a0f97..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/interoperability/Customer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.interoperability; - -public class Customer { - - private String firstName; - private String lastName; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java deleted file mode 100644 index 1c477ce039..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/introduction/StringUtils.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.introduction; - -public class StringUtils { - public static String toUpperCase(String name) { - return name.toUpperCase(); - } -} diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java deleted file mode 100644 index ac933d6228..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/Application.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.mavenjavakotlin; - -import com.baeldung.mavenjavakotlin.services.JavaService; - -public class Application { - - private static final String JAVA = "java"; - private static final String KOTLIN = "kotlin"; - - public static void main(String[] args) { - String language = args[0]; - switch (language) { - case JAVA: - new JavaService().sayHello(); - break; - case KOTLIN: - new KotlinService().sayHello(); - break; - default: - // Do nothing - break; - } - } - -} diff --git a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java b/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java deleted file mode 100644 index b767e761af..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/java/com/baeldung/mavenjavakotlin/services/JavaService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.mavenjavakotlin.services; - -public class JavaService { - - public void sayHello() { - System.out.println("Java says 'Hello World!'"); - } - -} diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/DefaultArguments.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/DefaultArguments.kt deleted file mode 100644 index 691b3475b4..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/DefaultArguments.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.arguments - -fun main() { - - // Skip both the connectTimeout and enableRetry arguments - connect("http://www.baeldung.com") - - // Skip only the enableRetry argument: - connect("http://www.baeldung.com", 5000) - - // Skip only the middle argument connectTimeout - // connect("http://www.baeldung.com", false) // This results in a compiler error - - // Because we skipped the connectTimeout argument, we must pass the enableRetry as a named argument - connect("http://www.baeldung.com", enableRetry = false) - - // Overriding Functions and Default Arguments - val realConnector = RealConnector() - realConnector.connect("www.baeldung.com") - realConnector.connect() -} - -fun connect(url: String, connectTimeout: Int = 1000, enableRetry: Boolean = true) { - println("The parameters are url = $url, connectTimeout = $connectTimeout, enableRetry = $enableRetry") -} - -open class AbstractConnector { - open fun connect(url: String = "localhost") { - // function implementation - } -} - -class RealConnector : AbstractConnector() { - override fun connect(url: String) { - println("The parameter is url = $url") - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/NamedArguments.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/NamedArguments.kt deleted file mode 100644 index 0cbf6f158a..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/arguments/NamedArguments.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.arguments - -fun main() { - resizePane(newSize = 10, forceResize = true, noAnimation = false) - - // Swap the order of last two named arguments - resizePane(newSize = 11, noAnimation = false, forceResize = true) - - // Named arguments can be passed in any order - resizePane(forceResize = true, newSize = 12, noAnimation = false) - - // Mixing Named and Positional Arguments - // Kotlin 1.3 would allow us to name only the arguments after the positional ones - resizePane(20, true, noAnimation = false) - - // Using a positional argument in the middle of named arguments (supported from Kotlin 1.4.0) - // resizePane(newSize = 20, true, noAnimation = false) - - // Only the last argument as a positional argument (supported from Kotlin 1.4.0) - // resizePane(newSize = 30, forceResize = true, false) - - // Use a named argument in the middle of positional arguments (supported from Kotlin 1.4.0) - // resizePane(40, forceResize = true, false) -} - -fun resizePane(newSize: Int, forceResize: Boolean, noAnimation: Boolean) { - println("The parameters are newSize = $newSize, forceResize = $forceResize, noAnimation = $noAnimation") -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt deleted file mode 100644 index 6689ab43e4..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.exceptionhandling - -import java.io.IOException - -class ExceptionHandling { - - fun tryCatchBlock(): Int? { - try { - val message = "Welcome to Kotlin Tutorials" - return message.toInt() - } catch (exception: NumberFormatException) { - println("NumberFormatException in the code") - return null - } - } - - fun tryCatchExpression(): Int? { - val number = try { - val message = "Welcome to Kotlin Tutorials" - message.toInt() - } catch (exception: NumberFormatException) { - println("NumberFormatException in the code") - null - } - return number - } - - fun multipleCatchBlock(): Int? { - return try { - val result = 25 / 0 - result - } catch (exception: NumberFormatException) { - println("NumberFormatException in the code") - null - } catch (exception: ArithmeticException) { - println("ArithmeticException in the code") - null - } catch (exception: Exception) { - println("Exception in the code") - null - } - } - - fun nestedTryCatchBlock(): Int? { - return try { - val firstNumber = 50 / 2 * 0 - try { - val secondNumber = 100 / firstNumber - secondNumber - } catch (exception: ArithmeticException) { - println("ArithmeticException in the code") - null - } - } catch (exception: NumberFormatException) { - println("NumberFormatException in the code") - null - } - } - - fun finallyBlock(): Int? { - return try { - val message = "Welcome to Kotlin Tutorials" - message.toInt() - } catch (exception: NumberFormatException) { - println("NumberFormatException in the code") - null - } finally { - println("In the Finally block") - } - } - - fun throwKeyword(): Int { - val message = "Welcome to Kotlin Tutorials" - if (message.length > 10) throw IllegalArgumentException("String is invalid") - else return message.length - } - - fun throwExpression(): Int? { - val message: String? = null - return message?.length ?: throw IllegalArgumentException("String is null") - } - - @Throws(IOException::class) - fun throwsAnnotation(): String?{ - val filePath = null - return filePath ?: throw IOException("File path is invalid") - } -} diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt deleted file mode 100644 index aacd8f7915..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Example1.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.introduction - -fun main(args: Array){ - println("hello word") -} diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt deleted file mode 100644 index bb91dd1eae..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/Item.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.introduction - -open class Item(val id: String, val name: String = "unknown_name") { - open fun getIdOfItem(): String { - return id - } -} - -class ItemWithCategory(id: String, name: String, val categoryId: String) : Item(id, name) { - override fun getIdOfItem(): String { - return id + name - } -} - diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt deleted file mode 100644 index dfcf17df7c..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ItemService.kt +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.introduction - -import java.util.* - -class ItemService { - fun findItemNameForId(id: String): Item? { - val itemId = UUID.randomUUID().toString() - return Item(itemId, "name-$itemId") - } -} - -class ItemManager(val categoryId: String, val dbConnection: String) { - var email = "" - - constructor(categoryId: String, dbConnection: String, email: String) - : this(categoryId, dbConnection) { - this.email = email - } - - fun isFromSpecificCategory(catId: String): Boolean { - return categoryId == catId - } - - fun makeAnalyisOfCategory(catId: String): Unit { - val result = if (catId == "100") "Yes" else "No" - println(result) - `object`() - } - - fun sum(a: Int, b: Int): Int { - return a + b - } - - fun `object`(): String { - return "this is object" - } - -} - -fun main(args: Array) { - val numbers = arrayOf("first", "second", "third", "fourth") - - for (n in numbers) { - println(n) - } - - for (i in 2..9 step 2) { - println(i) - } - - val res = 1.rangeTo(10).map { it * 2 } - println(res) - - val firstName = "Tom" - val secondName = "Mary" - val concatOfNames = "$firstName + $secondName" - println("Names: $concatOfNames") - val sum = "four: ${2 + 2}" - - val itemManager = ItemManager("cat_id", "db://connection") - ItemManager(categoryId = "catId", dbConnection = "db://Connection") - val result = "function result: ${itemManager.isFromSpecificCategory("1")}" - println(result) - - val number = 2 - if (number < 10) { - println("number less that 10") - } else if (number > 10) { - println("number is greater that 10") - } - - val name = "John" - when (name) { - "John" -> println("Hi man") - "Alice" -> println("Hi lady") - } - - val items = listOf(1, 2, 3, 4) - - - val rwList = mutableListOf(1, 2, 3) - rwList.add(5) -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt deleted file mode 100644 index e71292c60a..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/ListExtension.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.introduction - -import java.util.concurrent.ThreadLocalRandom - -class ListExtension { - fun List.random(): T? { - if (this.isEmpty()) return null - return get(ThreadLocalRandom.current().nextInt(count())) - } - - fun getRandomElementOfList(list: List): T? { - return list.random() - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt deleted file mode 100644 index 0ed30ed5b4..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/introduction/MathematicsOperations.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.introduction - -class MathematicsOperations { - fun addTwoNumbers(a: Int, b: Int): Int { - return a + b - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt deleted file mode 100644 index 10d6a792d8..0000000000 --- a/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/mavenjavakotlin/KotlinService.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.mavenjavakotlin - -class KotlinService { - - fun sayHello() { - System.out.println("Kotlin says 'Hello World!'") - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java b/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java deleted file mode 100644 index 2c386eaad3..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/java/com/baeldung/introduction/JavaCallToKotlinUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.introduction; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class JavaCallToKotlinUnitTest { - @Test - public void givenKotlinClass_whenCallFromJava_shouldProduceResults() { - //when - int res = new MathematicsOperations().addTwoNumbers(2, 4); - - //then - assertEquals(6, res); - - } -} diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt deleted file mode 100644 index af7aa4406f..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.exceptionhandling - -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.assertThrows -import java.io.IOException -import kotlin.test.assertNull - -class ExceptionHandlingUnitTest { - - private val classUnderTest: ExceptionHandling = ExceptionHandling() - - @Test - fun givenInvalidConversion_whenTryCatchUsed_thenReturnsCatchBlockValue(){ - assertNull(classUnderTest.tryCatchBlock()) - } - - @Test - fun givenInvalidConversion_whenTryCatchExpressionUsed_thenReturnsCatchBlockValue(){ - assertNull(classUnderTest.tryCatchExpression()) - } - - @Test - fun givenDivisionByZero_whenMultipleCatchUsed_thenReturnsCatchBlockValue(){ - assertNull(classUnderTest.multipleCatchBlock()) - } - - @Test - fun givenDivisionByZero_whenNestedTryCatchUsed_thenReturnsNestedCatchBlockValue(){ - assertNull(classUnderTest.nestedTryCatchBlock()) - } - - @Test - fun givenInvalidConversion_whenTryCatchFinallyUsed_thenReturnsCatchAndFinallyBlock(){ - assertNull(classUnderTest.finallyBlock()) - } - - @Test - fun givenIllegalArgument_whenThrowKeywordUsed_thenThrowsException(){ - assertThrows { classUnderTest.throwKeyword() } - } - - @Test - fun givenIllegalArgument_whenElvisExpressionUsed_thenThrowsException(){ - assertThrows { classUnderTest.throwExpression() } - } - - @Test - fun whenAnnotationUsed_thenThrowsException(){ - assertThrows { classUnderTest.throwsAnnotation() } - } -} diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt deleted file mode 100644 index 8e9467f92a..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/ArrayTest.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.interoperability - -import org.junit.Test -import kotlin.test.assertEquals - -class ArrayTest { - - @Test - fun givenArray_whenValidateArrayType_thenComplete () { - val ex = ArrayExample() - val numArray = intArrayOf(1, 2, 3) - - assertEquals(ex.sumValues(numArray), 6) - } - - @Test - fun givenCustomer_whenGetSuperType_thenComplete() { - val instance = Customer::class - val supertypes = instance.supertypes - - assertEquals(supertypes[0].toString(), "kotlin.Any") - } - - @Test - fun givenCustomer_whenGetConstructor_thenComplete() { - val instance = Customer::class.java - val constructors = instance.constructors - - assertEquals(constructors.size, 1) - assertEquals(constructors[0].name, "com.baeldung.interoperability.Customer") - } - - fun makeReadFile() { - val ax = ArrayExample() - ax.writeList() - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt deleted file mode 100644 index c1b09cd0c1..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/interoperability/CustomerTest.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.interoperability - -import org.junit.Test -import kotlin.test.assertEquals - -class CustomerTest { - - @Test - fun givenCustomer_whenNameAndLastNameAreAssigned_thenComplete() { - val customer = Customer() - - // Setter method is being called - customer.firstName = "Frodo" - customer.lastName = "Baggins" - - // Getter method is being called - assertEquals(customer.firstName, "Frodo") - assertEquals(customer.lastName, "Baggins") - } - -} - diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt deleted file mode 100644 index 2ba14a7462..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ItemServiceTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.introduction - -import org.junit.Test -import kotlin.test.assertNotNull - -class ItemServiceTest { - - @Test - fun givenItemId_whenGetForOptionalItem_shouldMakeActionOnNonNullValue() { - //given - val id = "item_id" - val itemService = ItemService() - - //when - val result = itemService.findItemNameForId(id) - - //then - assertNotNull(result?.let { it -> it.id }) - assertNotNull(result!!.id) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt deleted file mode 100644 index 5dddf9bfc9..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/KotlinJavaInteroperabilityTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.introduction - -import org.junit.Test -import kotlin.test.assertEquals - - -class KotlinJavaInteroperabilityTest { - - @Test - fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() { - //given - val name = "tom" - - //whene - val res = StringUtils.toUpperCase(name) - - //then - assertEquals(res, "TOM") - } -} diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt deleted file mode 100644 index 5e5166074e..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/LambdaTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.introduction - -import org.junit.Test -import kotlin.test.assertEquals - - -class LambdaTest { - - @Test - fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() { - //given - val listOfNumbers = listOf(1, 2, 3) - - //when - val sum = listOfNumbers.reduce { a, b -> a + b } - - //then - assertEquals(6, sum) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt deleted file mode 100644 index 38f244297b..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/introduction/ListExtensionTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.introduction - -import org.junit.Test -import kotlin.test.assertTrue - -class ListExtensionTest { - - @Test - fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList() { - //given - val elements = listOf("a", "b", "c") - - //when - val result = ListExtension().getRandomElementOfList(elements) - - //then - assertTrue(elements.contains(result)) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt deleted file mode 100644 index 434f177927..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/nullassertion/NotNullAssertionUnitTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.nullassertion - -import org.junit.Test -import kotlin.test.assertEquals - -class NotNullAssertionUnitTest { - - @Test - fun givenNullableValue_WhenNotNull_ShouldExtractTheValue() { - val answer: String? = "42" - - assertEquals(42, answer!!.toInt()) - } - - @Test(expected = KotlinNullPointerException::class) - fun givenNullableValue_WhenIsNull_ThenShouldThrow() { - val noAnswer: String? = null - noAnswer!! - } -} diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt deleted file mode 100644 index 2956a35f8a..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt +++ /dev/null @@ -1,55 +0,0 @@ - -import org.junit.jupiter.api.Test -import java.util.concurrent.ThreadLocalRandom -import kotlin.test.assertTrue - -class RandomNumberTest { - - @Test - fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() { - val randomNumber = Math.random() - assertTrue { randomNumber >=0 } - assertTrue { randomNumber <= 1 } - } - - @Test - fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() { - val randomDouble = ThreadLocalRandom.current().nextDouble() - val randomInteger = ThreadLocalRandom.current().nextInt() - val randomLong = ThreadLocalRandom.current().nextLong() - assertTrue { randomDouble >= 0 } - assertTrue { randomDouble <= 1 } - assertTrue { randomInteger >= Integer.MIN_VALUE } - assertTrue { randomInteger <= Integer.MAX_VALUE } - assertTrue { randomLong >= Long.MIN_VALUE } - assertTrue { randomLong <= Long.MAX_VALUE } - } - - @Test - fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() { - val randomDouble = Math.random() - assertTrue { randomDouble >=0 } - assertTrue { randomDouble <= 1 } - } - - @Test - fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() { - val randomInteger = (1..12).shuffled().first() - assertTrue { randomInteger >= 1 } - assertTrue { randomInteger <= 12 } - } - - @Test - fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() { - val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0) - val randomInteger = ThreadLocalRandom.current().nextInt(1, 10) - val randomLong = ThreadLocalRandom.current().nextLong(1, 10) - assertTrue { randomDouble >= 1 } - assertTrue { randomDouble <= 10 } - assertTrue { randomInteger >= 1 } - assertTrue { randomInteger <= 10 } - assertTrue { randomLong >= 1 } - assertTrue { randomLong <= 10 } - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt deleted file mode 100644 index a41e213c44..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/sequences/SequencesTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.sequeces - -import org.junit.Test -import kotlin.test.assertEquals -import java.time.Instant - -class SequencesTest { - - @Test - fun shouldBuildSequenceWhenUsingFromElements() { - val seqOfElements = sequenceOf("first" ,"second", "third") - .toList() - assertEquals(3, seqOfElements.count()) - } - - @Test - fun shouldBuildSequenceWhenUsingFromFunction() { - val seqFromFunction = generateSequence(Instant.now()) {it.plusSeconds(1)} - .take(3) - .toList() - assertEquals(3, seqFromFunction.count()) - } - - @Test - fun shouldBuildSequenceWhenUsingFromChunks() { - val seqFromChunks = sequence { - yield(1) - yieldAll((2..5).toList()) - }.toList() - assertEquals(5, seqFromChunks.count()) - } - - @Test - fun shouldBuildSequenceWhenUsingFromCollection() { - val seqFromIterable = (1..10) - .asSequence() - .toList() - assertEquals(10, seqFromIterable.count()) - } - - @Test - fun shouldShowNoCountDiffWhenUsingWithAndWithoutSequence() { - val withSequence = (1..10).asSequence() - .filter{it % 2 == 1} - .map { it * 2 } - .toList() - val withoutSequence = (1..10) - .filter{it % 2 == 1} - .map { it * 2 } - .toList() - assertEquals(withSequence.count(), withoutSequence.count()) - } - -} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt deleted file mode 100644 index 347290de72..0000000000 --- a/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/ternary/TernaryOperatorTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.ternary - -import org.junit.Test -import kotlin.test.assertEquals - -class TernaryOperatorTest { - - @Test - fun `using If`() { - val a = true - val result = if (a) "yes" else "no" - assertEquals("yes", result) - } - - @Test - fun `using When`() { - val a = true - val result = when(a) { - true -> "yes" - false -> "no" - } - assertEquals("yes", result) - } - - @Test - fun `using elvis`() { - val a: String? = null - val result = a ?: "Default" - - assertEquals("Default", result) - } -} \ No newline at end of file diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml deleted file mode 100644 index 67520a7dee..0000000000 --- a/core-kotlin-modules/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - com.baeldung.core-kotlin-modules - core-kotlin-modules - core-kotlin-modules - pom - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - core-kotlin - core-kotlin-advanced - core-kotlin-annotations - core-kotlin-collections - core-kotlin-collections-2 - core-kotlin-concurrency - core-kotlin-date-time - core-kotlin-design-patterns - core-kotlin-io - core-kotlin-lang - core-kotlin-lang-2 - core-kotlin-lang-oop - core-kotlin-lang-oop-2 - core-kotlin-strings - core-kotlin-testing - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - - - - 1.3.30 - - - diff --git a/docker/README.md b/docker/README.md index 7948b3d663..fcace3978f 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,3 +1,4 @@ ## Relevant Articles: - [Introduction to Docker Compose](https://www.baeldung.com/docker-compose) +- [Reusing Docker Layers with Spring Boot](https://www.baeldung.com/docker-layers-spring-boot) diff --git a/docker/docker-spring-boot-postgres/.gitignore b/docker/docker-spring-boot-postgres/.gitignore new file mode 100644 index 0000000000..802324853e --- /dev/null +++ b/docker/docker-spring-boot-postgres/.gitignore @@ -0,0 +1,38 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + + +### Custom exclusions ### + +*.jar diff --git a/docker/docker-spring-boot-postgres/.mvn/wrapper/MavenWrapperDownloader.java b/docker/docker-spring-boot-postgres/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..e76d1f3241 --- /dev/null +++ b/docker/docker-spring-boot-postgres/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.jar b/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..2cc7d4a55c Binary files /dev/null and b/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.jar differ diff --git a/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.properties b/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..642d572ce9 --- /dev/null +++ b/docker/docker-spring-boot-postgres/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/docker/docker-spring-boot-postgres/mvnw b/docker/docker-spring-boot-postgres/mvnw new file mode 100755 index 0000000000..a16b5431b4 --- /dev/null +++ b/docker/docker-spring-boot-postgres/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/docker/docker-spring-boot-postgres/mvnw.cmd b/docker/docker-spring-boot-postgres/mvnw.cmd new file mode 100644 index 0000000000..c8d43372c9 --- /dev/null +++ b/docker/docker-spring-boot-postgres/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/docker/docker-spring-boot-postgres/pom.xml b/docker/docker-spring-boot-postgres/pom.xml new file mode 100644 index 0000000000..f409ca7d92 --- /dev/null +++ b/docker/docker-spring-boot-postgres/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + com.baeldung.docker + spring-boot-postgres-docker + 0.0.1-SNAPSHOT + spring-boot-postgres-docker + Demo project showing Spring Boot, PostgreSQL, and Docker + + + 11 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/docker/docker-spring-boot-postgres/src/main/docker/Dockerfile b/docker/docker-spring-boot-postgres/src/main/docker/Dockerfile new file mode 100644 index 0000000000..a642876cbe --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/main/docker/Dockerfile @@ -0,0 +1,7 @@ +FROM adoptopenjdk:11-jre-hotspot +MAINTAINER baeldung.com + +ARG JAR_FILE=*.jar +COPY ${JAR_FILE} application.jar + +ENTRYPOINT ["java", "-jar", "application.jar"] \ No newline at end of file diff --git a/docker/docker-spring-boot-postgres/src/main/docker/docker-compose.yml b/docker/docker-spring-boot-postgres/src/main/docker/docker-compose.yml new file mode 100644 index 0000000000..93aa634205 --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/main/docker/docker-compose.yml @@ -0,0 +1,22 @@ +version: '2' + +services: + app: + image: 'docker-spring-boot-postgres:latest' + build: + context: . + container_name: app + depends_on: + - db + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/compose-postgres + - SPRING_DATASOURCE_USERNAME=compose-postgres + - SPRING_DATASOURCE_PASSWORD=compose-postgres + - SPRING_JPA_HIBERNATE_DDL_AUTO=update + + db: + image: 'postgres:13.1-alpine' + container_name: db + environment: + - POSTGRES_USER=compose-postgres + - POSTGRES_PASSWORD=compose-postgres \ No newline at end of file diff --git a/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/Customer.java b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/Customer.java new file mode 100644 index 0000000000..9369a84287 --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/Customer.java @@ -0,0 +1,57 @@ +package com.baeldung.docker; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customer") +public class Customer { + + @Id + @GeneratedValue + private long id; + + + @Column(name = "first_name", nullable = false) + private String firstName; + + @Column(name = "last_name", nullable = false) + private String lastName; + + public Customer() { + super(); + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/CustomerRepository.java b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/CustomerRepository.java new file mode 100644 index 0000000000..c959e00c89 --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/CustomerRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.docker; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CustomerRepository extends JpaRepository { + +} diff --git a/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/DemoApplication.java b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/DemoApplication.java new file mode 100644 index 0000000000..05377c6893 --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/main/java/com/baeldung/docker/DemoApplication.java @@ -0,0 +1,43 @@ +package com.baeldung.docker; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; + +@SpringBootApplication +public class DemoApplication { + private final Logger logger = LoggerFactory.getLogger(DemoApplication.class); + + @Autowired private CustomerRepository repository; + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + + @EventListener(ApplicationReadyEvent.class) + public void runAfterStartup() { + queryAllCustomers(); + createCustomer(); + queryAllCustomers(); + } + + private void createCustomer() { + Customer newCustomer = new Customer(); + newCustomer.setFirstName("John"); + newCustomer.setLastName("Doe"); + logger.info("Saving new customer..."); + this.repository.save(newCustomer); + } + + private void queryAllCustomers() { + List allCustomers = this.repository.findAll(); + logger.info("Number of customers: " + allCustomers.size()); + } + +} diff --git a/spring-security-modules/spring-security-kotlin-dsl/src/main/resources/application.properties b/docker/docker-spring-boot-postgres/src/main/resources/application.properties similarity index 100% rename from spring-security-modules/spring-security-kotlin-dsl/src/main/resources/application.properties rename to docker/docker-spring-boot-postgres/src/main/resources/application.properties diff --git a/docker/docker-spring-boot-postgres/src/test/java/com/baeldung/docker/DemoApplicationTests.java b/docker/docker-spring-boot-postgres/src/test/java/com/baeldung/docker/DemoApplicationTests.java new file mode 100644 index 0000000000..87bd1dd6ba --- /dev/null +++ b/docker/docker-spring-boot-postgres/src/test/java/com/baeldung/docker/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.baeldung.docker; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/jackson-modules/jackson/README.md b/jackson-modules/jackson/README.md index bcf8c3036f..50e13a5b75 100644 --- a/jackson-modules/jackson/README.md +++ b/jackson-modules/jackson/README.md @@ -10,6 +10,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Optional with Jackson](https://www.baeldung.com/jackson-optional) - [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects) - [Jackson vs Gson](https://www.baeldung.com/jackson-vs-gson) -- [Jackson JSON Tutorial](https://www.baeldung.com/jackson) - [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance) - [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) diff --git a/jee-kotlin/README.md b/jee-kotlin/README.md deleted file mode 100644 index e8975a7f62..0000000000 --- a/jee-kotlin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## JEE in Kotlin - -This module contains articles about Java EE with Kotlin. - -### Relevant Articles: -- [Jakarta EE Application with Kotlin](https://www.baeldung.com/java-ee-kotlin-app) diff --git a/jee-kotlin/pom.xml b/jee-kotlin/pom.xml deleted file mode 100644 index 45d5d8ece1..0000000000 --- a/jee-kotlin/pom.xml +++ /dev/null @@ -1,288 +0,0 @@ - - - 4.0.0 - jee-kotlin - jee-kotlin - war - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - org.jboss.arquillian - arquillian-bom - ${arquillian_core.version} - import - pom - - - org.jboss.arquillian.extension - arquillian-drone-bom - ${arquillian-drone-bom.version} - pom - import - - - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test-junit - ${kotlin.version} - test - - - junit - junit - ${junit.version} - test - - - javax - javaee-api - ${javaee-api.version} - jar - provided - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - test - - - org.jboss.arquillian.junit - arquillian-junit-container - ${arquillian_core.version} - test - - - org.jboss.shrinkwrap.resolver - shrinkwrap-resolver-depchain - ${shrinkwrap.version} - pom - test - - - org.jboss.arquillian.extension - arquillian-rest-client-impl-jersey - ${arquillian-rest-client.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - - - src/main/kotlin - src/test/kotlin - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - webapp - kotlin - - - - org.apache.maven.plugins - maven-compiler-plugin - - - default-compile - none - - - default-testCompile - none - - - compile - compile - - compile - - - - testCompile - test-compile - - testCompile - - - - - - - - - - wildfly-managed-arquillian - - true - - - - org.wildfly - wildfly-arquillian-container-embedded - ${wildfly.version} - - - org.wildfly - wildfly-embedded - ${wildfly.version} - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - ${maven-dependency-plugin.version} - - - unpack - process-test-classes - - unpack - - - - - org.wildfly - wildfly-dist - ${wildfly.version} - zip - false - target - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - always - - org.jboss.logmanager.LogManager - ${project.basedir}/target/wildfly-${wildfly.version} - 8756 - ${project.basedir}/target/wildfly-${wildfly.version}/modules - - false - - - - - - - wildfly-remote-arquillian-disabled - - - org.jboss.resteasy - resteasy-client - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-jaxb-provider - ${resteasy.version} - test - - - org.jboss.resteasy - resteasy-json-p-provider - ${resteasy.version} - test - - - org.wildfly.arquillian - wildfly-arquillian-container-remote - ${wildfly.arquillian.version} - test - - - - - - - 2.2.0.Final - UTF-8 - false - 8.0 - - 1.3.41 - official - true - - 8.2.1.Final - 2.21.0 - 3.1.1 - - 1.4.1.Final - 2.0.1.Final - 1.0.0.Alpha4 - - 1.1.7 - - 3.8.0.Final - 3.1.3 - - - diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt deleted file mode 100644 index 07f54a39d1..0000000000 --- a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/entity/Student.kt +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.jeekotlin.entity - -import com.fasterxml.jackson.annotation.JsonProperty -import javax.persistence.* - -@Entity -data class Student constructor ( - - @SequenceGenerator(name = "student_id_seq", sequenceName = "student_id_seq", allocationSize = 1) - @GeneratedValue(generator = "student_id_seq", strategy = GenerationType.SEQUENCE) - @Id - var id: Long?, - - var firstName: String, - - var lastName: String - -) { - constructor() : this(null, "", "") - - constructor(firstName: String, lastName: String) : this(null, firstName, lastName) -} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt deleted file mode 100644 index 12511ed320..0000000000 --- a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/ApplicationConfig.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.jeekotlin.rest - -import javax.ws.rs.ApplicationPath -import javax.ws.rs.core.Application - -@ApplicationPath("/") -class ApplicationConfig : Application() { - override fun getClasses() = setOf(StudentResource::class.java) -} diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt deleted file mode 100644 index 91fa3ff62b..0000000000 --- a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/rest/StudentResource.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.jeekotlin.rest - -import com.baeldung.jeekotlin.entity.Student -import com.baeldung.jeekotlin.service.StudentService -import javax.inject.Inject -import javax.ws.rs.* -import javax.ws.rs.core.MediaType -import javax.ws.rs.core.Response - -@Path("/student") -open class StudentResource { - - @Inject - private lateinit var service: StudentService - - @POST - open fun create(student: Student): Response { - service.create(student) - return Response.ok().build() - } - - @GET - @Path("/{id}") - open fun read(@PathParam("id") id: Long): Response { - val student = service.read(id) - return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() - } - - @PUT - open fun update(student: Student): Response { - service.update(student) - return Response.ok(student, MediaType.APPLICATION_JSON_TYPE).build() - } - - @DELETE - @Path("/{id}") - open fun delete(@PathParam("id") id: Long): Response { - service.delete(id) - return Response.noContent().build() - } - -} \ No newline at end of file diff --git a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt b/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt deleted file mode 100644 index 3977a45e96..0000000000 --- a/jee-kotlin/src/main/kotlin/com/baeldung/jeekotlin/service/StudentService.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.jeekotlin.service - -import com.baeldung.jeekotlin.entity.Student -import javax.ejb.Stateless -import javax.persistence.EntityManager -import javax.persistence.PersistenceContext - -@Stateless -open class StudentService { - - @PersistenceContext - private lateinit var entityManager: EntityManager - - open fun create(student: Student) = entityManager.persist(student) - - open fun read(id: Long): Student? = entityManager.find(Student::class.java, id) - - open fun update(student: Student) = entityManager.merge(student) - - open fun delete(id: Long) = entityManager.remove(read(id)) -} \ No newline at end of file diff --git a/jee-kotlin/src/main/resources/META-INF/persistence.xml b/jee-kotlin/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 0093792810..0000000000 --- a/jee-kotlin/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - - java:jboss/datasources/ExampleDS - - com.baeldung.jeekotlin.entity.Student - - - - - - - - diff --git a/jee-kotlin/src/main/webapp/WEB-INF/beans.xml b/jee-kotlin/src/main/webapp/WEB-INF/beans.xml deleted file mode 100644 index ae0f4bf2ee..0000000000 --- a/jee-kotlin/src/main/webapp/WEB-INF/beans.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - \ No newline at end of file diff --git a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java b/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java deleted file mode 100644 index d48a3a96da..0000000000 --- a/jee-kotlin/src/test/kotlin/com/baeldung/jeekotlin/StudentResourceIntegrationTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.baeldung.jeekotlin; - -import com.baeldung.jeekotlin.entity.Student; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.container.test.api.RunAsClient; -import org.jboss.arquillian.test.api.ArquillianResource; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.Filters; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.JavaArchive; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.maven.Maven; -import org.junit.Test; -import org.junit.runner.RunWith; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.URISyntaxException; -import java.net.URL; - -import static org.junit.Assert.assertEquals; - -@RunWith(Arquillian.class) -public class StudentResourceIntegrationTest { - - @Deployment - public static WebArchive createDeployment() { - JavaArchive[] kotlinRuntime = Maven.configureResolver() - .workOffline() - .withMavenCentralRepo(true) - .withClassPathResolution(true) - .loadPomFromFile("pom.xml") - .resolve("org.jetbrains.kotlin:kotlin-stdlib:1.3.41") - .withTransitivity() - .as(JavaArchive.class); - - return ShrinkWrap.create(WebArchive.class, "kotlin.war") - .addPackages(true, Filters.exclude(".*Test*"), - "com.baeldung.jeekotlin" - ) - .addAsLibraries(kotlinRuntime) - .addAsResource("META-INF/persistence.xml") - .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); - } - - @Test - @RunAsClient - public void when_post__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { - String student = new ObjectMapper().writeValueAsString(new Student("firstName", "lastName")); - WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); - - Response response = webTarget - .path("/student") - .request(MediaType.APPLICATION_JSON) - .post(Entity.json(student)); - - assertEquals(200, response.getStatus()); - } - - @Test - @RunAsClient - public void when_get__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { - WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); - - Response response = webTarget - .path("/student/1") - .request(MediaType.APPLICATION_JSON) - .get(); - - assertEquals(200, response.getStatus()); - } - - @Test - @RunAsClient - public void when_put__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { - Student student = new Student("firstName", "lastName"); - student.setId(1L); - String studentJson = new ObjectMapper().writeValueAsString(student); - WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); - - Response response = webTarget - .path("/student") - .request(MediaType.APPLICATION_JSON) - .put(Entity.json(studentJson)); - - assertEquals(200, response.getStatus()); - } - - @Test - @RunAsClient - public void when_delete__then_return_ok(@ArquillianResource URL url) throws URISyntaxException, JsonProcessingException { - WebTarget webTarget = ClientBuilder.newClient().target(url.toURI()); - - Response response = webTarget - .path("/student/1") - .request() - .delete(); - - assertEquals(204, response.getStatus()); - } - -} \ No newline at end of file diff --git a/jee-kotlin/src/test/resources/arquillian.xml b/jee-kotlin/src/test/resources/arquillian.xml deleted file mode 100644 index 5e6d7c54e8..0000000000 --- a/jee-kotlin/src/test/resources/arquillian.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - target/wildfly-8.2.1.Final - standalone.xml - true - 9990 - - - - - - 127.0.0.1 - 9990 - admin - pass - true - - - - \ No newline at end of file diff --git a/kotlin-js/.gitignore b/kotlin-js/.gitignore deleted file mode 100644 index 1db5e66882..0000000000 --- a/kotlin-js/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -/bin/ - -#ignore gradle -.gradle/ - - -#ignore build and generated files -build/ -node/ - -#ignore installed node modules and package lock file -node_modules/ -package-lock.json diff --git a/kotlin-js/README.md b/kotlin-js/README.md deleted file mode 100644 index 2ec50bad78..0000000000 --- a/kotlin-js/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## JavaScript in Kotlin - -This module contains articles about JavaScript in Kotlin. - -### Relevant Articles: - -- [Kotlin and Javascript](https://www.baeldung.com/kotlin-javascript) diff --git a/kotlin-js/build.gradle b/kotlin-js/build.gradle deleted file mode 100644 index ede6f51448..0000000000 --- a/kotlin-js/build.gradle +++ /dev/null @@ -1,27 +0,0 @@ -buildscript { - ext.kotlin_version = '1.4.10' - repositories { - mavenCentral() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -group 'com.baeldung' -version '1.0-SNAPSHOT' -apply plugin: 'kotlin2js' - -repositories { - mavenCentral() -} - -dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version" - testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version" -} - -compileKotlin2Js.kotlinOptions { - moduleKind = "commonjs" - outputFile = "node/crypto.js" -} diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.jar b/kotlin-js/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 490fda8577..0000000000 Binary files a/kotlin-js/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.properties b/kotlin-js/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index a4b4429748..0000000000 --- a/kotlin-js/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/kotlin-js/gradlew b/kotlin-js/gradlew deleted file mode 100755 index 2fe81a7d95..0000000000 --- a/kotlin-js/gradlew +++ /dev/null @@ -1,183 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/kotlin-js/gradlew.bat b/kotlin-js/gradlew.bat deleted file mode 100644 index 9109989e3c..0000000000 --- a/kotlin-js/gradlew.bat +++ /dev/null @@ -1,103 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/kotlin-js/package.json b/kotlin-js/package.json deleted file mode 100644 index 915b9d41ea..0000000000 --- a/kotlin-js/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "kotlin-node", - "version": "1.0.0", - "description": "Example of using NodeJS in Kotlin", - "main": "crypto.js", - "scripts": { - "start": "node node/crypto.js" - }, - "author": "", - "license": "ISC", - "dependencies": { - "express": "^4.17.1", - "kotlin": "^1.4.10" - } -} diff --git a/kotlin-js/settings.gradle b/kotlin-js/settings.gradle deleted file mode 100755 index 30c62d39ef..0000000000 --- a/kotlin-js/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'kotlin-node' diff --git a/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt b/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt deleted file mode 100755 index 92ef4a7356..0000000000 --- a/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.kotlinjs - -external fun require(module: String): dynamic - -data class CryptoCurrency(var name: String, var price: Float) - -fun main(args: Array) { - println("Crypto Currency price API!") - val express = require("express") - val app = express() - - app.get("/crypto", { _, res -> - res.send(generateCryptoRates()) - }) - - app.listen(3000, { - println("Listening on port 3000") - }) -} -fun generateCryptoRates(): Array{ - val cryptoCurrency = arrayOf( - CryptoCurrency("Bitcoin", 90000F), - CryptoCurrency("ETH",1000F), - CryptoCurrency("TRX",10F) - ); - return cryptoCurrency -} \ No newline at end of file diff --git a/kotlin-libraries-2/.gitignore b/kotlin-libraries-2/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/kotlin-libraries-2/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/bin/ - -#ignore gradle -.gradle/ - - -#ignore build and generated files -build/ -node/ -out/ - -#ignore installed node modules and package lock file -node_modules/ -package-lock.json diff --git a/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md deleted file mode 100644 index f725048acd..0000000000 --- a/kotlin-libraries-2/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Kotlin Libraries - -This module contains articles about Kotlin Libraries. - -### Relevant articles: - -- [Jackson Support for Kotlin](https://www.baeldung.com/jackson-kotlin) -- [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) -- [MockK: A Mocking Library for Kotlin](https://www.baeldung.com/kotlin-mockk) -- [Kotlin Immutable Collections](https://www.baeldung.com/kotlin-immutable-collections) -- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt) -- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) -- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) -- More articles: [[<-- prev]](/kotlin-libraries) diff --git a/kotlin-libraries-2/pom.xml b/kotlin-libraries-2/pom.xml deleted file mode 100644 index 254f2c6907..0000000000 --- a/kotlin-libraries-2/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - 4.0.0 - kotlin-libraries-2 - kotlin-libraries-2 - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - io.reactivex.rxjava2 - rxkotlin - ${rxkotlin.version} - - - junit - junit - test - - - com.google.guava - guava - ${guava.version} - - - - org.jetbrains.kotlinx - kotlinx-collections-immutable - ${kotlinx-collections-immutable.version} - - - uy.kohesive.injekt - injekt-core - ${injekt-core.version} - - - com.github.kittinunf.fuel - fuel - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-gson - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-rxjava - ${fuel.version} - - - com.github.kittinunf.fuel - fuel-coroutines - ${fuel.version} - - - nl.komponents.kovenant - kovenant - ${kovenant.version} - pom - - - - io.mockk - mockk - ${mockk.version} - test - - - - - 1.16.1 - 1.15.0 - 3.3.0 - 27.1-jre - 1.9.3 - 0.1 - 2.3.0 - - - diff --git a/kotlin-libraries-2/resources/logback.xml b/kotlin-libraries-2/resources/logback.xml deleted file mode 100644 index 9452207268..0000000000 --- a/kotlin-libraries-2/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - \ No newline at end of file diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt deleted file mode 100644 index 377ef979dc..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Interceptors.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.fuel - -import com.github.kittinunf.fuel.core.Request - -fun tokenInterceptor() = { - next: (Request) -> Request -> - { req: Request -> - req.header(mapOf("Authorization" to "Bearer AbCdEf123456")) - next(req) - } -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt deleted file mode 100644 index 035dfe7aa0..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/Post.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.fuel - -import com.github.kittinunf.fuel.core.ResponseDeserializable -import com.google.gson.Gson - -data class Post(var userId:Int, - var id:Int, - var title:String, - var body:String){ - - - class Deserializer : ResponseDeserializable> { - override fun deserialize(content: String): Array = Gson().fromJson(content, Array::class.java) - } -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt deleted file mode 100644 index 8238c41e56..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/fuel/PostRoutingAPI.kt +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.fuel - -import com.github.kittinunf.fuel.core.Method -import com.github.kittinunf.fuel.util.FuelRouting - -sealed class PostRoutingAPI : FuelRouting { - - override val basePath = "https://jsonplaceholder.typicode.com" - - class posts(val id: String, override val body: String?): PostRoutingAPI() - - class comments(val postId: String, override val body: String?): PostRoutingAPI() - - override val method: Method - get() { - return when(this) { - is PostRoutingAPI.posts -> Method.GET - is PostRoutingAPI.comments -> Method.GET - } - } - - override val path: String - get() { - return when(this) { - is PostRoutingAPI.posts -> "/posts" - is PostRoutingAPI.comments -> "/comments" - } - } - - override val params: List>? - get() { - return when(this) { - is PostRoutingAPI.posts -> listOf("id" to this.id) - is PostRoutingAPI.comments -> listOf("postId" to this.postId) - } - } - - override val headers: Map? - get() { - return null - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt deleted file mode 100644 index fb9beda621..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/DelegateInjectionApplication.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.injekt - -import org.slf4j.LoggerFactory -import uy.kohesive.injekt.* -import uy.kohesive.injekt.api.* -import java.util.* - -class DelegateInjectionApplication { - companion object : InjektMain() { - private val LOG = LoggerFactory.getLogger(DelegateInjectionApplication::class.java) - @JvmStatic fun main(args: Array) { - DelegateInjectionApplication().run() - } - - override fun InjektRegistrar.registerInjectables() { - addFactory { - val value = FactoryInstance("Factory" + UUID.randomUUID().toString()) - LOG.info("Constructing instance: {}", value) - value - } - - addSingletonFactory { - val value = SingletonInstance("Singleton" + UUID.randomUUID().toString()) - LOG.info("Constructing singleton instance: {}", value) - value - } - - addSingletonFactory { App() } - } - } - - data class FactoryInstance(val value: String) - data class SingletonInstance(val value: String) - - class App { - private val instance: FactoryInstance by injectValue() - private val lazyInstance: FactoryInstance by injectLazy() - private val singleton: SingletonInstance by injectValue() - private val lazySingleton: SingletonInstance by injectLazy() - - fun run() { - for (i in 1..5) { - LOG.info("Instance {}: {}", i, instance) - } - for (i in 1..5) { - LOG.info("Lazy Instance {}: {}", i, lazyInstance) - } - for (i in 1..5) { - LOG.info("Singleton {}: {}", i, singleton) - } - for (i in 1..5) { - LOG.info("Lazy Singleton {}: {}", i, lazySingleton) - } - } - } - - fun run() { - Injekt.get().run() - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt deleted file mode 100644 index 4205678981..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/KeyedApplication.kt +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.injekt - -import org.slf4j.LoggerFactory -import uy.kohesive.injekt.Injekt -import uy.kohesive.injekt.InjektMain -import uy.kohesive.injekt.api.InjektRegistrar -import uy.kohesive.injekt.api.addPerKeyFactory -import uy.kohesive.injekt.api.addSingletonFactory -import uy.kohesive.injekt.api.get - -class KeyedApplication { - companion object : InjektMain() { - private val LOG = LoggerFactory.getLogger(KeyedApplication::class.java) - @JvmStatic fun main(args: Array) { - KeyedApplication().run() - } - - override fun InjektRegistrar.registerInjectables() { - val configs = mapOf( - "google" to Config("googleClientId", "googleClientSecret"), - "twitter" to Config("twitterClientId", "twitterClientSecret") - ) - addPerKeyFactory {key -> configs[key]!! } - - addSingletonFactory { App() } - } - } - - data class Config(val clientId: String, val clientSecret: String) - - class App { - fun run() { - LOG.info("Google config: {}", Injekt.get("google")) - LOG.info("Twitter config: {}", Injekt.get("twitter")) - } - } - - fun run() { - Injekt.get().run() - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt deleted file mode 100644 index 96a0c9556a..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/ModularApplication.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.injekt - -import org.slf4j.LoggerFactory -import uy.kohesive.injekt.Injekt -import uy.kohesive.injekt.InjektMain -import uy.kohesive.injekt.api.* - -class ModularApplication { - class ConfigModule(private val port: Int) : InjektModule { - override fun InjektRegistrar.registerInjectables() { - addSingleton(Config(port)) - } - } - - object ServerModule : InjektModule { - override fun InjektRegistrar.registerInjectables() { - addSingletonFactory { Server(Injekt.get()) } - } - } - - companion object : InjektMain() { - private val LOG = LoggerFactory.getLogger(Server::class.java) - @JvmStatic fun main(args: Array) { - ModularApplication().run() - } - - override fun InjektRegistrar.registerInjectables() { - importModule(ConfigModule(12345)) - importModule(ServerModule) - } - } - - data class Config( - val port: Int - ) - - class Server(private val config: Config) { - - fun start() { - LOG.info("Starting server on ${config.port}") - } - } - - fun run() { - Injekt.get().start() - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt deleted file mode 100644 index f3167bc223..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/PerThreadApplication.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.injekt - -import org.slf4j.LoggerFactory -import uy.kohesive.injekt.Injekt -import uy.kohesive.injekt.InjektMain -import uy.kohesive.injekt.api.InjektRegistrar -import uy.kohesive.injekt.api.addPerThreadFactory -import uy.kohesive.injekt.api.addSingletonFactory -import uy.kohesive.injekt.api.get -import java.util.* -import java.util.concurrent.Executors -import java.util.concurrent.TimeUnit - -class PerThreadApplication { - companion object : InjektMain() { - private val LOG = LoggerFactory.getLogger(PerThreadApplication::class.java) - @JvmStatic fun main(args: Array) { - PerThreadApplication().run() - } - - override fun InjektRegistrar.registerInjectables() { - addPerThreadFactory { - val value = FactoryInstance(UUID.randomUUID().toString()) - LOG.info("Constructing instance: {}", value) - value - } - - addSingletonFactory { App() } - } - } - - data class FactoryInstance(val value: String) - - class App { - fun run() { - val threadPool = Executors.newFixedThreadPool(5) - - for (i in 1..20) { - threadPool.submit { - val instance = Injekt.get() - LOG.info("Value for thread {}: {}", Thread.currentThread().id, instance) - TimeUnit.MILLISECONDS.sleep(100) - } - } - threadPool.awaitTermination(10, TimeUnit.SECONDS) - } - } - - fun run() { - Injekt.get().run() - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt deleted file mode 100644 index 5c2dc28ba5..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/injekt/SimpleApplication.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.injekt - -import org.slf4j.LoggerFactory -import uy.kohesive.injekt.Injekt -import uy.kohesive.injekt.InjektMain -import uy.kohesive.injekt.api.InjektRegistrar -import uy.kohesive.injekt.api.addSingleton -import uy.kohesive.injekt.api.addSingletonFactory -import uy.kohesive.injekt.api.get - -class SimpleApplication { - companion object : InjektMain() { - private val LOG = LoggerFactory.getLogger(Server::class.java) - @JvmStatic fun main(args: Array) { - SimpleApplication().run() - } - - override fun InjektRegistrar.registerInjectables() { - addSingleton(Config(12345)) - addSingletonFactory { Server(Injekt.get()) } - } - } - - data class Config( - val port: Int - ) - - class Server(private val config: Config) { - - fun start() { - LOG.info("Starting server on ${config.port}") - } - } - - fun run() { - Injekt.get().start() - } -} diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Book.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Book.kt deleted file mode 100644 index 4ff47ea987..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Book.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.kotlin.jackson - -import com.fasterxml.jackson.annotation.* - -@JsonInclude(JsonInclude.Include.NON_EMPTY) -data class Book(var title: String, @JsonProperty("author") var authorName: String) { - var genres: List? = emptyList() -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Movie.kt b/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Movie.kt deleted file mode 100644 index 445b6013d5..0000000000 --- a/kotlin-libraries-2/src/main/kotlin/com/baeldung/kotlin/jackson/Movie.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.jackson - -data class Movie(var name: String, var studio: String, var rating: Float? = 1f) \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt deleted file mode 100644 index 69b6ae88c6..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/fuel/FuelHttpLiveTest.kt +++ /dev/null @@ -1,280 +0,0 @@ -package com.baeldung.fuel - -import com.github.kittinunf.fuel.Fuel -import com.github.kittinunf.fuel.core.FuelManager -import com.github.kittinunf.fuel.core.interceptors.cUrlLoggingRequestInterceptor -import com.github.kittinunf.fuel.gson.responseObject -import com.github.kittinunf.fuel.httpGet -import com.github.kittinunf.fuel.rx.rx_object -import com.google.gson.Gson -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Test -import java.io.File -import java.util.concurrent.CountDownLatch - -/** - * These live tests make connections to the external systems: http://httpbin.org, https://jsonplaceholder.typicode.com - * Make sure these hosts are up and your internet connection is on before running the tests. - */ -internal class FuelHttpLiveTest { - - @Test - fun whenMakingAsyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val latch = CountDownLatch(1) - - "http://httpbin.org/get".httpGet().response{ - request, response, result -> - - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - - latch.countDown() - } - - latch.await() - - } - - @Test - fun whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val (request, response, result) = "http://httpbin.org/get".httpGet().response() - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - - } - - @Test - fun whenMakingSyncHttpGetURLEncodedRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val (request, response, result) = - "https://jsonplaceholder.typicode.com/posts" - .httpGet(listOf("id" to "1")).response() - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - - } - - @Test - fun whenMakingAsyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val latch = CountDownLatch(1) - - Fuel.post("http://httpbin.org/post").response{ - request, response, result -> - - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - - latch.countDown() - } - - latch.await() - - } - - @Test - fun whenMakingSyncHttpPostRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val (request, response, result) = Fuel.post("http://httpbin.org/post").response() - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - } - - @Test - fun whenMakingSyncHttpPostRequestwithBody_thenResponseNotNullAndErrorNullAndStatusCode200() { - - val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") - .body("{ \"title\" : \"foo\",\"body\" : \"bar\",\"id\" : \"1\"}") - .response() - - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(201,response.statusCode) - } - - @Test - fun givenFuelInstance_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - FuelManager.instance.basePath = "http://httpbin.org" - FuelManager.instance.baseHeaders = mapOf("OS" to "macOS High Sierra") - - FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) - FuelManager.instance.addRequestInterceptor(tokenInterceptor()) - - - val (request, response, result) = "/get" - .httpGet().response() - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - } - - @Test - fun givenInterceptors_whenMakingSyncHttpGetRequest_thenResponseNotNullAndErrorNullAndStatusCode200() { - - FuelManager.instance.basePath = "http://httpbin.org" - FuelManager.instance.addRequestInterceptor(cUrlLoggingRequestInterceptor()) - FuelManager.instance.addRequestInterceptor(tokenInterceptor()) - - val (request, response, result) = "/get" - .httpGet().response() - val (data, error) = result - - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - } - - @Test - fun whenDownloadFile_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { - - Fuel.download("http://httpbin.org/bytes/32768").destination { response, url -> - File.createTempFile("temp", ".tmp") - }.response{ - request, response, result -> - - val (data, error) = result - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - } - } - - @Test - fun whenDownloadFilewithProgressHandler_thenCreateFileResponseNotNullAndErrorNullAndStatusCode200() { - - val (request, response, result) = Fuel.download("http://httpbin.org/bytes/327680") - .destination { response, url -> File.createTempFile("temp", ".tmp") - }.progress { readBytes, totalBytes -> - val progress = readBytes.toFloat() / totalBytes.toFloat() - }.response () - - val (data, error) = result - Assertions.assertNull(error) - Assertions.assertNotNull(data) - Assertions.assertEquals(200,response.statusCode) - - - } - - @Test - fun whenMakeGetRequest_thenDeserializePostwithGson() { - - val latch = CountDownLatch(1) - - "https://jsonplaceholder.typicode.com/posts/1".httpGet().responseObject { _,_, result -> - val post = result.component1() - Assertions.assertEquals(1, post?.userId) - latch.countDown() - } - - latch.await() - - } - - @Test - fun whenMakePOSTRequest_thenSerializePostwithGson() { - - val post = Post(1,1, "Lorem", "Lorem Ipse dolor sit amet") - - val (request, response, result) = Fuel.post("https://jsonplaceholder.typicode.com/posts") - .header("Content-Type" to "application/json") - .body(Gson().toJson(post).toString()) - .response() - - Assertions.assertEquals(201,response.statusCode) - - } - - @Test - fun whenMakeGETRequestWithRxJava_thenDeserializePostwithGson() { - - val latch = CountDownLatch(1) - - - "https://jsonplaceholder.typicode.com/posts?id=1" - .httpGet().rx_object(Post.Deserializer()).subscribe{ - res, throwable -> - - val post = res.component1() - Assertions.assertEquals(1, post?.get(0)?.userId) - latch.countDown() - } - - latch.await() - - } - - -// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library -// @Test -// fun whenMakeGETRequestUsingCoroutines_thenResponseStatusCode200() = runBlocking { -// val (request, response, result) = Fuel.get("http://httpbin.org/get").awaitStringResponse() -// -// result.fold({ data -> -// Assertions.assertEquals(200, response.statusCode) -// -// }, { error -> }) -// } - -// The new 1.3 coroutine APIs, aren't implemented yet in Fuel Library -// @Test -// fun whenMakeGETRequestUsingCoroutines_thenDeserializeResponse() = runBlocking { -// Fuel.get("https://jsonplaceholder.typicode.com/posts?id=1").awaitObjectResult(Post.Deserializer()) -// .fold({ data -> -// Assertions.assertEquals(1, data.get(0).userId) -// }, { error -> }) -// } - - @Test - fun whenMakeGETPostRequestUsingRoutingAPI_thenDeserializeResponse() { - - val latch = CountDownLatch(1) - - Fuel.request(PostRoutingAPI.posts("1",null)) - .responseObject(Post.Deserializer()) { - request, response, result -> - Assertions.assertEquals(1, result.component1()?.get(0)?.userId) - latch.countDown() - } - - latch.await() - } - - @Test - fun whenMakeGETCommentRequestUsingRoutingAPI_thenResponseStausCode200() { - - val latch = CountDownLatch(1) - - Fuel.request(PostRoutingAPI.comments("1",null)) - .responseString { request, response, result -> - Assertions.assertEquals(200, response.statusCode) - latch.countDown() - } - - latch.await() - } - - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt deleted file mode 100644 index 9159be96be..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/gson/GsonUnitTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.gson - -import com.google.gson.Gson - -import org.junit.Assert -import org.junit.Test - -class GsonUnitTest { - - var gson = Gson() - - @Test - fun givenObject_thenGetJSONString() { - var jsonString = gson.toJson(TestModel(1, "Test")) - Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}") - } - - @Test - fun givenJSONString_thenGetObject() { - var jsonString = "{\"id\":1,\"description\":\"Test\"}"; - var testModel = gson.fromJson(jsonString, TestModel::class.java) - Assert.assertEquals(testModel.id, 1) - Assert.assertEquals(testModel.description, "Test") - } - - data class TestModel( - val id: Int, - val description: String - ) -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt deleted file mode 100644 index 971f2de4c2..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/KotlinxImmutablesUnitTest.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.kotlin.immutable - -import junit.framework.Assert.assertEquals -import kotlinx.collections.immutable.ImmutableList -import kotlinx.collections.immutable.immutableListOf -import org.junit.Rule -import org.junit.Test -import org.junit.rules.ExpectedException - -class KotlinxImmutablesUnitTest{ - - - @Rule - @JvmField - var ee : ExpectedException = ExpectedException.none() - - @Test - fun givenKICLList_whenAddTried_checkExceptionThrown(){ - - val list: ImmutableList = immutableListOf("I", "am", "immutable") - - list.add("My new item") - - assertEquals(listOf("I", "am", "immutable"), list) - - } -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt deleted file mode 100644 index 62c4a4eb88..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/immutable/ReadOnlyUnitTest.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.kotlin.immutable - -import com.google.common.collect.ImmutableList -import com.google.common.collect.ImmutableSet -import junit.framework.Assert.assertEquals -import org.junit.Rule -import org.junit.Test -import org.junit.rules.ExpectedException - -class ReadOnlyUnitTest{ - - @Test - fun givenReadOnlyList_whenCastToMutableList_checkNewElementsAdded(){ - - val list: List = listOf("This", "Is", "Totally", "Immutable") - - (list as MutableList)[2] = "Not" - - assertEquals(listOf("This", "Is", "Not", "Immutable"), list) - - } - - @Rule - @JvmField - var ee : ExpectedException = ExpectedException.none() - - @Test - fun givenImmutableList_whenAddTried_checkExceptionThrown(){ - - val list: List = ImmutableList.of("I", "am", "actually", "immutable") - - ee.expect(UnsupportedOperationException::class.java) - - (list as MutableList).add("Oops") - - } - - @Test - fun givenMutableList_whenCopiedAndAddTried_checkExceptionThrown(){ - - val mutableList : List = listOf("I", "Am", "Definitely", "Immutable") - - (mutableList as MutableList)[2] = "100% Not" - - assertEquals(listOf("I", "Am", "100% Not", "Immutable"), mutableList) - - val list: List = ImmutableList.copyOf(mutableList) - - ee.expect(UnsupportedOperationException::class.java) - - (list as MutableList)[2] = "Really?" - - } - - @Test - fun givenImmutableSetBuilder_whenAddTried_checkExceptionThrown(){ - - val mutableList : List = listOf("Hello", "Baeldung") - val set: ImmutableSet = ImmutableSet.builder() - .add("I","am","immutable") - .addAll(mutableList) - .build() - - assertEquals(setOf("Hello", "Baeldung", "I", "am", "immutable"), set) - - ee.expect(UnsupportedOperationException::class.java) - - (set as MutableSet).add("Oops") - - } - - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt deleted file mode 100644 index 0c72edc2fd..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt +++ /dev/null @@ -1,122 +0,0 @@ -package com.baeldung.kotlin.jackson - -import org.junit.Test -import kotlin.test.assertTrue -import kotlin.test.assertFalse -import kotlin.test.assertEquals -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.module.kotlin.KotlinModule - -class JacksonUnitTest { - //val mapper = jacksonObjectMapper() - val mapper = ObjectMapper().registerModule(KotlinModule()) - - - @Test - fun whenSerializeMovie_thenSuccess() { - val movie = Movie("Endgame", "Marvel", 9.2f) - val serialized = mapper.writeValueAsString(movie) - - val json = """{"name":"Endgame","studio":"Marvel","rating":9.2}""" - assertEquals(serialized, json) - } - - @Test - fun whenDeserializeMovie_thenSuccess() { - val json = """{"name":"Endgame","studio":"Marvel","rating":9.2}""" - // val movie: Movie = mapper.readValue(json) - val movie = mapper.readValue(json) - - assertEquals(movie.name, "Endgame") - assertEquals(movie.studio, "Marvel") - assertEquals(movie.rating, 9.2f) - } - - @Test - fun whenDeserializeMovieWithMissingValue_thenUseDefaultValue() { - val json = """{"name":"Endgame","studio":"Marvel"}""" - val movie: Movie = mapper.readValue(json) - - assertEquals(movie.name, "Endgame") - assertEquals(movie.studio, "Marvel") - assertEquals(movie.rating, 1f) - } - - @Test - fun whenSerializeMap_thenSuccess() { - val map = mapOf(1 to "one", 2 to "two") - val serialized = mapper.writeValueAsString(map) - - val json = """{"1":"one","2":"two"}""" - assertEquals(serialized, json) - } - - @Test - fun whenDeserializeMap_thenSuccess() { - val json = """{"1":"one","2":"two"}""" - val aMap: Map = mapper.readValue(json) - - assertEquals(aMap[1], "one") - assertEquals(aMap[2], "two") - - val sameMap = mapper.readValue>(json) - assertEquals(sameMap[1], "one") - assertEquals(sameMap[2], "two") - } - - @Test - fun whenSerializeList_thenSuccess() { - val movie1 = Movie("Endgame", "Marvel", 9.2f) - val movie2 = Movie("Shazam", "Warner Bros", 7.6f) - val movieList = listOf(movie1, movie2) - val serialized = mapper.writeValueAsString(movieList) - - val json = """[{"name":"Endgame","studio":"Marvel","rating":9.2},{"name":"Shazam","studio":"Warner Bros","rating":7.6}]""" - assertEquals(serialized, json) - } - - @Test - fun whenDeserializeList_thenSuccess() { - val json = """[{"name":"Endgame","studio":"Marvel","rating":9.2},{"name":"Shazam","studio":"Warner Bros","rating":7.6}]""" - val movieList: List = mapper.readValue(json) - - val movie1 = Movie("Endgame", "Marvel", 9.2f) - val movie2 = Movie("Shazam", "Warner Bros", 7.6f) - assertTrue(movieList.contains(movie1)) - assertTrue(movieList.contains(movie2)) - - val sameList = mapper.readValue>(json) - assertTrue(sameList.contains(movie1)) - assertTrue(sameList.contains(movie2)) - } - - @Test - fun whenSerializeBook_thenSuccess() { - val book = Book("Oliver Twist", "Charles Dickens") - val serialized = mapper.writeValueAsString(book) - - val json = """{"title":"Oliver Twist","author":"Charles Dickens"}""" - assertEquals(serialized, json) - } - - @Test - fun whenDeserializeBook_thenSuccess() { - val json = """{"title":"Oliver Twist","author":"Charles Dickens"}""" - val book: Book = mapper.readValue(json) - - assertEquals(book.title, "Oliver Twist") - assertEquals(book.authorName, "Charles Dickens") - } - - @Test - fun givenJsonInclude_whenSerializeBook_thenEmptyFieldExcluded() { - val book = Book("Oliver Twist", "Charles Dickens") - val serialized = mapper.writeValueAsString(book) - - val json = """{"title":"Oliver Twist","author":"Charles Dickens"}""" - assertEquals(serialized, json) - } - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt deleted file mode 100644 index 979ed3f809..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.kotlin.rxkotlin - -import io.reactivex.Maybe -import io.reactivex.Observable -import io.reactivex.functions.BiFunction -import io.reactivex.rxkotlin.* -import io.reactivex.subjects.PublishSubject -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse - -class RxKotlinTest { - - @Test - fun whenBooleanArrayToObserver_thenBooleanObserver() { - val observable = listOf(true, false, false).toObservable() - observable.test().assertValues(true, false, false) - } - - @Test - fun whenBooleanArrayToFlowable_thenBooleanFlowable() { - val flowable = listOf(true, false, false).toFlowable() - flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false)) - } - - @Test - fun whenIntArrayToObserver_thenIntObserver() { - val observable = listOf(1, 1, 2, 3).toObservable() - observable.test().assertValues(1, 1, 2, 3) - } - - @Test - fun whenIntArrayToFlowable_thenIntFlowable() { - val flowable = listOf(1, 1, 2, 3).toFlowable() - flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3)) - } - - @Test - fun whenObservablePairToMap_thenSingleNoDuplicates() { - val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4)) - val observable = list.toObservable() - val map = observable.toMap() - assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet()) - } - - @Test - fun whenObservablePairToMap_thenSingleWithDuplicates() { - val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4)) - val observable = list.toObservable() - val map = observable.toMultimap() - assertEquals( - mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))), - map.blockingGet()) - } - - @Test - fun whenMergeAll_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.mergeAll() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenConcatAll_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.concatAll() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenSwitchLatest_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.switchLatest() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenMergeAllMaybes_thenObservable() { - val subject = PublishSubject.create>() - val observable = subject.mergeAllMaybes() - val testObserver = observable.test() - subject.onNext(Maybe.just(1)) - subject.onNext(Maybe.just(2)) - subject.onNext(Maybe.empty()) - testObserver.assertValues(1, 2) - subject.onNext(Maybe.error(Exception(""))) - subject.onNext(Maybe.just(3)) - testObserver.assertValues(1, 2).assertError(Exception::class.java) - } - - @Test - fun whenMerge_thenStream() { - val observables = mutableListOf(Observable.just("first", "second")) - val observable = observables.merge() - observables.add(Observable.just("third", "fourth")) - observables.add(Observable.error(Exception("e"))) - observables.add(Observable.just("fifth")) - - observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java) - } - - @Test - fun whenMergeDelayError_thenStream() { - val observables = mutableListOf>(Observable.error(Exception("e1"))) - val observable = observables.mergeDelayError() - observables.add(Observable.just("1", "2")) - observables.add(Observable.error(Exception("e2"))) - observables.add(Observable.just("3")) - - observable.test().assertValues("1", "2", "3").assertError(Exception::class.java) - } - - @Test - fun whenCast_thenUniformType() { - val observable = Observable.just(1, 1, 2, 3) - observable.cast().test().assertValues(1, 1, 2, 3) - } - - @Test - fun whenOfType_thenFilter() { - val observable = Observable.just(1, "and", 2, "and") - observable.ofType().test().assertValues(1, 2) - } - - @Test - fun whenFunction_thenCompletable() { - var value = 0 - val completable = { value = 3 }.toCompletable() - assertFalse(completable.test().isCancelled) - assertEquals(3, value) - } - - @Test - fun whenHelper_thenMoreIdiomaticKotlin() { - val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b } - zipWith.subscribeBy(onNext = { println(it) }) - val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b } - zip.subscribeBy(onNext = { println(it) }) - val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction { a, b -> a + b }) - zipOrig.subscribeBy(onNext = { println(it) }) - } -} diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt deleted file mode 100644 index 046b7380f7..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTest.kt +++ /dev/null @@ -1,192 +0,0 @@ -package com.baeldung.kovenant - -import nl.komponents.kovenant.* -import nl.komponents.kovenant.Kovenant.deferred -import nl.komponents.kovenant.combine.and -import nl.komponents.kovenant.combine.combine -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import java.io.IOException -import java.util.* -import java.util.concurrent.TimeUnit - -class KovenantTest { - - @Before - fun setupTestMode() { - Kovenant.testMode { error -> - println("An unexpected error occurred") - Assert.fail(error.message) - } - } - - @Test - fun testSuccessfulDeferred() { - val def = deferred() - Assert.assertFalse(def.promise.isDone()) - - def.resolve(1L) - Assert.assertTrue(def.promise.isDone()) - Assert.assertTrue(def.promise.isSuccess()) - Assert.assertFalse(def.promise.isFailure()) - } - - @Test - fun testFailedDeferred() { - val def = deferred() - Assert.assertFalse(def.promise.isDone()) - - def.reject(RuntimeException()) - Assert.assertTrue(def.promise.isDone()) - Assert.assertFalse(def.promise.isSuccess()) - Assert.assertTrue(def.promise.isFailure()) - } - - @Test - fun testResolveDeferredTwice() { - val def = deferred() - def.resolve(1L) - try { - def.resolve(1L) - } catch (e: AssertionError) { - // Expected. - // This is slightly unusual. The AssertionError comes from Assert.fail() from setupTestMode() - } - } - - @Test - fun testSuccessfulTask() { - val promise = task { 1L } - Assert.assertTrue(promise.isDone()) - Assert.assertTrue(promise.isSuccess()) - Assert.assertFalse(promise.isFailure()) - } - - @Test - fun testFailedTask() { - val promise = task { throw RuntimeException() } - Assert.assertTrue(promise.isDone()) - Assert.assertFalse(promise.isSuccess()) - Assert.assertTrue(promise.isFailure()) - } - - @Test - fun testCallbacks() { - val promise = task { 1L } - - promise.success { - println("This was a success") - Assert.assertEquals(1L, it) - } - - promise.fail { - println(it) - Assert.fail("This shouldn't happen") - } - - promise.always { - println("This always happens") - } - } - - @Test - fun testGetValues() { - val promise = task { 1L } - Assert.assertEquals(1L, promise.get()) - } - - @Test - fun testAllSucceed() { - val numbers = all( - task { 1L }, - task { 2L }, - task { 3L } - ) - - Assert.assertEquals(listOf(1L, 2L, 3L), numbers.get()) - } - - @Test - fun testOneFails() { - val runtimeException = RuntimeException() - - val numbers = all( - task { 1L }, - task { 2L }, - task { throw runtimeException } - ) - - Assert.assertEquals(runtimeException, numbers.getError()) - } - - @Test - fun testAnySucceeds() { - val promise = any( - task { - TimeUnit.SECONDS.sleep(3) - 1L - }, - task { - TimeUnit.SECONDS.sleep(2) - 2L - }, - task { - TimeUnit.SECONDS.sleep(1) - 3L - } - ) - - Assert.assertTrue(promise.isDone()) - Assert.assertTrue(promise.isSuccess()) - Assert.assertFalse(promise.isFailure()) - } - - @Test - fun testAllFails() { - val runtimeException = RuntimeException() - val ioException = IOException() - val illegalStateException = IllegalStateException() - val promise = any( - task { - TimeUnit.SECONDS.sleep(3) - throw runtimeException - }, - task { - TimeUnit.SECONDS.sleep(2) - throw ioException - }, - task { - TimeUnit.SECONDS.sleep(1) - throw illegalStateException - } - ) - - Assert.assertTrue(promise.isDone()) - Assert.assertFalse(promise.isSuccess()) - Assert.assertTrue(promise.isFailure()) - } - - @Test - fun testSimpleCombine() { - val promise = task { 1L } and task { "Hello" } - val result = promise.get() - - Assert.assertEquals(1L, result.first) - Assert.assertEquals("Hello", result.second) - } - - @Test - fun testLongerCombine() { - val promise = combine( - task { 1L }, - task { "Hello" }, - task { Currency.getInstance("USD") } - ) - val result = promise.get() - - Assert.assertEquals(1L, result.first) - Assert.assertEquals("Hello", result.second) - Assert.assertEquals(Currency.getInstance("USD"), result.third) - } -} diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt deleted file mode 100644 index d98f9c538f..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kovenant/KovenantTimeoutTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.kovenant - -import nl.komponents.kovenant.Promise -import nl.komponents.kovenant.any -import nl.komponents.kovenant.task -import org.junit.Assert -import org.junit.Ignore -import org.junit.Test - -@Ignore -// Note that this can not run in the same test run if KovenantTest has already been executed -class KovenantTimeoutTest { - @Test - fun testTimeout() { - val promise = timedTask(1000) { "Hello" } - val result = promise.get() - Assert.assertEquals("Hello", result) - } - - @Test - fun testTimeoutExpired() { - val promise = timedTask(1000) { - Thread.sleep(3000) - "Hello" - } - val result = promise.get() - Assert.assertNull(result) - } - - fun timedTask(millis: Long, body: () -> T) : Promise> { - val timeoutTask = task { - Thread.sleep(millis) - null - } - val activeTask = task(body = body) - return any(activeTask, timeoutTask) - } -} diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt deleted file mode 100644 index 56cd8b43eb..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/AnnotationMockKUnitTest.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.mockk - -import io.mockk.MockKAnnotations -import io.mockk.every -import io.mockk.impl.annotations.InjectMockKs -import io.mockk.impl.annotations.MockK -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class InjectTestService { - lateinit var service1: TestableService - lateinit var service2: TestableService - - fun invokeService1(): String { - return service1.getDataFromDb("Test Param") - } -} - -class AnnotationMockKUnitTest { - - @MockK - lateinit var service1: TestableService - - @MockK - lateinit var service2: TestableService - - @InjectMockKs - var objectUnderTest = InjectTestService() - - @BeforeEach - fun setUp() = MockKAnnotations.init(this) - - @Test - fun givenServiceMock_whenCallingMockedMethod_thenCorrectlyVerified() { - // given - every { service1.getDataFromDb("Test Param") } returns "No" - // when - val result = objectUnderTest.invokeService1() - // then - assertEquals("No", result) - } - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt deleted file mode 100644 index df4c03be09..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/BasicMockKUnitTest.kt +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.mockk - -import io.mockk.* -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - - -class BasicMockKUnitTest { - - @Test - fun givenServiceMock_whenCallingMockedMethod_thenCorrectlyVerified() { - // given - val service = mockk() - every { service.getDataFromDb("Expected Param") } returns "Expected Output" - // when - val result = service.getDataFromDb("Expected Param") - // then - verify { service.getDataFromDb("Expected Param") } - assertEquals("Expected Output", result) - } - - @Test - fun givenServiceSpy_whenMockingOnlyOneMethod_thenOtherMethodsShouldBehaveAsOriginalObject() { - // given - val service = spyk() - every { service.getDataFromDb(any()) } returns "Mocked Output" - // when checking mocked method - val firstResult = service.getDataFromDb("Any Param") - // then - assertEquals("Mocked Output", firstResult) - // when checking not mocked method - val secondResult = service.doSomethingElse("Any Param") - // then - assertEquals("I don't want to!", secondResult) - } - - @Test - fun givenRelaxedMock_whenCallingNotMockedMethod_thenReturnDefaultValue() { - // given - val service = mockk(relaxed = true) - // when - val result = service.getDataFromDb("Any Param") - // then - assertEquals("", result) - } - - @Test - fun givenObject_whenMockingIt_thenMockedMethodShouldReturnProperValue() { - // given - val service = TestableService() - mockkObject(service) - // when calling not mocked method - val firstResult = service.getDataFromDb("Any Param") - // then return real response - assertEquals("Value from DB", firstResult) - - // when calling mocked method - every { service.getDataFromDb(any()) } returns "Mocked Output" - val secondResult = service.getDataFromDb("Any Param") - // then return mocked response - assertEquals("Mocked Output", secondResult) - } - - @Test - fun givenMock_whenCapturingParamValue_thenProperValueShouldBeCaptured() { - // given - val service = mockk() - val slot = slot() - every { service.getDataFromDb(capture(slot)) } returns "Expected Output" - // when - service.getDataFromDb("Expected Param") - // then - assertEquals("Expected Param", slot.captured) - } - - @Test - fun givenMock_whenCapturingParamsValues_thenProperValuesShouldBeCaptured() { - // given - val service = mockk() - val list = mutableListOf() - every { service.getDataFromDb(capture(list)) } returns "Expected Output" - // when - service.getDataFromDb("Expected Param 1") - service.getDataFromDb("Expected Param 2") - // then - assertEquals(2, list.size) - assertEquals("Expected Param 1", list[0]) - assertEquals("Expected Param 2", list[1]) - } - - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt deleted file mode 100644 index e9ef133663..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/HierarchicalMockKUnitTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.mockk - -import io.mockk.* -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -class Foo { - lateinit var name: String - lateinit var bar: Bar -} - -class Bar { - lateinit var nickname: String -} - -class HierarchicalMockKUnitTest { - - @Test - fun givenHierarchicalClass_whenMockingIt_thenReturnProperValue() { - // given - val foo = mockk { - every { name } returns "Karol" - every { bar } returns mockk { - every { nickname } returns "Tomato" - } - } - // when - val result = foo.bar.nickname - // then - assertEquals("Tomato", result) - } - -} \ No newline at end of file diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/TestableService.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/TestableService.kt deleted file mode 100644 index d6f57e5fb0..0000000000 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/mockk/TestableService.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.mockk - -class TestableService { - fun getDataFromDb(testParameter: String): String { - // query database and return matching value - return "Value from DB" - } - - fun doSomethingElse(testParameter: String): String { - return "I don't want to!" - } -} \ No newline at end of file diff --git a/kotlin-libraries/.gitignore b/kotlin-libraries/.gitignore deleted file mode 100644 index 0c017e8f8c..0000000000 --- a/kotlin-libraries/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -/bin/ - -#ignore gradle -.gradle/ - - -#ignore build and generated files -build/ -node/ -out/ - -#ignore installed node modules and package lock file -node_modules/ -package-lock.json diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md deleted file mode 100644 index 570bf9b1e5..0000000000 --- a/kotlin-libraries/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Kotlin Libraries - -This module contains articles about Kotlin Libraries. - -### Relevant articles: - -- [Kotlin with Mockito](https://www.baeldung.com/kotlin-mockito) -- [HTTP Requests with Kotlin and khttp](https://www.baeldung.com/kotlin-khttp) -- [Kotlin Dependency Injection with Kodein](https://www.baeldung.com/kotlin-kodein-dependency-injection) -- [Writing Specifications with Kotlin and Spek](https://www.baeldung.com/kotlin-spek) -- [Processing JSON with Kotlin and Klaxson](https://www.baeldung.com/kotlin-json-klaxson) -- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence) -- [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow) -- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) -- [REST API With Kotlin and Kovert](https://www.baeldung.com/kotlin-kovert) -- More articles: [[next -->]](/kotlin-libraries-2) diff --git a/kotlin-libraries/build.gradle b/kotlin-libraries/build.gradle deleted file mode 100644 index db23a438a0..0000000000 --- a/kotlin-libraries/build.gradle +++ /dev/null @@ -1,62 +0,0 @@ - - -group 'com.baeldung.ktor' -version '1.0-SNAPSHOT' - - -buildscript { - ext.kotlin_version = '1.2.41' - ext.ktor_version = '0.9.2' - ext.khttp_version = '0.1.0' - - repositories { - mavenCentral() - } - dependencies { - - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -apply plugin: 'java' -apply plugin: 'kotlin' -apply plugin: 'application' - -mainClassName = 'APIServer.kt' - -sourceCompatibility = 1.8 -compileKotlin { kotlinOptions.jvmTarget = "1.8" } -compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } - -kotlin { experimental { coroutines "enable" } } - -repositories { - mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/kotlin/ktor" } -} -sourceSets { - main{ - kotlin{ - srcDirs 'com/baeldung/ktor' - } - } - -} - -dependencies { - compile "io.ktor:ktor-server-netty:$ktor_version" - compile "ch.qos.logback:logback-classic:1.2.1" - compile "io.ktor:ktor-gson:$ktor_version" - compile "khttp:khttp:$khttp_version" - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.jetbrains.spek', name: 'spek-api', version: '1.1.5' - testCompile group: 'org.jetbrains.spek', name: 'spek-subject-extension', version: '1.1.5' - testCompile group: 'org.jetbrains.spek', name: 'spek-junit-platform-engine', version: '1.1.5' - implementation 'com.beust:klaxon:3.0.1' -} - -task runServer(type: JavaExec) { - main = 'APIServer' - classpath = sourceSets.main.runtimeClasspath -} diff --git a/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar b/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 01b8bf6b1f..0000000000 Binary files a/kotlin-libraries/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties b/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 933b6473ce..0000000000 --- a/kotlin-libraries/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/kotlin-libraries/gradlew b/kotlin-libraries/gradlew deleted file mode 100644 index cccdd3d517..0000000000 --- a/kotlin-libraries/gradlew +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env sh - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/kotlin-libraries/gradlew.bat b/kotlin-libraries/gradlew.bat deleted file mode 100644 index f9553162f1..0000000000 --- a/kotlin-libraries/gradlew.bat +++ /dev/null @@ -1,84 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml deleted file mode 100644 index 908a545ae3..0000000000 --- a/kotlin-libraries/pom.xml +++ /dev/null @@ -1,171 +0,0 @@ - - - 4.0.0 - kotlin-libraries - kotlin-libraries - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - exposed - exposed - https://dl.bintray.com/kotlin/exposed - - - - false - - kotlinx - bintray - https://dl.bintray.com/kotlin/kotlinx - - - - - - org.jetbrains.spek - spek-api - ${spek.version} - test - - - org.jetbrains.spek - spek-subject-extension - ${spek.version} - test - - - org.jetbrains.spek - spek-junit-platform-engine - ${spek.version} - test - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - org.junit.platform - junit-platform-runner - test - - - khttp - khttp - ${khttp.version} - - - com.nhaarman - mockito-kotlin - ${mockito-kotlin.version} - test - - - com.github.salomonbrys.kodein - kodein - ${kodein.version} - - - org.assertj - assertj-core - test - - - com.beust - klaxon - ${klaxon.version} - - - org.jetbrains.exposed - exposed - ${exposed.version} - - - com.h2database - h2 - - - - io.arrow-kt - arrow-core - ${arrow-core.version} - - - - uy.kohesive.kovert - kovert-vertx - [1.5.0,1.6.0) - - - nl.komponents.kovenant - kovenant - - - - - nl.komponents.kovenant - kovenant - ${kovenant.version} - pom - - - - - junit - junit - test - - - - - net.bytebuddy - byte-buddy - compile - - - net.bytebuddy - byte-buddy-agent - compile - - - org.objenesis - objenesis - ${objenesis.version} - compile - - - - io.reactivex.rxjava2 - rxkotlin - ${rxkotlin.version} - - - - - 1.5.0 - 4.1.0 - 3.0.4 - 0.1.0 - 3.6.1 - 1.1.1 - 5.2.0 - 3.10.0 - 0.10.4 - 3.3.0 - 1.8.13 - 2.6 - 2.3.0 - 0.7.3 - 1.1.5 - - - diff --git a/kotlin-libraries/resources/logback.xml b/kotlin-libraries/resources/logback.xml deleted file mode 100644 index 9452207268..0000000000 --- a/kotlin-libraries/resources/logback.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - \ No newline at end of file diff --git a/kotlin-libraries/settings.gradle b/kotlin-libraries/settings.gradle deleted file mode 100644 index c91c993971..0000000000 --- a/kotlin-libraries/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'KtorWithKotlin' - diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt deleted file mode 100644 index cc46c65f96..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.klaxon - -import com.beust.klaxon.Json - -class CustomProduct( - @Json(name = "productName") - val name: String, - @Json(ignored = true) - val id: Int) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt deleted file mode 100644 index 09bcbc8722..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/Product.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.klaxon - -class Product(val name: String) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt deleted file mode 100644 index 1f30f26ce9..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/klaxon/ProductData.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.klaxon - -data class ProductData(val name: String, val capacityInGb: Int) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt deleted file mode 100644 index 75dfb9a2a4..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.kotlin.arrow - -import arrow.core.Either -import arrow.core.filterOrElse -import kotlin.math.sqrt - -class FunctionalErrorHandlingWithEither { - - sealed class ComputeProblem { - object OddNumber : ComputeProblem() - object NotANumber : ComputeProblem() - } - - fun parseInput(s : String) : Either = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} ) - - fun isEven(x : Int) : Boolean = x % 2 == 0 - - fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2) - - fun biggestDivisor(x : Int, y : Int) : Int { - if(x == y){ - return 1; - } - if(x % y == 0){ - return x / y; - } - return biggestDivisor(x, y+1) - } - - fun isSquareNumber(x : Int) : Boolean { - val sqrt: Double = sqrt(x.toDouble()) - return sqrt % 1.0 == 0.0 - } - - fun computeWithEither(input : String) : Either { - return parseInput(input) - .filterOrElse(::isEven) {->ComputeProblem.OddNumber} - .map (::biggestDivisor) - .map (::isSquareNumber) - } - - fun computeWithEitherClient(input : String) { - val computeWithEither = computeWithEither(input) - - when(computeWithEither){ - is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}" - is Either.Left -> when(computeWithEither.a){ - is ComputeProblem.NotANumber -> "Wrong input! Not a number!" - is ComputeProblem.OddNumber -> "It is an odd number!" - } - } - } - -} \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt deleted file mode 100644 index 5fddd1d88e..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.kotlin.arrow - -import arrow.core.None -import arrow.core.Option -import arrow.core.Some -import kotlin.math.sqrt - -class FunctionalErrorHandlingWithOption { - - fun parseInput(s : String) : Option = Option.fromNullable(s.toIntOrNull()) - - fun isEven(x : Int) : Boolean = x % 2 == 0 - - fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2) - - fun biggestDivisor(x : Int, y : Int) : Int { - if(x == y){ - return 1; - } - if(x % y == 0){ - return x / y; - } - return biggestDivisor(x, y+1) - } - - fun isSquareNumber(x : Int) : Boolean { - val sqrt: Double = sqrt(x.toDouble()) - return sqrt % 1.0 == 0.0 - } - - fun computeWithOption(input : String) : Option { - return parseInput(input) - .filter(::isEven) - .map(::biggestDivisor) - .map(::isSquareNumber) - } - - fun computeWithOptionClient(input : String) : String{ - val computeOption = computeWithOption(input) - - return when(computeOption){ - is None -> "Not an even number!" - is Some -> "The greatest divisor is square number: ${computeOption.t}" - } - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt deleted file mode 100644 index 721bdb04bc..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Controller.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.kodein - -class Controller(private val service : Service) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt deleted file mode 100644 index a0be7ef0e0..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Dao.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.kodein - -interface Dao \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt deleted file mode 100644 index 0a09b95dbf..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/JdbcDao.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.kodein - -class JdbcDao : Dao \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt deleted file mode 100644 index 06436fcd21..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/MongoDao.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.kodein - -class MongoDao : Dao \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt deleted file mode 100644 index bb24a5cc21..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/kodein/Service.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.kodein - -class Service(private val dao: Dao, private val tag: String) \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt deleted file mode 100644 index 993ee555af..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/BookService.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.kotlin - -interface BookService { - fun inStock(bookId: Int): Boolean - fun lend(bookId: Int, memberId: Int) -} \ No newline at end of file diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt deleted file mode 100644 index 5a4718162a..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/mockito/LendBookManager.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.kotlin - -class LendBookManager(val bookService:BookService) { - fun checkout(bookId: Int, memberId: Int) { - if(bookService.inStock(bookId)) { - bookService.lend(bookId, memberId) - } else { - throw IllegalStateException("Book is not available") - } - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt deleted file mode 100644 index da2bbe4208..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/AnnotatedServer.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.kovert - -import io.vertx.ext.web.Router -import io.vertx.ext.web.RoutingContext -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.core.HttpVerb -import uy.kohesive.kovert.core.Location -import uy.kohesive.kovert.core.Verb -import uy.kohesive.kovert.core.VerbAlias -import uy.kohesive.kovert.vertx.bindController -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - - -class AnnotatedServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(AnnotatedServer::class.java) - - @JvmStatic - fun main(args: Array) { - AnnotatedServer().start() - } - } - - @VerbAlias("show", HttpVerb.GET) - class AnnotatedController { - fun RoutingContext.showStringById(id: String) = id - - @Verb(HttpVerb.GET) - @Location("/ping/:id") - fun RoutingContext.ping(id: String) = id - } - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", AnnotatedServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - bindController(AnnotatedController(), "api") - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt deleted file mode 100644 index a596391ed8..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/ErrorServer.kt +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.kovert - -import io.vertx.ext.web.Router -import io.vertx.ext.web.RoutingContext -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.core.HttpErrorCode -import uy.kohesive.kovert.core.HttpErrorCodeWithBody -import uy.kohesive.kovert.core.HttpErrorForbidden -import uy.kohesive.kovert.vertx.bindController -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - - -class ErrorServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(ErrorServer::class.java) - - @JvmStatic - fun main(args: Array) { - ErrorServer().start() - } - } - - class ErrorController { - fun RoutingContext.getForbidden() { - throw HttpErrorForbidden() - } - fun RoutingContext.getError() { - throw HttpErrorCode("Something went wrong", 590) - } - fun RoutingContext.getErrorbody() { - throw HttpErrorCodeWithBody("Something went wrong", 591, "Body here") - } - } - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", ErrorServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - bindController(ErrorController(), "api") - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt deleted file mode 100644 index 310fe2a7a0..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/JsonServer.kt +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.kovert - -import com.fasterxml.jackson.annotation.JsonProperty -import io.vertx.ext.web.Router -import io.vertx.ext.web.RoutingContext -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.vertx.bindController -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - -class JsonServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(JsonServer::class.java) - - @JvmStatic - fun main(args: Array) { - JsonServer().start() - } - } - - data class Person( - @JsonProperty("_id") - val id: String, - val name: String, - val job: String - ) - - class JsonController { - fun RoutingContext.getPersonById(id: String) = Person( - id = id, - name = "Tony Stark", - job = "Iron Man" - ) - fun RoutingContext.putPersonById(id: String, person: Person) = person - } - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", JsonServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - bindController(JsonController(), "api") - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt deleted file mode 100644 index 98ce775e66..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/NoopServer.kt +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.kovert - -import io.vertx.ext.web.Router -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - -class NoopServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(NoopServer::class.java) - - @JvmStatic - fun main(args: Array) { - NoopServer().start() - } - } - - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", NoopServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt deleted file mode 100644 index 86ca482808..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SecuredServer.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.kovert - -import io.vertx.ext.web.Router -import io.vertx.ext.web.RoutingContext -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.vertx.bindController -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - - -class SecuredServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(SecuredServer::class.java) - - @JvmStatic - fun main(args: Array) { - SecuredServer().start() - } - } - - class SecuredContext(private val routingContext: RoutingContext) { - val authenticated = routingContext.request().getHeader("Authorization") == "Secure" - } - - class SecuredController { - fun SecuredContext.getSecured() = this.authenticated - } - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SecuredServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - bindController(SecuredController(), "api") - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt deleted file mode 100644 index 172469ab46..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/kovert/SimpleServer.kt +++ /dev/null @@ -1,65 +0,0 @@ -package com.baeldung.kovert - -import io.vertx.ext.web.Router -import io.vertx.ext.web.RoutingContext -import nl.komponents.kovenant.functional.bind -import org.kodein.di.Kodein -import org.kodein.di.conf.global -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import uy.klutter.config.typesafe.ClassResourceConfig -import uy.klutter.config.typesafe.ReferenceConfig -import uy.klutter.config.typesafe.kodein.importConfig -import uy.klutter.config.typesafe.loadConfig -import uy.klutter.vertx.kodein.KodeinVertx -import uy.kohesive.kovert.vertx.bindController -import uy.kohesive.kovert.vertx.boot.KodeinKovertVertx -import uy.kohesive.kovert.vertx.boot.KovertVerticle -import uy.kohesive.kovert.vertx.boot.KovertVerticleModule -import uy.kohesive.kovert.vertx.boot.KovertVertx - - -class SimpleServer { - companion object { - private val LOG: Logger = LoggerFactory.getLogger(SimpleServer::class.java) - - @JvmStatic - fun main(args: Array) { - SimpleServer().start() - } - } - - class SimpleController { - fun RoutingContext.getStringById(id: String) = id - fun RoutingContext.get_truncatedString_by_id(id: String, length: Int = 1) = id.subSequence(0, length) - } - - fun start() { - Kodein.global.addImport(Kodein.Module { - importConfig(loadConfig(ClassResourceConfig("/kovert.conf", SimpleServer::class.java), ReferenceConfig())) { - import("kovert.vertx", KodeinKovertVertx.configModule) - import("kovert.server", KovertVerticleModule.configModule) - } - - // includes jackson ObjectMapper to match compatibility with Vertx, app logging via Vertx facade to Slf4j - import(KodeinVertx.moduleWithLoggingToSlf4j) - // Kovert boot - import(KodeinKovertVertx.module) - import(KovertVerticleModule.module) - }) - - val initControllers = fun Router.() { - bindController(SimpleController(), "api") - } - - // startup asynchronously... - KovertVertx.start() bind { vertx -> - KovertVerticle.deploy(vertx, routerInit = initControllers) - } success { deploymentId -> - LOG.warn("Deployment complete.") - } fail { error -> - LOG.error("Deployment failed!", error) - } - - } -} diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt deleted file mode 100755 index a12182ccc8..0000000000 --- a/kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt +++ /dev/null @@ -1,73 +0,0 @@ -@file:JvmName("APIServer") - - -import io.ktor.application.call -import io.ktor.application.install -import io.ktor.features.CallLogging -import io.ktor.features.ContentNegotiation -import io.ktor.features.DefaultHeaders -import io.ktor.gson.gson -import io.ktor.request.path -import io.ktor.request.receive -import io.ktor.response.respond -import io.ktor.routing.* -import io.ktor.server.engine.embeddedServer -import io.ktor.server.netty.Netty -import org.slf4j.event.Level - -data class Author(val name: String, val website: String) -data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean) - -fun main(args: Array) { - - val toDoList = ArrayList(); - val jsonResponse = """{ - "id": 1, - "task": "Pay waterbill", - "description": "Pay water bill today", - }""" - - - embeddedServer(Netty, 8080) { - install(DefaultHeaders) { - header("X-Developer", "Baeldung") - } - install(CallLogging) { - level = Level.DEBUG - filter { call -> call.request.path().startsWith("/todo") } - filter { call -> call.request.path().startsWith("/author") } - } - install(ContentNegotiation) { - gson { - setPrettyPrinting() - } - } - routing() { - route("/todo") { - post { - var toDo = call.receive(); - toDo.id = toDoList.size; - toDoList.add(toDo); - call.respond("Added") - - } - delete("/{id}") { - call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt())); - } - get("/{id}") { - - call.respond(toDoList[call.parameters["id"]!!.toInt()]); - } - get { - call.respond(toDoList); - } - } - get("/author"){ - call.respond(Author("Baeldung","baeldung.com")); - - } - - - } - }.start(wait = true) -} \ No newline at end of file diff --git a/kotlin-libraries/src/main/resources/kovert.conf b/kotlin-libraries/src/main/resources/kovert.conf deleted file mode 100644 index 3b08641693..0000000000 --- a/kotlin-libraries/src/main/resources/kovert.conf +++ /dev/null @@ -1,15 +0,0 @@ -{ - kovert: { - vertx: { - clustered: false - } - server: { - listeners: [ - { - host: "0.0.0.0" - port: "8000" - } - ] - } - } -} diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt deleted file mode 100644 index 2a7d44a163..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt +++ /dev/null @@ -1,163 +0,0 @@ -package com.baeldung.klaxon - -import com.beust.klaxon.JsonArray -import com.beust.klaxon.JsonObject -import com.beust.klaxon.JsonReader -import com.beust.klaxon.Klaxon -import com.beust.klaxon.Parser -import com.beust.klaxon.PathMatcher -import org.assertj.core.api.Assertions.assertThat -import org.assertj.core.api.SoftAssertions.assertSoftly -import org.junit.Assert -import org.junit.jupiter.api.Test -import java.io.StringReader -import java.util.regex.Pattern - -class KlaxonUnitTest { - - @Test - fun giveProduct_whenSerialize_thenGetJsonString() { - val product = Product("HDD") - val result = Klaxon().toJsonString(product) - - assertThat(result).isEqualTo("""{"name" : "HDD"}""") - } - - @Test - fun giveJsonString_whenDeserialize_thenGetProduct() { - val result = Klaxon().parse(""" - { - "name" : "RAM" - } - """) - - assertThat(result?.name).isEqualTo("RAM") - } - - @Test - fun giveCustomProduct_whenSerialize_thenGetJsonString() { - val product = CustomProduct("HDD", 1) - val result = Klaxon().toJsonString(product) - - assertThat(result).isEqualTo("""{"productName" : "HDD"}""") - } - - @Test - fun giveJsonArray_whenStreaming_thenGetProductArray() { - val jsonArray = """ - [ - { "name" : "HDD", "capacityInGb" : 512 }, - { "name" : "RAM", "capacityInGb" : 16 } - ]""" - val expectedArray = arrayListOf(ProductData("HDD", 512), - ProductData("RAM", 16)) - val klaxon = Klaxon() - val productArray = arrayListOf() - JsonReader(StringReader(jsonArray)).use { reader -> - reader.beginArray { - while (reader.hasNext()) { - val product = klaxon.parse(reader) - productArray.add(product!!) - } - } - } - - assertThat(productArray).hasSize(2).isEqualTo(expectedArray) - } - - @Test - fun giveJsonString_whenParser_thenGetJsonObject() { - val jsonString = StringBuilder(""" - { - "name" : "HDD", - "capacityInGb" : 512, - "sizeInInch" : 2.5 - } - """) - val parser = Parser() - val json = parser.parse(jsonString) as JsonObject - - assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5) - } - - @Suppress("UNCHECKED_CAST") - @Test - fun giveJsonStringArray_whenParser_thenGetJsonArray() { - val jsonString = StringBuilder(""" - [ - { "name" : "SDD" }, - { "madeIn" : "Taiwan" }, - { "warrantyInYears" : 5 } - ]""") - val parser = Parser() - val json = parser.parse(jsonString) as JsonArray - - assertSoftly({ softly -> - softly.assertThat(json).hasSize(3) - softly.assertThat(json[0]["name"]).isEqualTo("SDD") - softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan") - softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5) - }) - } - - @Test - fun givenJsonString_whenStreaming_thenProcess() { - val jsonString = """ - { - "name" : "HDD", - "madeIn" : "Taiwan", - "warrantyInYears" : 5 - "hasStock" : true - "capacitiesInTb" : [ 1, 2 ], - "features" : { "cacheInMb" : 64, "speedInRpm" : 7200 } - }""" - - JsonReader(StringReader(jsonString)).use { reader -> - reader.beginObject { - while (reader.hasNext()) { - val readName = reader.nextName() - when (readName) { - "name" -> assertThat(reader.nextString()).isEqualTo("HDD") - "madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan") - "warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5) - "hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true) - "capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2) - "features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200) - else -> Assert.fail("Unexpected name: $readName") - } - } - } - } - - } - - @Test - fun givenDiskInventory_whenRegexMatches_thenGetTypes() { - val jsonString = """ - { - "inventory" : { - "disks" : [ - { - "type" : "HDD", - "sizeInGb" : 1000 - }, - { - "type" : "SDD", - "sizeInGb" : 512 - } - ] - } - }""" - val pathMatcher = object : PathMatcher { - override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path) - - override fun onMatch(path: String, value: Any) { - when (path) { - "$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD") - "$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD") - } - } - } - Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString)) - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt deleted file mode 100644 index 692425ee07..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt +++ /dev/null @@ -1,143 +0,0 @@ -package com.baeldung.kotlin.arrow - -import arrow.core.* -import org.junit.Assert -import org.junit.Test - -class FunctionalDataTypes { - - @Test - fun whenIdCreated_thanValueIsPresent(){ - val id = Id("foo") - val justId = Id.just("foo"); - - Assert.assertEquals("foo", id.extract()) - Assert.assertEquals(justId, id) - } - - fun length(s : String) : Int = s.length - - fun isBigEnough(i : Int) : Boolean = i > 10 - - @Test - fun whenIdCreated_thanMapIsAssociative(){ - val foo = Id("foo") - - val map1 = foo.map(::length) - .map(::isBigEnough) - val map2 = foo.map { s -> isBigEnough(length(s)) } - - Assert.assertEquals(map1, map2) - } - - fun lengthId(s : String) : Id = Id.just(length(s)) - - fun isBigEnoughId(i : Int) : Id = Id.just(isBigEnough(i)) - - @Test - fun whenIdCreated_thanFlatMapIsAssociative(){ - val bar = Id("bar") - - val flatMap = bar.flatMap(::lengthId) - .flatMap(::isBigEnoughId) - val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) } - - Assert.assertEquals(flatMap, flatMap1) - } - - @Test - fun whenOptionCreated_thanValueIsPresent(){ - val factory = Option.just(42) - val constructor = Option(42) - val emptyOptional = Option.empty() - val fromNullable = Option.fromNullable(null) - - Assert.assertEquals(42, factory.getOrElse { -1 }) - Assert.assertEquals(factory, constructor) - Assert.assertEquals(emptyOptional, fromNullable) - } - - @Test - fun whenOptionCreated_thanConstructorDifferFromFactory(){ - val constructor : Option = Option(null) - val fromNullable : Option = Option.fromNullable(null) - - try{ - constructor.map { s -> s!!.length } - Assert.fail() - } catch (e : KotlinNullPointerException){ - fromNullable.map { s->s!!.length } - } - Assert.assertNotEquals(constructor, fromNullable) - } - - fun wrapper(x : Integer?) : Option = if (x == null) Option.just(-1) else Option.just(x.toInt()) - - @Test - fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){ - val optionFromNull = Option.fromNullable(null) - - Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null)) - } - - @Test - fun whenEitherCreated_thanOneValueIsPresent(){ - val rightOnly : Either = Either.right(42) - val leftOnly : Either = Either.left("foo") - - Assert.assertTrue(rightOnly.isRight()) - Assert.assertTrue(leftOnly.isLeft()) - Assert.assertEquals(42, rightOnly.getOrElse { -1 }) - Assert.assertEquals(-1, leftOnly.getOrElse { -1 }) - - Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 }) - Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 }) - Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight()) - Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft()) - } - - @Test - fun whenEvalNowUsed_thenMapEvaluatedLazily(){ - val now = Eval.now(1) - Assert.assertEquals(1, now.value()) - - var counter : Int = 0 - val map = now.map { x -> counter++; x+1 } - Assert.assertEquals(0, counter) - - val value = map.value() - Assert.assertEquals(2, value) - Assert.assertEquals(1, counter) - } - - @Test - fun whenEvalLaterUsed_theResultIsMemoized(){ - var counter : Int = 0 - val later = Eval.later { counter++; counter } - Assert.assertEquals(0, counter) - - val firstValue = later.value() - Assert.assertEquals(1, firstValue) - Assert.assertEquals(1, counter) - - val secondValue = later.value() - Assert.assertEquals(1, secondValue) - Assert.assertEquals(1, counter) - } - - @Test - fun whenEvalAlwaysUsed_theResultIsNotMemoized(){ - var counter : Int = 0 - val later = Eval.always { counter++; counter } - Assert.assertEquals(0, counter) - - val firstValue = later.value() - Assert.assertEquals(1, firstValue) - Assert.assertEquals(1, counter) - - val secondValue = later.value() - Assert.assertEquals(2, secondValue) - Assert.assertEquals(2, counter) - } - -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt deleted file mode 100644 index 47fbf825a0..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.kotlin.arrow - -import arrow.core.Either -import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber -import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber -import org.junit.Assert -import org.junit.Test - -class FunctionalErrorHandlingWithEitherTest { - - val operator = FunctionalErrorHandlingWithEither() - - @Test - fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){ - val computeWithEither = operator.computeWithEither("bar") - - Assert.assertTrue(computeWithEither.isLeft()) - when(computeWithEither){ - is Either.Left -> when(computeWithEither.a){ - NotANumber -> "Ok." - else -> Assert.fail() - } - else -> Assert.fail() - } - } - - @Test - fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){ - val computeWithEither = operator.computeWithEither("121") - - Assert.assertTrue(computeWithEither.isLeft()) - when(computeWithEither){ - is Either.Left -> when(computeWithEither.a){ - OddNumber -> "Ok." - else -> Assert.fail() - } - else -> Assert.fail() - } - } - - @Test - fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){ - val computeWithEither = operator.computeWithEither("100") - - Assert.assertTrue(computeWithEither.isRight()) - when(computeWithEither){ - is Either.Right -> when(computeWithEither.b){ - false -> "Ok." - else -> Assert.fail() - } - else -> Assert.fail() - } - } - - @Test - fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){ - val computeWithEither = operator.computeWithEither("98") - - Assert.assertTrue(computeWithEither.isRight()) - when(computeWithEither){ - is Either.Right -> when(computeWithEither.b){ - true -> "Ok." - else -> Assert.fail() - } - else -> Assert.fail() - } - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt deleted file mode 100644 index 3ca4cd033f..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.kotlin.arrow - -import org.junit.Assert -import org.junit.Test - -class FunctionalErrorHandlingWithOptionTest { - - val operator = FunctionalErrorHandlingWithOption() - - @Test - fun givenInvalidInput_thenErrorMessageIsPresent(){ - val useComputeOption = operator.computeWithOptionClient("foo") - Assert.assertEquals("Not an even number!", useComputeOption) - } - - @Test - fun givenOddNumberInput_thenErrorMessageIsPresent(){ - val useComputeOption = operator.computeWithOptionClient("539") - Assert.assertEquals("Not an even number!",useComputeOption) - } - - @Test - fun givenEvenNumberInputWithNonSquareNum_thenFalseMessageIsPresent(){ - val useComputeOption = operator.computeWithOptionClient("100") - Assert.assertEquals("The greatest divisor is square number: false",useComputeOption) - } - - @Test - fun givenEvenNumberInputWithSquareNum_thenTrueMessageIsPresent(){ - val useComputeOption = operator.computeWithOptionClient("242") - Assert.assertEquals("The greatest divisor is square number: true",useComputeOption) - } - -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt deleted file mode 100644 index 29fa18ef7a..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt +++ /dev/null @@ -1,333 +0,0 @@ -package com.baeldung.kotlin.exposed - -import org.jetbrains.exposed.dao.* -import org.jetbrains.exposed.sql.* -import org.jetbrains.exposed.sql.transactions.TransactionManager -import org.jetbrains.exposed.sql.transactions.transaction -import org.junit.Test -import java.sql.DriverManager -import kotlin.test.* - -class ExposedTest { - - @Test - fun whenH2Database_thenConnectionSuccessful() { - val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - transaction { - assertEquals(1.4.toBigDecimal(), database.version) - assertEquals("h2", database.vendor) - } - } - - @Test - fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() { - Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret") - } - - @Test - fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() { - var connected = false - Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") }) - assertEquals(false, connected) - transaction { - addLogger(StdOutSqlLogger) - assertEquals(false, connected) - SchemaUtils.create(Cities) - assertEquals(true, connected) - } - } - - @Test - fun whenManualCommit_thenOk() { - Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - transaction { - assertTrue(this is Transaction) - commit() - commit() - commit() - } - } - - @Test - fun whenInsert_thenGeneratedKeys() { - Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - transaction { - SchemaUtils.create(StarWarsFilms) - val id = StarWarsFilms.insertAndGetId { - it[name] = "The Last Jedi" - it[sequelId] = 8 - it[director] = "Rian Johnson" - } - assertEquals(1, id.value) - val insert = StarWarsFilms.insert { - it[name] = "The Force Awakens" - it[sequelId] = 7 - it[director] = "J.J. Abrams" - } - assertEquals(2, insert[StarWarsFilms.id]?.value) - val selectAll = StarWarsFilms.selectAll() - selectAll.forEach { - assertTrue { it[StarWarsFilms.sequelId] >= 7 } - } - StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll() - .forEach { - assertTrue { it[StarWarsFilms.name].startsWith("The") } - } - val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) } - assertEquals(1, select.count()) - StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) { - it[name] = "Episode VIII – The Last Jedi" - with(SqlExpressionBuilder) { - it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1) - } - } - } - } - - @Test - fun whenForeignKey_thenAutoJoin() { - Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - transaction { - addLogger(StdOutSqlLogger) - SchemaUtils.create(StarWarsFilms, Players) - StarWarsFilms.insert { - it[name] = "The Last Jedi" - it[sequelId] = 8 - it[director] = "Rian Johnson" - } - StarWarsFilms.insert { - it[name] = "The Force Awakens" - it[sequelId] = 7 - it[director] = "J.J. Abrams" - } - Players.insert { - it[name] = "Mark Hamill" - it[sequelId] = 7 - } - Players.insert { - it[name] = "Mark Hamill" - it[sequelId] = 8 - } - val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll() - assertEquals(2, simpleInnerJoin.count()) - simpleInnerJoin.forEach { - assertNotNull(it[StarWarsFilms.name]) - assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) - assertEquals("Mark Hamill", it[Players.name]) - } - val innerJoinWithCondition = (StarWarsFilms innerJoin Players) - .select { StarWarsFilms.sequelId eq Players.sequelId } - assertEquals(2, innerJoinWithCondition.count()) - innerJoinWithCondition.forEach { - assertNotNull(it[StarWarsFilms.name]) - assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) - assertEquals("Mark Hamill", it[Players.name]) - } - val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = { - StarWarsFilms.sequelId eq 8 - }).selectAll() - assertEquals(1, complexInnerJoin.count()) - complexInnerJoin.forEach { - assertNotNull(it[StarWarsFilms.name]) - assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId]) - assertEquals("Mark Hamill", it[Players.name]) - } - - } - } - - @Test - fun whenJoinWithAlias_thenFun() { - Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - transaction { - addLogger(StdOutSqlLogger) - SchemaUtils.create(StarWarsFilms, Players) - StarWarsFilms.insert { - it[name] = "The Last Jedi" - it[sequelId] = 8 - it[director] = "Rian Johnson" - } - StarWarsFilms.insert { - it[name] = "The Force Awakens" - it[sequelId] = 7 - it[director] = "J.J. Abrams" - } - val sequel = StarWarsFilms.alias("sequel") - Join(StarWarsFilms, sequel, - additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 }) - .selectAll().forEach { - assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1) - } - } - } - - @Test - fun whenEntity_thenDAO() { - val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction - val inserted = transaction { - addLogger(StdOutSqlLogger) - SchemaUtils.create(StarWarsFilms, Players) - val theLastJedi = StarWarsFilm.new { - name = "The Last Jedi" - sequelId = 8 - director = "Rian Johnson" - } - assertFalse(TransactionManager.current().entityCache.inserts.isEmpty()) - assertEquals(1, theLastJedi.id.value) //Reading this causes a flush - assertTrue(TransactionManager.current().entityCache.inserts.isEmpty()) - theLastJedi - } - transaction { - val theLastJedi = StarWarsFilm.findById(1) - assertNotNull(theLastJedi) - assertEquals(inserted.id, theLastJedi?.id) - } - connection.close() - } - - @Test - fun whenManyToOne_thenNavigation() { - val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - val connection = database.connector.invoke() - transaction { - addLogger(StdOutSqlLogger) - SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings) - val theLastJedi = StarWarsFilm.new { - name = "The Last Jedi" - sequelId = 8 - director = "Rian Johnson" - } - val someUser = User.new { - name = "Some User" - } - val rating = UserRating.new { - value = 9 - user = someUser - film = theLastJedi - } - assertEquals(theLastJedi, rating.film) - assertEquals(someUser, rating.user) - assertEquals(rating, theLastJedi.ratings.first()) - } - transaction { - val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first() - val ratings = UserRating.find { UserRatings.film eq theLastJedi.id } - assertEquals(1, ratings.count()) - val rating = ratings.first() - assertEquals("Some User", rating.user.name) - assertEquals(rating, theLastJedi.ratings.first()) - UserRating.new { - value = 8 - user = rating.user - film = theLastJedi - } - assertEquals(2, theLastJedi.ratings.count()) - } - connection.close() - } - - @Test - fun whenManyToMany_thenAssociation() { - val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver") - val connection = database.connector.invoke() - val film = transaction { - SchemaUtils.create(StarWarsFilms) - StarWarsFilm.new { - name = "The Last Jedi" - sequelId = 8 - director = "Rian Johnson" - } - } - - val actor = transaction { - SchemaUtils.create(Actors) - Actor.new { - firstname = "Daisy" - lastname = "Ridley" - } - } - - transaction { - SchemaUtils.create(StarWarsFilmActors) - film.actors = SizedCollection(listOf(actor)) - } - connection.close() - } - -} - -object Cities: IntIdTable() { - val name = varchar("name", 50) -} - -object StarWarsFilms_Simple : Table() { - val id = integer("id").autoIncrement().primaryKey() - val sequelId = integer("sequel_id").uniqueIndex() - val name = varchar("name", 50) - val director = varchar("director", 50) -} - -object StarWarsFilms : IntIdTable() { - val sequelId = integer("sequel_id").uniqueIndex() - val name = varchar("name", 50) - val director = varchar("director", 50) -} - -object Players : Table() { - //val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId) - val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex() - //val filmId = reference("film_id", StarWarsFilms).nullable() - val name = varchar("name", 50) -} - -class StarWarsFilm(id: EntityID) : Entity(id) { - companion object : EntityClass(StarWarsFilms) - - var sequelId by StarWarsFilms.sequelId - var name by StarWarsFilms.name - var director by StarWarsFilms.director - var actors by Actor via StarWarsFilmActors - val ratings by UserRating referrersOn UserRatings.film -} - -object Users: IntIdTable() { - val name = varchar("name", 50) -} - -object UserRatings: IntIdTable() { - val value = long("value") - val film = reference("film", StarWarsFilms) - val user = reference("user", Users) -} - -class User(id: EntityID): IntEntity(id) { - companion object : IntEntityClass(Users) - - var name by Users.name -} - -class UserRating(id: EntityID): IntEntity(id) { - companion object : IntEntityClass(UserRatings) - - var value by UserRatings.value - var film by StarWarsFilm referencedOn UserRatings.film - var user by User referencedOn UserRatings.user -} - -object Actors: IntIdTable() { - val firstname = varchar("firstname", 50) - val lastname = varchar("lastname", 50) -} - -class Actor(id: EntityID): IntEntity(id) { - companion object : IntEntityClass(Actors) - - var firstname by Actors.firstname - var lastname by Actors.lastname -} - -object StarWarsFilmActors : Table() { - val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0) - val actor = reference("actor", Actors).primaryKey(1) -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt deleted file mode 100644 index 1b61c05887..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/Calculator.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.kotlin.junit5 - -class Calculator { - fun add(a: Int, b: Int) = a + b - - fun divide(a: Int, b: Int) = if (b == 0) { - throw DivideByZeroException(a) - } else { - a / b - } - - fun square(a: Int) = a * a - - fun squareRoot(a: Int) = Math.sqrt(a.toDouble()) - - fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble()) -} diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt deleted file mode 100644 index 60bc4e2944..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/junit5/DivideByZeroException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.kotlin.junit5 - -class DivideByZeroException(val numerator: Int) : Exception() diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt deleted file mode 100644 index 4deb576b9f..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/khttp/KhttpLiveTest.kt +++ /dev/null @@ -1,153 +0,0 @@ -package com.baeldung.kotlin.khttp - -import khttp.structures.files.FileLike -import org.json.JSONObject -import org.junit.Test -import java.beans.ExceptionListener -import java.beans.XMLEncoder -import java.io.* -import java.lang.Exception -import java.net.ConnectException -import kotlin.test.assertEquals -import kotlin.test.assertTrue -import kotlin.test.fail - -class KhttpLiveTest { - - @Test - fun whenHttpGetRequestIsMade_thenArgsAreReturned() { - val response = khttp.get( - url = "http://httpbin.org/get", - params = mapOf("p1" to "1", "p2" to "2")) - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - } - - @Test - fun whenAlternateHttpGetRequestIsMade_thenArgsAreReturned() { - val response = khttp.request( - method = "GET", - url = "http://httpbin.org/get", - params = mapOf("p1" to "1", "p2" to "2")) - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - } - - @Test - fun whenHeadersAreSet_thenHeadersAreSent() { - val response = khttp.get( - url = "http://httpbin.org/get", - headers = mapOf("header1" to "1", "header2" to "2")) - val headers = response.jsonObject.getJSONObject("headers") - - assertEquals("1", headers["Header1"]) - assertEquals("2", headers["Header2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithJson_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - json = mapOf("pr1" to "1", "pr2" to "2")) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val json = response.jsonObject.getJSONObject("json") - - assertEquals("1", json["pr1"]) - assertEquals("2", json["pr2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithMapData_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - data = mapOf("pr1" to "1", "pr2" to "2")) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val form = response.jsonObject.getJSONObject("form") - - assertEquals("1", form["pr1"]) - assertEquals("2", form["pr2"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithFiles_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - files = listOf( - FileLike("file1", "content1"), - FileLike("file2", javaClass.getResource("KhttpTest.class").openStream().readBytes()))) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - val files = response.jsonObject.getJSONObject("files") - - assertEquals("content1", files["file1"]) - } - - @Test - fun whenHttpPostRequestIsMadeWithInputStream_thenBodyIsReturned() { - val response = khttp.post( - url = "http://httpbin.org/post", - params = mapOf("p1" to "1", "p2" to "2"), - data = ByteArrayInputStream("content!".toByteArray())) - - val args = response.jsonObject.getJSONObject("args") - - assertEquals("1", args["p1"]) - assertEquals("2", args["p2"]) - - assertEquals("content!", response.jsonObject["data"]) - } - - @Test - fun whenHttpPostStreamingRequestIsMade_thenBodyIsReturnedInChunks() { - val response = khttp.post( - url = "http://httpbin.org/post", - stream = true, - json = mapOf("pr1" to "1", "pr2" to "2")) - - val baos = ByteArrayOutputStream() - response.contentIterator(chunkSize = 10).forEach { arr : ByteArray -> baos.write(arr) } - val json = JSONObject(String(baos.toByteArray())).getJSONObject("json") - - assertEquals("1", json["pr1"]) - assertEquals("2", json["pr2"]) - } - - @Test - fun whenHttpRequestFails_thenExceptionIsThrown() { - try { - khttp.get(url = "http://localhost/nothing/to/see/here") - - fail("Should have thrown an exception") - } catch (e : ConnectException) { - //Ok - } - } - - @Test - fun whenHttpNotFound_thenExceptionIsThrown() { - val response = khttp.get(url = "http://httpbin.org/nothing/to/see/here") - - assertEquals(404, response.statusCode) - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt deleted file mode 100644 index 7776eebd52..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/kodein/KodeinUnitTest.kt +++ /dev/null @@ -1,191 +0,0 @@ -package com.baeldung.kotlin.kodein - -import com.github.salomonbrys.kodein.* -import org.assertj.core.api.Assertions.assertThat -import org.junit.Test - -class KodeinUnitTest { - - class InMemoryDao : Dao - - @Test - fun whenSingletonBinding_thenSingleInstanceIsCreated() { - var created = false - val kodein = Kodein { - bind() with singleton { - created = true - MongoDao() - } - } - - assertThat(created).isFalse() - - val dao1: Dao = kodein.instance() - - assertThat(created).isTrue() - - val dao2: Dao = kodein.instance() - - assertThat(dao1).isSameAs(dao2) - } - - @Test - fun whenFactoryBinding_thenNewInstanceIsCreated() { - val kodein = Kodein { - bind() with singleton { MongoDao() } - bind() with factory { tag: String -> Service(instance(), tag) } - } - val service1: Service = kodein.with("myTag").instance() - val service2: Service = kodein.with("myTag").instance() - - assertThat(service1).isNotSameAs(service2) - } - - @Test - fun whenProviderBinding_thenNewInstanceIsCreated() { - val kodein = Kodein { - bind() with provider { MongoDao() } - } - val dao1: Dao = kodein.instance() - val dao2: Dao = kodein.instance() - - assertThat(dao1).isNotSameAs(dao2) - } - - @Test - fun whenTaggedBinding_thenMultipleInstancesOfSameTypeCanBeRegistered() { - val kodein = Kodein { - bind("dao1") with singleton { MongoDao() } - bind("dao2") with singleton { MongoDao() } - } - val dao1: Dao = kodein.instance("dao1") - val dao2: Dao = kodein.instance("dao2") - - assertThat(dao1).isNotSameAs(dao2) - } - - @Test - fun whenEagerSingletonBinding_thenCreationIsEager() { - var created = false - val kodein = Kodein { - bind() with eagerSingleton { - created = true - MongoDao() - } - } - - assertThat(created).isTrue() - val dao1: Dao = kodein.instance() - val dao2: Dao = kodein.instance() - - assertThat(dao1).isSameAs(dao2) - } - - @Test - fun whenMultitonBinding_thenInstancesAreReused() { - val kodein = Kodein { - bind() with singleton { MongoDao() } - bind() with multiton { tag: String -> Service(instance(), tag) } - } - val service1: Service = kodein.with("myTag").instance() - val service2: Service = kodein.with("myTag").instance() - - assertThat(service1).isSameAs(service2) - } - - @Test - fun whenInstanceBinding_thenItIsReused() { - val dao = MongoDao() - val kodein = Kodein { - bind() with instance(dao) - } - val fromContainer: Dao = kodein.instance() - - assertThat(dao).isSameAs(fromContainer) - } - - @Test - fun whenConstantBinding_thenItIsAvailable() { - val kodein = Kodein { - constant("magic") with 42 - } - val fromContainer: Int = kodein.instance("magic") - - assertThat(fromContainer).isEqualTo(42) - } - - @Test - fun whenUsingModules_thenTransitiveDependenciesAreSuccessfullyResolved() { - val jdbcModule = Kodein.Module { - bind() with singleton { JdbcDao() } - } - val kodein = Kodein { - import(jdbcModule) - bind() with singleton { Controller(instance()) } - bind() with singleton { Service(instance(), "myService") } - } - - val dao: Dao = kodein.instance() - assertThat(dao).isInstanceOf(JdbcDao::class.java) - } - - @Test - fun whenComposition_thenBeansAreReUsed() { - val persistenceContainer = Kodein { - bind() with singleton { MongoDao() } - } - val serviceContainer = Kodein { - extend(persistenceContainer) - bind() with singleton { Service(instance(), "myService") } - } - val fromPersistence: Dao = persistenceContainer.instance() - val fromService: Dao = serviceContainer.instance() - - assertThat(fromPersistence).isSameAs(fromService) - } - - @Test - fun whenOverriding_thenRightBeanIsUsed() { - val commonModule = Kodein.Module { - bind() with singleton { MongoDao() } - bind() with singleton { Service(instance(), "myService") } - } - val testContainer = Kodein { - import(commonModule) - bind(overrides = true) with singleton { InMemoryDao() } - } - val dao: Dao = testContainer.instance() - - assertThat(dao).isInstanceOf(InMemoryDao::class.java) - } - - @Test - fun whenMultiBinding_thenWorks() { - val kodein = Kodein { - bind() from setBinding() - bind().inSet() with singleton { MongoDao() } - bind().inSet() with singleton { JdbcDao() } - } - val daos: Set = kodein.instance() - - assertThat(daos.map { it.javaClass as Class<*> }).containsOnly(MongoDao::class.java, JdbcDao::class.java) - } - - @Test - fun whenInjector_thenWorks() { - class Controller2 { - private val injector = KodeinInjector() - val service: Service by injector.instance() - fun injectDependencies(kodein: Kodein) = injector.inject(kodein) - } - - val kodein = Kodein { - bind() with singleton { MongoDao() } - bind() with singleton { Service(instance(), "myService") } - } - val controller = Controller2() - controller.injectDependencies(kodein) - - assertThat(controller.service).isNotNull - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt deleted file mode 100644 index ab08273686..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTest.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.kotlin; - -import org.junit.Test -import org.mockito.Mockito - -class LibraryManagementTest { - @Test(expected = IllegalStateException::class) - fun whenBookIsNotAvailable_thenAnExceptionIsThrown() { - val mockBookService = Mockito.mock(BookService::class.java) - - Mockito.`when`(mockBookService.inStock(100)).thenReturn(false) - - val manager = LendBookManager(mockBookService) - - manager.checkout(100, 1) - } - - @Test - fun whenBookIsAvailable_thenLendMethodIsCalled() { - val mockBookService = Mockito.mock(BookService::class.java) - - Mockito.`when`(mockBookService.inStock(100)).thenReturn(true) - - val manager = LendBookManager(mockBookService) - - manager.checkout(100, 1) - - Mockito.verify(mockBookService).lend(100, 1) - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt deleted file mode 100644 index 1ff4e20c61..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/mockito/LendBookManagerTestMockitoKotlin.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.kotlin; - -import com.nhaarman.mockito_kotlin.mock -import com.nhaarman.mockito_kotlin.verify -import com.nhaarman.mockito_kotlin.whenever -import org.junit.Test - -class LibraryManagementTestMockitoKotlin { - @Test(expected = IllegalStateException::class) - fun whenBookIsNotAvailable_thenAnExceptionIsThrown() { - val mockBookService = mock() - - whenever(mockBookService.inStock(100)).thenReturn(false) - - val manager = LendBookManager(mockBookService) - - manager.checkout(100, 1) - } - - @Test - fun whenBookIsAvailable_thenLendMethodIsCalled() { - val mockBookService : BookService = mock() - - whenever(mockBookService.inStock(100)).thenReturn(true) - - val manager = LendBookManager(mockBookService) - - manager.checkout(100, 1) - - verify(mockBookService).lend(100, 1) - } -} \ No newline at end of file diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt deleted file mode 100644 index 979ed3f809..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/rxkotlin/RxKotlinTest.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.kotlin.rxkotlin - -import io.reactivex.Maybe -import io.reactivex.Observable -import io.reactivex.functions.BiFunction -import io.reactivex.rxkotlin.* -import io.reactivex.subjects.PublishSubject -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse - -class RxKotlinTest { - - @Test - fun whenBooleanArrayToObserver_thenBooleanObserver() { - val observable = listOf(true, false, false).toObservable() - observable.test().assertValues(true, false, false) - } - - @Test - fun whenBooleanArrayToFlowable_thenBooleanFlowable() { - val flowable = listOf(true, false, false).toFlowable() - flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false)) - } - - @Test - fun whenIntArrayToObserver_thenIntObserver() { - val observable = listOf(1, 1, 2, 3).toObservable() - observable.test().assertValues(1, 1, 2, 3) - } - - @Test - fun whenIntArrayToFlowable_thenIntFlowable() { - val flowable = listOf(1, 1, 2, 3).toFlowable() - flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3)) - } - - @Test - fun whenObservablePairToMap_thenSingleNoDuplicates() { - val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4)) - val observable = list.toObservable() - val map = observable.toMap() - assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet()) - } - - @Test - fun whenObservablePairToMap_thenSingleWithDuplicates() { - val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4)) - val observable = list.toObservable() - val map = observable.toMultimap() - assertEquals( - mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))), - map.blockingGet()) - } - - @Test - fun whenMergeAll_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.mergeAll() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenConcatAll_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.concatAll() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenSwitchLatest_thenStream() { - val subject = PublishSubject.create>() - val observable = subject.switchLatest() - val testObserver = observable.test() - subject.onNext(Observable.just("first", "second")) - testObserver.assertValues("first", "second") - subject.onNext(Observable.just("third", "fourth")) - subject.onNext(Observable.just("fifth")) - testObserver.assertValues("first", "second", "third", "fourth", "fifth") - } - - @Test - fun whenMergeAllMaybes_thenObservable() { - val subject = PublishSubject.create>() - val observable = subject.mergeAllMaybes() - val testObserver = observable.test() - subject.onNext(Maybe.just(1)) - subject.onNext(Maybe.just(2)) - subject.onNext(Maybe.empty()) - testObserver.assertValues(1, 2) - subject.onNext(Maybe.error(Exception(""))) - subject.onNext(Maybe.just(3)) - testObserver.assertValues(1, 2).assertError(Exception::class.java) - } - - @Test - fun whenMerge_thenStream() { - val observables = mutableListOf(Observable.just("first", "second")) - val observable = observables.merge() - observables.add(Observable.just("third", "fourth")) - observables.add(Observable.error(Exception("e"))) - observables.add(Observable.just("fifth")) - - observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java) - } - - @Test - fun whenMergeDelayError_thenStream() { - val observables = mutableListOf>(Observable.error(Exception("e1"))) - val observable = observables.mergeDelayError() - observables.add(Observable.just("1", "2")) - observables.add(Observable.error(Exception("e2"))) - observables.add(Observable.just("3")) - - observable.test().assertValues("1", "2", "3").assertError(Exception::class.java) - } - - @Test - fun whenCast_thenUniformType() { - val observable = Observable.just(1, 1, 2, 3) - observable.cast().test().assertValues(1, 1, 2, 3) - } - - @Test - fun whenOfType_thenFilter() { - val observable = Observable.just(1, "and", 2, "and") - observable.ofType().test().assertValues(1, 2) - } - - @Test - fun whenFunction_thenCompletable() { - var value = 0 - val completable = { value = 3 }.toCompletable() - assertFalse(completable.test().isCancelled) - assertEquals(3, value) - } - - @Test - fun whenHelper_thenMoreIdiomaticKotlin() { - val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b } - zipWith.subscribeBy(onNext = { println(it) }) - val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b } - zip.subscribeBy(onNext = { println(it) }) - val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction { a, b -> a + b }) - zipOrig.subscribeBy(onNext = { println(it) }) - } -} diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt deleted file mode 100644 index f595d65bf2..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorSubjectTest5.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.kotlin.spek - -import com.baeldung.kotlin.junit5.Calculator -import org.jetbrains.spek.api.dsl.describe -import org.jetbrains.spek.api.dsl.it -import org.jetbrains.spek.subject.SubjectSpek -import org.junit.jupiter.api.Assertions.assertEquals - -class CalculatorSubjectTest5 : SubjectSpek({ - subject { Calculator() } - describe("A calculator") { - describe("Addition") { - val result = subject.add(3, 5) - it("Produces the correct answer") { - assertEquals(8, result) - } - } - } -}) diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt deleted file mode 100644 index 3c49d916e4..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/CalculatorTest5.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.kotlin.spek - -import com.baeldung.kotlin.junit5.Calculator -import org.jetbrains.spek.api.Spek -import org.jetbrains.spek.api.dsl.describe -import org.jetbrains.spek.api.dsl.given -import org.jetbrains.spek.api.dsl.it -import org.jetbrains.spek.api.dsl.on -import org.junit.jupiter.api.Assertions.assertEquals - -class CalculatorTest5 : Spek({ - given("A calculator") { - val calculator = Calculator() - on("Adding 3 and 5") { - val result = calculator.add(3, 5) - it("Produces 8") { - assertEquals(8, result) - } - } - } - - describe("A calculator") { - val calculator = Calculator() - describe("Addition") { - val result = calculator.add(3, 5) - it("Produces the correct answer") { - assertEquals(8, result) - } - } - } - -}) diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt deleted file mode 100644 index bbcb36e8bb..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/DataDrivenTest5.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kotlin.spek - -import org.jetbrains.spek.api.Spek -import org.jetbrains.spek.api.dsl.describe -import org.jetbrains.spek.api.dsl.it -import org.junit.jupiter.api.Assertions - -class DataDrivenTest5 : Spek({ - describe("A data driven test") { - mapOf( - "hello" to "HELLO", - "world" to "WORLD" - ).forEach { input, expected -> - describe("Capitalising $input") { - it("Correctly returns $expected") { - Assertions.assertEquals(expected, input.toUpperCase()) - } - } - } - } -}) diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt deleted file mode 100644 index 5aeee622e4..0000000000 --- a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/spek/GroupTest5.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.kotlin.spek - -import org.jetbrains.spek.api.Spek -import org.jetbrains.spek.api.dsl.describe -import org.jetbrains.spek.api.dsl.it - -class GroupTest5 : Spek({ - describe("Outer group") { - beforeEachTest { - System.out.println("BeforeEachTest 0") - } - beforeGroup { - System.out.println("BeforeGroup 0") - } - afterEachTest { - System.out.println("AfterEachTest 0") - } - afterGroup { - System.out.println("AfterGroup 0") - } - describe("Inner group 1") { - beforeEachTest { - System.out.println("BeforeEachTest 1") - } - beforeGroup { - System.out.println("BeforeGroup 1") - } - afterEachTest { - System.out.println("AfterEachTest 1") - } - afterGroup { - System.out.println("AfterGroup 1") - } - it("Test 1") { - System.out.println("Test 1") - } - it("Test 2") { - System.out.println("Test 2") - } - } - describe("Inner group 2") { - beforeEachTest { - System.out.println("BeforeEachTest 2") - } - beforeGroup { - System.out.println("BeforeGroup 2") - } - afterEachTest { - System.out.println("AfterEachTest 2") - } - afterGroup { - System.out.println("AfterGroup 2") - } - it("Test 3") { - System.out.println("Test 3") - } - it("Test 4") { - System.out.println("Test 4") - } - } - } -}) diff --git a/kotlin-quasar/README.md b/kotlin-quasar/README.md deleted file mode 100644 index b3693284f9..0000000000 --- a/kotlin-quasar/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### Relevant Articles - -- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar) -- [Advanced Quasar Usage for Kotlin](https://www.baeldung.com/kotlin-quasar-advanced) diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml deleted file mode 100644 index 59553f422e..0000000000 --- a/kotlin-quasar/pom.xml +++ /dev/null @@ -1,153 +0,0 @@ - - - 4.0.0 - kotlin-quasar - 1.0.0-SNAPSHOT - kotlin-quasar - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - co.paralleluniverse - quasar-core - ${quasar.version} - - - co.paralleluniverse - quasar-actors - ${quasar.version} - - - co.paralleluniverse - quasar-reactive-streams - ${quasar.version} - - - co.paralleluniverse - quasar-kotlin - ${quasar.version} - - - junit - junit - ${junit.version} - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - ch.qos.logback - logback-core - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - - - src/main/kotlin - src/test/kotlin - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - maven-dependency-plugin - ${dependency.plugin.version} - - - getClasspathFilenames - - properties - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.plugin.version} - - -Dco.paralleluniverse.fibers.verifyInstrumentation=true - -javaagent:${co.paralleluniverse:quasar-core:jar} - - - - org.codehaus.mojo - exec-maven-plugin - ${exec.plugin.version} - - target/classes - echo - - -javaagent:${co.paralleluniverse:quasar-core:jar} - -classpath - - com.baeldung.quasar.QuasarHelloWorldKt - - - - - - - - 0.8.0 - 1.3.31 - 1.7.21 - 1.1.7 - 3.1.1 - 2.22.1 - 1.3.2 - - - diff --git a/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt b/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt deleted file mode 100644 index 9bf01ecb09..0000000000 --- a/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Fiber -import co.paralleluniverse.strands.SuspendableRunnable - - -/** - * Entrypoint into the application - */ -fun main(args: Array) { - class Runnable : SuspendableRunnable { - override fun run() { - println("Hello") - } - } - val result = Fiber(Runnable()).start() - result.join() - println("World") -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt deleted file mode 100644 index b4d0288a64..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsBehaviorTest.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.actors.Actor -import co.paralleluniverse.actors.ActorRef -import co.paralleluniverse.actors.behaviors.* -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.strands.SuspendableCallable -import org.junit.Test -import org.slf4j.LoggerFactory -import java.lang.Exception - -class ActorsBehaviorTest { - companion object { - private val LOG = LoggerFactory.getLogger(ActorsBehaviorTest::class.java) - } - - @Test - fun requestReplyHelper() { - data class TestMessage(val input: Int) : RequestMessage() - - val actor = object : Actor("requestReplyActor", null) { - @Suspendable - override fun doRun(): Void? { - while (true) { - val msg = receive() - LOG.info("Processing message: {}", msg) - - RequestReplyHelper.reply(msg, msg.input * 100) - } - } - } - - val actorRef = actor.spawn() - - val result = RequestReplyHelper.call(actorRef, TestMessage(50)) - LOG.info("Received reply: {}", result) - } - - @Test - fun server() { - val actor = ServerActor(object : AbstractServerHandler() { - @Suspendable - override fun handleCall(from: ActorRef<*>?, id: Any?, m: Int?): String { - LOG.info("Called with message: {} from {} with ID {}", m, from, id) - return m.toString() ?: "None" - } - - @Suspendable - override fun handleCast(from: ActorRef<*>?, id: Any?, m: Float?) { - LOG.info("Cast message: {} from {} with ID {}", m, from, id) - } - }) - - val server = actor.spawn() - - LOG.info("Call result: {}", server.call(5)) - server.cast(2.5f) - - server.shutdown() - } - - interface Summer { - fun sum(a: Int, b: Int) : Int - } - - @Test - fun proxyServer() { - val actor = ProxyServerActor(false, object : Summer { - @Synchronized - override fun sum(a: Int, b: Int): Int { - Exception().printStackTrace() - LOG.info("Adding together {} and {}", a, b) - return a + b - } - }) - - val summerActor = actor.spawn() - - val result = (summerActor as Summer).sum(1, 2) - LOG.info("Result: {}", result) - - summerActor.shutdown() - } - - @Test - fun eventSource() { - val actor = EventSourceActor() - val eventSource = actor.spawn() - - eventSource.addHandler { msg -> - LOG.info("Sent message: {}", msg) - } - - val name = "Outside Value" - eventSource.addHandler { msg -> - LOG.info("Also Sent message: {} {}", msg, name) - } - - eventSource.send("Hello") - - eventSource.shutdown() - } - - @Test - fun finiteStateMachine() { - val actor = object : FiniteStateMachineActor() { - @Suspendable - override fun initialState(): SuspendableCallable> { - LOG.info("Starting") - return SuspendableCallable { lockedState() } - } - - @Suspendable - fun lockedState() : SuspendableCallable> { - return receive {msg -> - when (msg) { - "PUSH" -> { - LOG.info("Still locked") - lockedState() - } - "COIN" -> { - LOG.info("Unlocking...") - unlockedState() - } - else -> TERMINATE - } - } - } - - @Suspendable - fun unlockedState() : SuspendableCallable> { - return receive {msg -> - when (msg) { - "PUSH" -> { - LOG.info("Locking") - lockedState() - } - "COIN" -> { - LOG.info("Unlocked") - unlockedState() - } - else -> TERMINATE - } - } - } - } - - val actorRef = actor.spawn() - - listOf("PUSH", "COIN", "COIN", "PUSH", "PUSH").forEach { - LOG.info(it) - actorRef.sendSync(it) - } - - actorRef.shutdown() - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt deleted file mode 100644 index 819a149af3..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ActorsTest.kt +++ /dev/null @@ -1,298 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.actors.* -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.strands.channels.Channels -import org.junit.Assert -import org.junit.Test -import org.slf4j.LoggerFactory -import java.util.concurrent.TimeUnit - -class ActorsTest { - companion object { - private val LOG = LoggerFactory.getLogger(ActorsTest::class.java) - } - - @Test - fun createNoopActor() { - val actor = object : Actor("noopActor", MailboxConfig(5, Channels.OverflowPolicy.THROW)) { - @Suspendable - override fun doRun(): String { - return "Hello" - } - } - - actor.spawn() - - println("Noop Actor: ${actor.get()}") - } - - @Test - fun registerActor() { - val actor = object : Actor("registerActor", null) { - @Suspendable - override fun doRun(): String { - return "Hello" - } - } - - val actorRef = actor.spawn() - actor.register() - - val retrievedRef = ActorRegistry.getActor>("registerActor") - - Assert.assertEquals(actorRef, retrievedRef) - actor.join() - } - - @Test - fun registerActorNewName() { - val actor = object : Actor(null, null) { - @Suspendable - override fun doRun(): String { - return "Hello" - } - } - - val actorRef = actor.spawn() - actor.register("renamedActor") - - val retrievedRef = ActorRegistry.getActor>("renamedActor") - - Assert.assertEquals(actorRef, retrievedRef) - actor.join() - } - - @Test - fun retrieveUnknownActor() { - val retrievedRef = ActorRegistry.getActor>("unknownActor", 1, TimeUnit.SECONDS) - - Assert.assertNull(retrievedRef) - } - - @Test - fun createSimpleActor() { - val actor = object : Actor("simpleActor", null) { - @Suspendable - override fun doRun(): Void? { - val msg = receive() - LOG.info("SimpleActor Received Message: {}", msg) - - return null - } - } - - val actorRef = actor.spawn() - - actorRef.send(1) - - actor.join() - } - - @Test - fun createLoopingActor() { - val actor = object : Actor("loopingActor", null) { - @Suspendable - override fun doRun(): Void? { - while (true) { - val msg = receive() - - if (msg > 0) { - LOG.info("LoopingActor Received Message: {}", msg) - } else { - break - } - } - - return null - } - } - - val actorRef = actor.spawn() - - actorRef.send(3) - actorRef.send(2) - actorRef.send(1) - actorRef.send(0) - - actor.join() - } - - @Test - fun actorBacklog() { - val actor = object : Actor("backlogActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { - @Suspendable - override fun doRun(): String { - TimeUnit.MILLISECONDS.sleep(500); - LOG.info("Backlog Actor Received: {}", receive()) - - try { - receive() - } catch (e: Throwable) { - LOG.info("==== Exception throws by receive() ====") - e.printStackTrace() - } - - return "No Exception" - } - } - - val actorRef = actor.spawn() - - actorRef.send(1) - actorRef.send(2) - - try { - LOG.info("Backlog Actor: {}", actor.get()) - } catch (e: Exception) { - // Expected - LOG.info("==== Exception throws by get() ====") - e.printStackTrace() - } - } - - @Test - fun actorBacklogTrySend() { - val actor = object : Actor("backlogTrySendActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { - @Suspendable - override fun doRun(): String { - TimeUnit.MILLISECONDS.sleep(500); - LOG.info("Backlog TrySend Actor Received: {}", receive()) - - return "No Exception" - } - } - - val actorRef = actor.spawn() - - LOG.info("Backlog TrySend 1: {}", actorRef.trySend(1)) - LOG.info("Backlog TrySend 1: {}", actorRef.trySend(2)) - - actor.join() - } - - @Test - fun actorTimeoutReceive() { - val actor = object : Actor("TimeoutReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { - @Suspendable - override fun doRun(): String { - LOG.info("Timeout Actor Received: {}", receive(500, TimeUnit.MILLISECONDS)) - - return "Finished" - } - } - - val actorRef = actor.spawn() - - TimeUnit.MILLISECONDS.sleep(300) - actorRef.trySend(1) - - actor.join() - } - - - @Test - fun actorNonBlockingReceive() { - val actor = object : Actor("NonBlockingReceiveActor", MailboxConfig(1, Channels.OverflowPolicy.THROW)) { - @Suspendable - override fun doRun(): String { - LOG.info("NonBlocking Actor Received #1: {}", tryReceive()) - TimeUnit.MILLISECONDS.sleep(500) - LOG.info("NonBlocking Actor Received #2: {}", tryReceive()) - - return "Finished" - } - } - - val actorRef = actor.spawn() - - TimeUnit.MILLISECONDS.sleep(300) - actorRef.trySend(1) - - actor.join() - } - - @Test - fun evenActor() { - val actor = object : Actor("EvenActor", null) { - @Suspendable - override fun filterMessage(m: Any?): Int? { - return when (m) { - is Int -> { - if (m % 2 == 0) { - m * 10 - } else { - null - } - } - else -> super.filterMessage(m) - } - } - - @Suspendable - override fun doRun(): Void? { - while (true) { - val msg = receive() - - if (msg > 0) { - LOG.info("EvenActor Received Message: {}", msg) - } else { - break - } - } - - return null - } - } - - val actorRef = actor.spawn() - - actorRef.send(3) - actorRef.send(2) - actorRef.send(1) - actorRef.send(0) - - actor.join() - } - - @Test - fun watchingActors() { - val watched = object : Actor("WatchedActor", null) { - @Suspendable - override fun doRun(): Void? { - LOG.info("WatchedActor Starting") - receive(500, TimeUnit.MILLISECONDS) - LOG.info("WatchedActor Finishing") - return null - } - } - - val watcher = object : Actor("WatcherActor", null) { - @Suspendable - override fun doRun(): Void? { - LOG.info("WatcherActor Listening") - try { - LOG.info("WatcherActor received Message: {}", receive(2, TimeUnit.SECONDS)) - } catch (e: Exception) { - LOG.info("WatcherActor Received Exception", e) - } - return null - } - - @Suspendable - override fun handleLifecycleMessage(m: LifecycleMessage?): Int? { - LOG.info("WatcherActor Received Lifecycle Message: {}", m) - return super.handleLifecycleMessage(m) - } - } - - val watcherRef = watcher.spawn() - TimeUnit.MILLISECONDS.sleep(200) - - val watchedRef = watched.spawn() - watcher.link(watchedRef) - - watched.join() - watcher.join() - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt deleted file mode 100644 index b51943446e..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt +++ /dev/null @@ -1,155 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.kotlin.fiber -import co.paralleluniverse.strands.channels.Channels -import co.paralleluniverse.strands.channels.Selector -import com.google.common.base.Function -import org.junit.Test - -class ChannelsTest { - @Test - fun createChannel() { - Channels.newChannel(0, // The size of the channel buffer - Channels.OverflowPolicy.BLOCK, // The policy for when the buffer is full - true, // Whether we should optimize for a single message producer - true) // Whether we should optimize for a single message consumer - } - - @Test - fun blockOnMessage() { - val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - - fiber @Suspendable { - while (!channel.isClosed) { - val message = channel.receive() - println("Received: $message") - } - println("Stopped receiving messages") - } - - channel.send("Hello") - channel.send("World") - - channel.close() - } - - @Test - fun selectReceiveChannels() { - val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - - fiber @Suspendable { - while (!channel1.isClosed && !channel2.isClosed) { - val received = Selector.select(Selector.receive(channel1), Selector.receive(channel2)) - - println("Received: $received") - } - } - - fiber @Suspendable { - for (i in 0..10) { - channel1.send("Channel 1: $i") - } - } - - fiber @Suspendable { - for (i in 0..10) { - channel2.send("Channel 2: $i") - } - } - } - - @Test - fun selectSendChannels() { - val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - - fiber @Suspendable { - for (i in 0..10) { - Selector.select( - Selector.send(channel1, "Channel 1: $i"), - Selector.send(channel2, "Channel 2: $i") - ) - } - } - - fiber @Suspendable { - while (!channel1.isClosed) { - val msg = channel1.receive() - println("Read: $msg") - } - } - - fiber @Suspendable { - while (!channel2.isClosed) { - val msg = channel2.receive() - println("Read: $msg") - } - } - } - - @Test - fun tickerChannel() { - val channel = Channels.newChannel(3, Channels.OverflowPolicy.DISPLACE) - - for (i in 0..10) { - val tickerConsumer = Channels.newTickerConsumerFor(channel) - fiber @Suspendable { - while (!tickerConsumer.isClosed) { - val message = tickerConsumer.receive() - println("Received on $i: $message") - } - println("Stopped receiving messages on $i") - } - } - - for (i in 0..50) { - channel.send("Message $i") - } - - channel.close() - } - - - @Test - fun transformOnSend() { - val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - - fiber @Suspendable { - while (!channel.isClosed) { - val message = channel.receive() - println("Received: $message") - } - println("Stopped receiving messages") - } - - val transformOnSend = Channels.mapSend(channel, Function { msg: String? -> msg?.toUpperCase() }) - - transformOnSend.send("Hello") - transformOnSend.send("World") - - channel.close() - } - - @Test - fun transformOnReceive() { - val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) - - val transformOnReceive = Channels.map(channel, Function { msg: String? -> msg?.reversed() }) - - fiber @Suspendable { - while (!transformOnReceive.isClosed) { - val message = transformOnReceive.receive() - println("Received: $message") - } - println("Stopped receiving messages") - } - - - channel.send("Hello") - channel.send("World") - - channel.close() - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt deleted file mode 100644 index 3f73af3917..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.strands.dataflow.Val -import co.paralleluniverse.strands.dataflow.Var -import org.junit.Assert -import org.junit.Test -import java.util.concurrent.TimeUnit - -class DataflowTest { - @Test - fun testValVar() { - val a = Var() - val b = Val() - - val c = Var { a.get() + b.get() } - val d = Var { a.get() * b.get() } - - // (a*b) - (a+b) - val initialResult = Val { d.get() - c.get() } - val currentResult = Var { d.get() - c.get() } - - a.set(2) - b.set(4) - - Assert.assertEquals(2, initialResult.get()) - Assert.assertEquals(2, currentResult.get()) - - a.set(3) - - TimeUnit.SECONDS.sleep(1) - - Assert.assertEquals(2, initialResult.get()) - Assert.assertEquals(5, currentResult.get()) - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt deleted file mode 100644 index d4ea04820d..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Fiber -import co.paralleluniverse.fibers.FiberAsync -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.kotlin.fiber -import co.paralleluniverse.strands.Strand -import org.junit.Assert -import org.junit.Test -import java.math.BigDecimal -import java.util.concurrent.TimeUnit - -interface PiCallback { - fun success(result: BigDecimal) - fun failure(error: Exception) -} - -fun computePi(callback: PiCallback) { - println("Starting calculations") - TimeUnit.SECONDS.sleep(2) - println("Finished calculations") - callback.success(BigDecimal("3.14")) -} - -class PiAsync : PiCallback, FiberAsync() { - override fun success(result: BigDecimal) { - asyncCompleted(result) - } - - override fun failure(error: Exception) { - asyncFailed(error) - } - - override fun requestAsync() { - computePi(this) - } -} - -class PiAsyncTest { - @Test - fun testPi() { - val result = fiber @Suspendable { - val pi = PiAsync() - println("Waiting to get PI on: " + Fiber.currentFiber().name) - val result = pi.run() - println("Got PI") - - result - }.get() - - Assert.assertEquals(BigDecimal("3.14"), result) - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt deleted file mode 100644 index 83e06bf7d6..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ReactiveStreamsTest.kt +++ /dev/null @@ -1,135 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.kotlin.fiber -import co.paralleluniverse.strands.channels.Channels -import co.paralleluniverse.strands.channels.Topic -import co.paralleluniverse.strands.channels.reactivestreams.ReactiveStreams -import org.junit.Test -import org.reactivestreams.Subscriber -import org.reactivestreams.Subscription -import org.slf4j.LoggerFactory -import java.util.concurrent.TimeUnit - -class ReactiveStreamsTest { - companion object { - private val LOG = LoggerFactory.getLogger(ReactiveStreamsTest::class.java) - } - - @Test - fun publisher() { - val inputChannel = Channels.newChannel(1); - - val publisher = ReactiveStreams.toPublisher(inputChannel) - publisher.subscribe(object : Subscriber { - @Suspendable - override fun onComplete() { - LOG.info("onComplete") - } - - @Suspendable - override fun onSubscribe(s: Subscription) { - LOG.info("onSubscribe: {}", s) - s.request(2) - } - - @Suspendable - override fun onNext(t: String?) { - LOG.info("onNext: {}", t) - } - - @Suspendable - override fun onError(t: Throwable?) { - LOG.info("onError: {}", t) - } - }) - - inputChannel.send("Hello") - inputChannel.send("World") - - TimeUnit.SECONDS.sleep(1) - - inputChannel.close() - } - - @Test - fun publisherTopic() { - val inputTopic = Topic() - - val publisher = ReactiveStreams.toPublisher(inputTopic) - publisher.subscribe(object : Subscriber { - @Suspendable - override fun onComplete() { - LOG.info("onComplete 1") - } - - @Suspendable - override fun onSubscribe(s: Subscription) { - LOG.info("onSubscribe 1: {}", s) - s.request(2) - } - - @Suspendable - override fun onNext(t: String?) { - LOG.info("onNext 1: {}", t) - } - - @Suspendable - override fun onError(t: Throwable?) { - LOG.info("onError 1: {}", t) - } - }) - publisher.subscribe(object : Subscriber { - @Suspendable - override fun onComplete() { - LOG.info("onComplete 2") - } - - @Suspendable - override fun onSubscribe(s: Subscription) { - LOG.info("onSubscribe 2: {}", s) - s.request(2) - } - - @Suspendable - override fun onNext(t: String?) { - LOG.info("onNext 2: {}", t) - } - - @Suspendable - override fun onError(t: Throwable?) { - LOG.info("onError 2: {}", t) - } - }) - - inputTopic.send("Hello") - inputTopic.send("World") - - TimeUnit.SECONDS.sleep(1) - - inputTopic.close() - } - - @Test - fun subscribe() { - val inputChannel = Channels.newChannel(10); - val publisher = ReactiveStreams.toPublisher(inputChannel) - - val channel = ReactiveStreams.subscribe(10, Channels.OverflowPolicy.THROW, publisher) - - fiber @Suspendable { - while (!channel.isClosed) { - val message = channel.receive() - LOG.info("Received: {}", message) - } - LOG.info("Stopped receiving messages") - } - - inputChannel.send("Hello") - inputChannel.send("World") - - TimeUnit.SECONDS.sleep(1) - - inputChannel.close() - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt deleted file mode 100644 index 9b139dd686..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Fiber -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.kotlin.fiber -import co.paralleluniverse.strands.SuspendableCallable -import org.junit.Assert -import org.junit.Test -import java.util.concurrent.TimeUnit - - -class SuspendableCallableTest { - @Test - fun createFiber() { - class Callable : SuspendableCallable { - override fun run(): String { - println("Inside Fiber") - return "Hello" - } - } - val result = Fiber(Callable()).start() - - Assert.assertEquals("Hello", result.get()) - } - - @Test - fun createFiberLambda() { - val lambda: (() -> String) = { - println("Inside Fiber Lambda") - "Hello" - } - val result = Fiber(lambda) - result.start() - - Assert.assertEquals("Hello", result.get()) - } - - @Test - fun createFiberDsl() { - val result = fiber @Suspendable { - TimeUnit.SECONDS.sleep(5) - println("Inside Fiber DSL") - "Hello" - } - - Assert.assertEquals("Hello", result.get()) - } -} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt deleted file mode 100644 index ba4cef8f4c..0000000000 --- a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.quasar - -import co.paralleluniverse.fibers.Fiber -import co.paralleluniverse.fibers.Suspendable -import co.paralleluniverse.kotlin.fiber -import co.paralleluniverse.strands.SuspendableRunnable -import org.junit.Test -import java.util.concurrent.TimeUnit -import java.util.concurrent.TimeoutException - - -class SuspensableRunnableTest { - @Test - fun createFiber() { - class Runnable : SuspendableRunnable { - override fun run() { - println("Inside Fiber") - } - } - val result = Fiber(Runnable()).start() - result.join() - } - - @Test - fun createFiberLambda() { - val result = Fiber { - println("Inside Fiber Lambda") - } - result.start() - result.join() - } - - @Test - fun createFiberDsl() { - fiber @Suspendable { - println("Inside Fiber DSL") - }.join() - } - - @Test(expected = TimeoutException::class) - fun fiberTimeout() { - fiber @Suspendable { - TimeUnit.SECONDS.sleep(5) - println("Inside Fiber DSL") - }.join(2, TimeUnit.SECONDS) - } -} diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index 96f9e2911d..d0bdb26bd4 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -84,7 +84,6 @@ 3.14.2 2.8.5 3.14.2 - 1.0.3 9.4.19.v20190610 2.2.11 diff --git a/kotlin-js/src/main/resources/logback.xml b/libraries-http-2/src/main/resources/logback.xml similarity index 100% rename from kotlin-js/src/main/resources/logback.xml rename to libraries-http-2/src/main/resources/logback.xml diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java index 4a3e67a7c5..876586032a 100644 --- a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java @@ -3,23 +3,16 @@ package com.baeldung.jetty.httpclient; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; public abstract class AbstractUnitTest { - protected HttpClient httpClient; - protected Server server; + protected static HttpClient httpClient; + protected static Server server; protected static final String CONTENT = "Hello World!"; - protected final int port = 9080; - - @Before - public void init() { - startServer(new RequestHandler()); - startClient(); - } - private void startClient() { + protected static void startClient() { httpClient = new HttpClient(); try { httpClient.start(); @@ -28,7 +21,7 @@ public abstract class AbstractUnitTest { } } - private void startServer(Handler handler) { + protected static void startServer(Handler handler, int port) { server = new Server(port); server.setHandler(handler); try { @@ -37,18 +30,9 @@ public abstract class AbstractUnitTest { e.printStackTrace(); } } - - @After - public void dispose() throws Exception { - if (httpClient != null) { - httpClient.stop(); - } - if (server != null) { - server.stop(); - } - } - - protected String uri() { + + protected String uri(int port) { return "http://localhost:" + port; } + } \ No newline at end of file diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java index 6d79773609..db27ea1c89 100644 --- a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java @@ -4,18 +4,29 @@ import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.reactive.client.ReactiveRequest; import org.eclipse.jetty.reactive.client.ReactiveResponse; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; public class ProjectReactorUnitTest extends AbstractUnitTest { + protected static int port = 9080; + + @BeforeAll + public static void init() { + startServer(new RequestHandler(), port); + startClient(); + } + @Test public void givenReactiveClient_whenRequested_shouldReturn200() throws Exception { - Request request = httpClient.newRequest(uri()); + Request request = httpClient.newRequest(uri(port)); ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) .build(); Publisher publisher = reactiveRequest.response(); @@ -23,8 +34,19 @@ public class ProjectReactorUnitTest extends AbstractUnitTest { ReactiveResponse response = Mono.from(publisher) .block(); - Assert.assertNotNull(response); - Assert.assertEquals(response.getStatus(), HttpStatus.OK_200); + assertNotNull(response); + assertEquals(response.getStatus(), HttpStatus.OK_200); } + + @AfterAll + public static void dispose() throws Exception { + if (httpClient != null) { + httpClient.stop(); + } + if (server != null) { + server.stop(); + } + } + } diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java index 3db4553c86..494d65e9e1 100644 --- a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java @@ -4,16 +4,27 @@ import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.reactive.client.ReactiveRequest; import org.eclipse.jetty.reactive.client.ReactiveResponse; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; public class ReactiveStreamsUnitTest extends AbstractUnitTest { + + protected static int port = 9081; + + @BeforeAll + public static void init() { + startServer(new RequestHandler(), port); + startClient(); + } @Test public void givenReactiveClient_whenRequested_shouldReturn200() throws Exception { - Request request = httpClient.newRequest(uri()); + Request request = httpClient.newRequest(uri(port)); ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) .build(); Publisher publisher = reactiveRequest.response(); @@ -21,8 +32,18 @@ public class ReactiveStreamsUnitTest extends AbstractUnitTest { BlockingSubscriber subscriber = new BlockingSubscriber(); publisher.subscribe(subscriber); ReactiveResponse response = subscriber.block(); - Assert.assertNotNull(response); - Assert.assertEquals(response.getStatus(), HttpStatus.OK_200); + assertNotNull(response); + assertEquals(response.getStatus(), HttpStatus.OK_200); + } + + @AfterAll + public static void dispose() throws Exception { + if (httpClient != null) { + httpClient.stop(); + } + if (server != null) { + server.stop(); + } } } diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java index dabd768702..a819eec475 100644 --- a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java @@ -10,8 +10,11 @@ import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.reactive.client.ReactiveRequest; import org.eclipse.jetty.reactive.client.ReactiveRequest.Event.Type; import org.eclipse.jetty.reactive.client.ReactiveResponse; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import org.springframework.http.MediaType; @@ -19,11 +22,19 @@ import io.reactivex.Flowable; import io.reactivex.Single; public class RxJava2UnitTest extends AbstractUnitTest { + + protected static int port = 9082; + + @BeforeAll + public static void init() { + startServer(new RequestHandler(), port); + startClient(); + } @Test public void givenReactiveClient_whenRequestedWithBody_ShouldReturnBody() throws Exception { - Request request = httpClient.newRequest(uri()); + Request request = httpClient.newRequest(uri(port)); ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) .content(ReactiveRequest.Content.fromString(CONTENT, MediaType.TEXT_PLAIN_VALUE, UTF_8)) .build(); @@ -32,12 +43,12 @@ public class RxJava2UnitTest extends AbstractUnitTest { String responseContent = Single.fromPublisher(publisher) .blockingGet(); - Assert.assertEquals(CONTENT, responseContent); + assertEquals(CONTENT, responseContent); } @Test public void givenReactiveClient_whenRequested_ShouldPrintEvents() throws Exception { - ReactiveRequest request = ReactiveRequest.newBuilder(httpClient, uri()) + ReactiveRequest request = ReactiveRequest.newBuilder(httpClient, uri(port)) .content(ReactiveRequest.Content.fromString(CONTENT, MediaType.TEXT_PLAIN_VALUE, UTF_8)) .build(); Publisher requestEvents = request.requestEvents(); @@ -58,10 +69,20 @@ public class RxJava2UnitTest extends AbstractUnitTest { int actualStatus = response.blockingGet() .getStatus(); - Assert.assertEquals(6, requestEventTypes.size()); - Assert.assertEquals(5, responseEventTypes.size()); + assertEquals(6, requestEventTypes.size()); + assertEquals(5, responseEventTypes.size()); - Assert.assertEquals(actualStatus, HttpStatus.OK_200); + assertEquals(actualStatus, HttpStatus.OK_200); + } + + @AfterAll + public static void dispose() throws Exception { + if (httpClient != null) { + httpClient.stop(); + } + if (server != null) { + server.stop(); + } } } \ No newline at end of file diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java index 4a1a9bb2b5..f14fc38e1d 100644 --- a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java @@ -1,8 +1,11 @@ package com.baeldung.jetty.httpclient; import org.eclipse.jetty.client.HttpClient; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.http.client.reactive.ClientHttpConnector; import org.springframework.http.client.reactive.JettyClientHttpConnector; @@ -12,25 +15,40 @@ import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class SpringWebFluxUnitTest extends AbstractUnitTest { - + + protected static int port = 9083; + + @BeforeAll + public static void init() { + startServer(new RequestHandler(), port); + startClient(); + } + @Test public void givenReactiveClient_whenRequested_shouldReturnResponse() throws Exception { - - HttpClient httpClient = new HttpClient(); - httpClient.start(); ClientHttpConnector clientConnector = new JettyClientHttpConnector(httpClient); WebClient client = WebClient.builder() .clientConnector(clientConnector) .build(); String responseContent = client.post() - .uri(uri()) + .uri(uri(port)) .contentType(MediaType.TEXT_PLAIN) .body(BodyInserters.fromPublisher(Mono.just(CONTENT), String.class)) .retrieve() .bodyToMono(String.class) .block(); - Assert.assertNotNull(responseContent); - Assert.assertEquals(CONTENT, responseContent); + assertNotNull(responseContent); + assertEquals(CONTENT, responseContent); + } + + @AfterAll + public static void dispose() throws Exception { + if (httpClient != null) { + httpClient.stop(); + } + if (server != null) { + server.stop(); + } } } \ No newline at end of file diff --git a/machine-learning/README.md b/machine-learning/README.md deleted file mode 100644 index 80f2d2c6cd..0000000000 --- a/machine-learning/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Introduction to Supervised Learning in Kotlin](https://www.baeldung.com/kotlin-supervised-learning) diff --git a/machine-learning/pom.xml b/machine-learning/pom.xml deleted file mode 100644 index 842e488985..0000000000 --- a/machine-learning/pom.xml +++ /dev/null @@ -1,163 +0,0 @@ - - - 4.0.0 - machine-learning - 1.0-SNAPSHOT - machine-learning - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.nd4j - nd4j-native-platform - ${dl4j.version} - - - org.deeplearning4j - deeplearning4j-core - ${dl4j.version} - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - ${kotlin.version} - - - - - src/main/kotlin - src/test - - - - - maven-clean-plugin - ${clean.plugin.version} - - - - maven-resources-plugin - ${resources.plugin.version} - - - maven-compiler-plugin - ${compiler.plugin.version} - - - maven-surefire-plugin - ${surefire.plugin.version} - - - maven-jar-plugin - ${jar.plugin.version} - - - maven-install-plugin - ${install.plugin.version} - - - maven-deploy-plugin - ${deploy.plugin.version} - - - - maven-site-plugin - ${site.plugin.version} - - - maven-project-info-reports-plugin - ${report.plugin.version} - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - 1.8 - - - - org.apache.maven.plugins - maven-compiler-plugin - - - compile - compile - - compile - - - - testCompile - test-compile - - testCompile - - - - - - - - - UTF-8 - 1.7 - 1.7 - 1.3.50 - 0.9.1 - 3.1.0 - 3.0.2 - 3.0.2 - 3.8.0 - 2.22.1 - 2.5.2 - 2.8.2 - 3.7.1 - 3.0.0 - - - diff --git a/machine-learning/src/main/kotlin/com/baeldung/cnn/ConvolutionalNeuralNetwork.kt b/machine-learning/src/main/kotlin/com/baeldung/cnn/ConvolutionalNeuralNetwork.kt deleted file mode 100644 index b77fe273ae..0000000000 --- a/machine-learning/src/main/kotlin/com/baeldung/cnn/ConvolutionalNeuralNetwork.kt +++ /dev/null @@ -1,117 +0,0 @@ -package com.baeldung.cnn - -import org.datavec.api.records.reader.impl.collection.ListStringRecordReader -import org.datavec.api.split.ListStringSplit -import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator -import org.deeplearning4j.eval.Evaluation -import org.deeplearning4j.nn.conf.NeuralNetConfiguration -import org.deeplearning4j.nn.conf.inputs.InputType -import org.deeplearning4j.nn.conf.layers.* -import org.deeplearning4j.nn.multilayer.MultiLayerNetwork -import org.deeplearning4j.nn.weights.WeightInit -import org.nd4j.linalg.activations.Activation -import org.nd4j.linalg.learning.config.Adam -import org.nd4j.linalg.lossfunctions.LossFunctions - -object ConvolutionalNeuralNetwork { - - @JvmStatic - fun main(args: Array) { - val dataset = ZalandoMNISTDataSet().load() - dataset.shuffle() - val trainDatasetIterator = createDatasetIterator(dataset.subList(0, 50_000)) - val testDatasetIterator = createDatasetIterator(dataset.subList(50_000, 60_000)) - - val cnn = buildCNN() - learning(cnn, trainDatasetIterator) - testing(cnn, testDatasetIterator) - } - - private fun createDatasetIterator(dataset: MutableList>): RecordReaderDataSetIterator { - val listStringRecordReader = ListStringRecordReader() - listStringRecordReader.initialize(ListStringSplit(dataset)) - return RecordReaderDataSetIterator(listStringRecordReader, 128, 28 * 28, 10) - } - - private fun buildCNN(): MultiLayerNetwork { - val multiLayerNetwork = MultiLayerNetwork(NeuralNetConfiguration.Builder() - .seed(123) - .l2(0.0005) - .updater(Adam()) - .weightInit(WeightInit.XAVIER) - .list() - .layer(0, buildInitialConvolutionLayer()) - .layer(1, buildBatchNormalizationLayer()) - .layer(2, buildPoolingLayer()) - .layer(3, buildConvolutionLayer()) - .layer(4, buildBatchNormalizationLayer()) - .layer(5, buildPoolingLayer()) - .layer(6, buildDenseLayer()) - .layer(7, buildBatchNormalizationLayer()) - .layer(8, buildDenseLayer()) - .layer(9, buildOutputLayer()) - .setInputType(InputType.convolutionalFlat(28, 28, 1)) - .backprop(true) - .build()) - multiLayerNetwork.init() - return multiLayerNetwork - } - - private fun buildOutputLayer(): OutputLayer? { - return OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) - .nOut(10) - .activation(Activation.SOFTMAX) - .build() - } - - private fun buildDenseLayer(): DenseLayer? { - return DenseLayer.Builder().activation(Activation.RELU) - .nOut(500) - .dropOut(0.5) - .build() - } - - private fun buildPoolingLayer(): SubsamplingLayer? { - return SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) - .kernelSize(2, 2) - .stride(2, 2) - .build() - } - - private fun buildBatchNormalizationLayer() = BatchNormalization.Builder().build() - - private fun buildConvolutionLayer(): ConvolutionLayer? { - return ConvolutionLayer.Builder(5, 5) - .stride(1, 1) // nIn need not specified in later layers - .nOut(50) - .activation(Activation.IDENTITY) - .build() - } - - private fun buildInitialConvolutionLayer(): ConvolutionLayer? { - return ConvolutionLayer.Builder(5, 5) - .nIn(1) - .stride(1, 1) - .nOut(20) - .activation(Activation.IDENTITY) - .build() - } - - private fun learning(cnn: MultiLayerNetwork, trainSet: RecordReaderDataSetIterator) { - for (i in 0 until 10) { - cnn.fit(trainSet) - } - } - - private fun testing(cnn: MultiLayerNetwork, testSet: RecordReaderDataSetIterator) { - val evaluation = Evaluation(10) - while (testSet.hasNext()) { - val next = testSet.next() - val output = cnn.output(next.features) - evaluation.eval(next.labels, output) - } - - println(evaluation.stats()) - println(evaluation.confusionToString()) - } -} \ No newline at end of file diff --git a/machine-learning/src/main/kotlin/com/baeldung/cnn/ZalandoMNISTDataSet.kt b/machine-learning/src/main/kotlin/com/baeldung/cnn/ZalandoMNISTDataSet.kt deleted file mode 100644 index f29c8f2d0b..0000000000 --- a/machine-learning/src/main/kotlin/com/baeldung/cnn/ZalandoMNISTDataSet.kt +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.cnn - -import java.io.File -import java.nio.ByteBuffer -import java.util.* -import java.util.stream.Collectors -import kotlin.streams.asStream - -class ZalandoMNISTDataSet { - private val OFFSET_SIZE = 4 //in bytes - private val NUM_ITEMS_OFFSET = 4 - private val ITEMS_SIZE = 4 - private val ROWS = 28 - private val COLUMNS = 28 - private val IMAGE_OFFSET = 16 - private val IMAGE_SIZE = ROWS * COLUMNS - - fun load(): MutableList> { - val labelsFile = File("machine-learning/src/main/resources/train-labels-idx1-ubyte") - val imagesFile = File("machine-learning/src/main/resources/train-images-idx3-ubyte") - - val labelBytes = labelsFile.readBytes() - val imageBytes = imagesFile.readBytes() - - val byteLabelCount = Arrays.copyOfRange(labelBytes, NUM_ITEMS_OFFSET, NUM_ITEMS_OFFSET + ITEMS_SIZE) - val numberOfLabels = ByteBuffer.wrap(byteLabelCount).int - - val list = mutableListOf>() - - for (i in 0 until numberOfLabels) { - val label = labelBytes[OFFSET_SIZE + ITEMS_SIZE + i] - val startBoundary = i * IMAGE_SIZE + IMAGE_OFFSET - val endBoundary = i * IMAGE_SIZE + IMAGE_OFFSET + IMAGE_SIZE - val imageData = Arrays.copyOfRange(imageBytes, startBoundary, endBoundary) - - val imageDataList = imageData.iterator() - .asSequence() - .asStream().map { b -> b.toString() } - .collect(Collectors.toList()) - imageDataList.add(label.toString()) - list.add(imageDataList) - } - return list - } -} \ No newline at end of file diff --git a/machine-learning/src/main/kotlin/com/baeldung/simplelinearregression/SimpleLinearRegression.kt b/machine-learning/src/main/kotlin/com/baeldung/simplelinearregression/SimpleLinearRegression.kt deleted file mode 100644 index 5ab520924e..0000000000 --- a/machine-learning/src/main/kotlin/com/baeldung/simplelinearregression/SimpleLinearRegression.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.simplelinearregression - -import kotlin.math.pow - -class SimpleLinearRegression(private val xs: List, private val ys: List) { - var slope: Double = 0.0 - var yIntercept: Double = 0.0 - - init { - val covariance = calculateCovariance(xs, ys) - val variance = calculateVariance(xs) - slope = calculateSlope(covariance, variance) - yIntercept = calculateYIntercept(ys, slope, xs) - } - - fun predict(independentVariable: Double) = slope * independentVariable + yIntercept - - fun calculateRSquared(): Double { - val sst = ys.sumByDouble { y -> (y - ys.average()).pow(2) } - val ssr = xs.zip(ys) { x, y -> (y - predict(x.toDouble())).pow(2) }.sum() - return (sst - ssr) / sst - } - - private fun calculateYIntercept(ys: List, slope: Double, xs: List) = ys.average() - slope * xs.average() - - private fun calculateSlope(covariance: Double, variance: Double) = covariance / variance - - private fun calculateCovariance(xs: List, ys: List) = xs.zip(ys) { x, y -> (x - xs.average()) * (y - ys.average()) }.sum() - - private fun calculateVariance(xs: List) = xs.sumByDouble { x -> (x - xs.average()).pow(2) } -} \ No newline at end of file diff --git a/machine-learning/src/main/resources/train-labels-idx1-ubyte b/machine-learning/src/main/resources/train-labels-idx1-ubyte deleted file mode 100644 index 30424ca2ea..0000000000 Binary files a/machine-learning/src/main/resources/train-labels-idx1-ubyte and /dev/null differ diff --git a/machine-learning/src/test/com/baeldung/simplelinearregression/SimpleLinearRegressionUnitTest.kt b/machine-learning/src/test/com/baeldung/simplelinearregression/SimpleLinearRegressionUnitTest.kt deleted file mode 100644 index a741639d50..0000000000 --- a/machine-learning/src/test/com/baeldung/simplelinearregression/SimpleLinearRegressionUnitTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.simplelinearregression - -import org.junit.Assert.assertEquals -import org.junit.jupiter.api.Test - -class SimpleLinearRegressionUnitTest { - @Test - fun givenAProperDataSetWhenFedToASimpleLinearRegressionModelThenItPredictsCorrectly() { - val xs = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - val ys = arrayListOf(25, 35, 49, 60, 75, 90, 115, 130, 150, 200) - - val model = SimpleLinearRegression(xs, ys) - - val predictionOne = model.predict(2.5) - assertEquals(38.99, predictionOne, 0.01) - - val predictionTwo = model.predict(7.5) - assertEquals(128.84, predictionTwo, 0.01) - } - - @Test - fun givenAPredictableDataSetWhenCalculatingTheLossFunctionThenTheModelIsConsideredReliable() { - val xs = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - val ys = arrayListOf(25, 35, 49, 60, 75, 90, 115, 130, 150, 200) - - val model = SimpleLinearRegression(xs, ys) - - assertEquals(0.95, model.calculateRSquared(), 0.01) - } - - @Test - fun givenAnUnpredictableDataSetWhenCalculatingTheLossFunctionThenTheModelIsConsideredUnreliable() { - val xs = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - val ys = arrayListOf(200, 0, 200, 0, 0, 0, -115, 1000, 0, 1) - - val model = SimpleLinearRegression(xs, ys) - - assertEquals(0.01, model.calculateRSquared(), 0.01) - } -} \ No newline at end of file diff --git a/maven-modules/README.md b/maven-modules/README.md index 1ef664f879..19f0473a58 100644 --- a/maven-modules/README.md +++ b/maven-modules/README.md @@ -7,3 +7,4 @@ This module contains articles about Apache Maven. Please refer to its submodules - [Apache Maven Tutorial](https://www.baeldung.com/maven) - [Apache Maven Standard Directory Layout](https://www.baeldung.com/maven-directory-structure) - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) +- [Maven Packaging Types](https://www.baeldung.com/maven-packaging-types) diff --git a/parent-kotlin/README.md b/parent-kotlin/README.md deleted file mode 100644 index c78ecbac42..0000000000 --- a/parent-kotlin/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Parent Kotlin - -This is a parent module for all projects using Kotlin diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml deleted file mode 100644 index 947dd20483..0000000000 --- a/parent-kotlin/pom.xml +++ /dev/null @@ -1,223 +0,0 @@ - - - 4.0.0 - parent-kotlin - parent-kotlin - pom - Parent for all kotlin modules - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - jcenter - https://jcenter.bintray.com - - - kotlin-ktor - https://dl.bintray.com/kotlin/ktor/ - - - kotlin-eap - https://dl.bintray.com/kotlin/kotlin-eap - - - spring-milestone - Spring Milestone Repository - https://repo.spring.io/milestone - - - - - - kotlin-eap - https://dl.bintray.com/kotlin/kotlin-eap - - - - - - - org.springframework.boot - spring-boot-dependencies - ${boot.dependencies.version} - pom - import - - - - - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-stdlib - - - org.jetbrains.kotlin - kotlin-reflect - - - - org.jetbrains.kotlinx - kotlinx-coroutines-core - ${kotlinx.version} - - - - io.ktor - ktor-server-netty - ${ktor.io.version} - - - io.ktor - ktor-gson - ${ktor.io.version} - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - - org.jetbrains.kotlin - kotlin-test-junit - test - - - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - ${kotlin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - ${java.version} - - -Xjvm-default=enable - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - ${java.version} - - - - - - spring - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - - default-compile - none - - - - default-testCompile - none - - - java-compile - compile - - compile - - - - java-test-compile - test-compile - - testCompile - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - - - junit5 - - integration-test - verify - - - - **/*Test5.java - - - - - - - - - - 1.3.30 - 1.0.0 - 0.9.5 - 3.12.0 - 1.3.2 - 2.2.0.M4 - - - diff --git a/persistence-modules/java-jpa-3/README.md b/persistence-modules/java-jpa-3/README.md index 504c7ccdd0..50ea75d995 100644 --- a/persistence-modules/java-jpa-3/README.md +++ b/persistence-modules/java-jpa-3/README.md @@ -6,3 +6,5 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [JPA Entity Equality](https://www.baeldung.com/jpa-entity-equality) - [Ignoring Fields With the JPA @Transient Annotation](https://www.baeldung.com/jpa-transient-ignore-field) +- [Defining Indexes in JPA](https://www.baeldung.com/jpa-indexes) +- [JPA CascadeType.REMOVE vs orphanRemoval](https://www.baeldung.com/jpa-cascade-remove-vs-orphanremoval) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index de5188c1ad..0a690fe5a5 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -2,4 +2,5 @@ ### Relevant Articles: - [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) -- More articles: [[<-- prev]](/spring-data-jpa-repo/) \ No newline at end of file +- [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall) +- More articles: [[<-- prev]](/spring-data-jpa-repo/) diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/Book.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/Book.java new file mode 100644 index 0000000000..b6abdd2ed5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/Book.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.data.persistence.saveperformance; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Book { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String title; + private String author; + + public Book(final String title, final String author) { + this.title = title; + this.author = author; + } + + public Book() { + } +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java new file mode 100644 index 0000000000..56ad918be3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookApplication.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.data.persistence.saveperformance; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; + +import java.util.ArrayList; +import java.util.List; + +@SpringBootApplication +public class BookApplication { + + @Autowired + private BookRepository bookRepository; + + public static void main(String[] args) { + SpringApplication.run(BookApplication.class, args); + } + + @EventListener(ApplicationReadyEvent.class) + public void executePerformanceBenchmark() { + + int bookCount = 10000; + + long start = System.currentTimeMillis(); + for(int i = 0; i < bookCount; i++) { + bookRepository.save(new Book("Book " + i, "Author " + i)); + } + long end = System.currentTimeMillis(); + bookRepository.deleteAll(); + + System.out.println("It took " + (end - start) + "ms to execute save() for " + bookCount + " books"); + + List bookList = new ArrayList<>(); + for (int i = 0; i < bookCount; i++) { + bookList.add(new Book("Book " + i, "Author " + i)); + } + + start = System.currentTimeMillis(); + bookRepository.saveAll(bookList); + end = System.currentTimeMillis(); + + System.out.println("It took " + (end - start) + "ms to execute saveAll() with " + bookCount + " books\n"); + + } +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookRepository.java new file mode 100644 index 0000000000..9db4a18796 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/saveperformance/BookRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.data.persistence.saveperformance; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BookRepository extends JpaRepository { + +} diff --git a/pom.xml b/pom.xml index 82e242b9af..15a9170672 100644 --- a/pom.xml +++ b/pom.xml @@ -325,7 +325,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin akka-http akka-streams @@ -386,7 +385,6 @@ core-groovy-strings core-java-modules - core-kotlin-modules core-scala couchbase @@ -457,7 +455,6 @@ jaxb jee-7 jee-7-security - jee-kotlin jersey jgit jgroups @@ -475,11 +472,6 @@ jsoup jta - - kotlin-libraries - kotlin-libraries-2 - kotlin-quasar - language-interop libraries-2 @@ -506,7 +498,6 @@ lombok-custom lucene - machine-learning mapstruct maven-modules @@ -599,7 +590,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin saas software-security/sql-injection-samples @@ -683,7 +673,6 @@ spring-mvc-forms-thymeleaf spring-mvc-java spring-mvc-java-2 - spring-mvc-kotlin spring-mvc-velocity spring-mvc-views @@ -693,7 +682,6 @@ spring-protobuf spring-quartz - spring-reactive-kotlin spring-reactor spring-remoting spring-rest-angular @@ -793,7 +781,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin jenkins/plugins jhipster @@ -838,7 +825,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin akka-http akka-streams @@ -898,7 +884,6 @@ core-groovy-strings core-java-modules - core-kotlin-modules core-scala couchbase @@ -969,7 +954,6 @@ jaxb jee-7 jee-7-security - jee-kotlin jersey jgit jgroups @@ -986,11 +970,6 @@ jsoup jta - - kotlin-libraries - kotlin-libraries-2 - kotlin-quasar - libraries-2 libraries-3 @@ -1016,7 +995,6 @@ lombok-custom lucene - machine-learning mapstruct maven-modules @@ -1101,7 +1079,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin saas software-security/sql-injection-samples @@ -1183,8 +1160,7 @@ spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java - spring-mvc-java-2 - spring-mvc-kotlin + spring-mvc-java-2 spring-mvc-velocity spring-mvc-views @@ -1195,7 +1171,6 @@ spring-protobuf spring-quartz - spring-reactive-kotlin spring-reactor spring-remoting spring-rest-angular @@ -1286,7 +1261,6 @@ parent-spring-4 parent-spring-5 parent-java - parent-kotlin jenkins/plugins jhipster @@ -1471,7 +1445,6 @@ 1.6.0 1.8 1.2.17 - 1.1 2.1.0.1 1.19 1.19 diff --git a/spring-5-data-reactive/README.md b/spring-5-data-reactive/README.md index 42fcba96f2..0931161700 100644 --- a/spring-5-data-reactive/README.md +++ b/spring-5-data-reactive/README.md @@ -6,7 +6,6 @@ This module contains articles about reactive Spring 5 Data The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](https://www.baeldung.com/kotlin-mongodb-spring-webflux) - [Spring Data Reactive Repositories with MongoDB](https://www.baeldung.com/spring-data-mongodb-reactive) - [Spring Data MongoDB Tailable Cursors](https://www.baeldung.com/spring-data-mongodb-tailable-cursors) - [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 396f7f5959..0fb689f16d 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -31,18 +31,6 @@ org.springframework.boot spring-boot-starter-web - - com.fasterxml.jackson.module - jackson-module-kotlin - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlin - kotlin-reflect - org.projectlombok lombok @@ -52,12 +40,6 @@ reactor-test test - - org.jetbrains.kotlin - kotlin-test - ${kotlin.version} - test - io.reactivex.rxjava2 rxjava @@ -128,53 +110,6 @@ org.springframework.boot spring-boot-maven-plugin - - kotlin-maven-plugin - ${kotlin-maven-plugin.version} - - - compile - - compile - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/main/java - - - - - test-compile - - test-compile - - - - ${project.basedir}/src/test/kotlin - ${project.basedir}/src/test/java - - - - - org.jetbrains.kotlin - - - -Xjsr305=strict - - - spring - - 1.8 - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - org.apache.maven.plugins maven-compiler-plugin @@ -215,8 +150,6 @@ - 1.2.40 - 1.2.40 5.2.2.RELEASE 1.0.0.RELEASE 0.8.1.RELEASE diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt deleted file mode 100644 index 5a59d11de0..0000000000 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Application.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration - -@SpringBootApplication(exclude = arrayOf(MongoReactiveDataAutoConfiguration::class)) -class Application - -fun main(args: Array) { - SpringApplication.run(Application::class.java, *args) -} diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt deleted file mode 100644 index 17fa9699a8..0000000000 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/Event.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung - -import org.springframework.data.mongodb.core.mapping.Document - -@Document -data class Event(val id: String, val name: String) diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt deleted file mode 100644 index e66af71ea6..0000000000 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/EventRepository.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung - -import org.springframework.data.mongodb.core.mapping.Document -import org.springframework.data.mongodb.repository.ReactiveMongoRepository - -interface EventRepository : ReactiveMongoRepository diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt deleted file mode 100644 index 64d51a176a..0000000000 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/MongoConfig.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung - -import com.mongodb.reactivestreams.client.MongoClient -import com.mongodb.reactivestreams.client.MongoClients -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration -import org.springframework.data.mongodb.core.ReactiveMongoTemplate -import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories - - -@Configuration -@EnableReactiveMongoRepositories(basePackageClasses = arrayOf(EventRepository::class)) -class MongoConfig : AbstractReactiveMongoConfiguration() { - - override fun reactiveMongoClient(): MongoClient = mongoClient() - - @Bean - fun mongoClient(): MongoClient = MongoClients.create() - - override fun getDatabaseName(): String = "mongoDatabase" - - @Bean - override fun reactiveMongoTemplate(): ReactiveMongoTemplate = ReactiveMongoTemplate(mongoClient(), databaseName) -} diff --git a/spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt b/spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt deleted file mode 100644 index 6fa3118d8f..0000000000 --- a/spring-5-data-reactive/src/main/kotlin/com/baeldung/SendEmitter.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung - -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.RequestParam -import org.springframework.web.bind.annotation.RestController -import java.util.* - - -@RestController -class SendEmitter(val eventRepository: EventRepository) { - - @GetMapping(value = "/save", produces = arrayOf(MediaType.TEXT_EVENT_STREAM_VALUE)) - fun executeExample(@RequestParam("eventName") eventName: String) = - eventRepository.save(Event(UUID.randomUUID().toString(), eventName)).flux() -} diff --git a/spring-5-data-reactive/src/main/resources/static/index.html b/spring-5-data-reactive/src/main/resources/static/index.html deleted file mode 100644 index a0b8f6f884..0000000000 --- a/spring-5-data-reactive/src/main/resources/static/index.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - -
- - -
- - - -
- - - - diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index aff8bb227c..edb6cec455 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -3,7 +3,6 @@ This module contains articles about Spring 5 model-view-controller (MVC) pattern ### Relevant Articles: -- [Spring Boot and Kotlin](https://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Interface Driven Controllers in Spring](https://www.baeldung.com/spring-interface-driven-controllers) - [Returning Plain HTML From a Spring MVC Controller](https://www.baeldung.com/spring-mvc-return-html) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 0bb69d8057..39fcd22824 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,22 +42,6 @@ org.slf4j jcl-over-slf4j - - - org.jetbrains.kotlin - kotlin-stdlib-jre8 - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-reflect - ${kotlin.version} - - - com.fasterxml.jackson.module - jackson-module-kotlin - ${jackson.version} - org.springframework.boot @@ -103,77 +87,11 @@ org.springframework.boot spring-boot-maven-plugin
- - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - spring - - ${java.version} - - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - generate-sources - - add-source - - - - ${basedir}/src/main/java - ${basedir}/src/main/kotlin - - - - - test-compile - test-compile - - add-test-source - - - - ${basedir}/src/test/java - ${basedir}/src/test/kotlin - - - - - 2.9.0 - 1.2.71 4.5.8 com.baeldung.Spring5Application 0.18 diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloController.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloController.kt deleted file mode 100644 index 69be7dac7e..0000000000 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloController.kt +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.springbootkotlin - -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.RestController - -@RestController -class HelloController(val helloService: HelloService) { - - @GetMapping("/hello") - fun helloKotlin(): String { - return "hello world" - } - - @GetMapping("/hello-service") - fun helloKotlinService(): String { - return helloService.getHello() - } - - @GetMapping("/hello-dto") - fun helloDto(): HelloDto { - return HelloDto("Hello from the dto") - } -} \ No newline at end of file diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloDto.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloDto.kt deleted file mode 100644 index f61c101f0f..0000000000 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloDto.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.springbootkotlin - -data class HelloDto(val greeting: String) diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloService.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloService.kt deleted file mode 100644 index 67791a0c2d..0000000000 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/HelloService.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.springbootkotlin - -import org.springframework.stereotype.Service - -@Service -class HelloService { - - fun getHello(): String { - return "hello service" - } -} \ No newline at end of file diff --git a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt b/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt deleted file mode 100644 index 8904d8d805..0000000000 --- a/spring-5-mvc/src/main/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplication.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.springbootkotlin - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration - -@SpringBootApplication(scanBasePackages = arrayOf("com.baeldung.springbootkotlin"), exclude = arrayOf(SecurityAutoConfiguration::class)) -class KotlinDemoApplication - -fun main(args: Array) { - SpringApplication.run(KotlinDemoApplication::class.java, *args) -} diff --git a/spring-5-mvc/src/test/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplicationIntegrationTest.kt b/spring-5-mvc/src/test/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplicationIntegrationTest.kt deleted file mode 100644 index d0667177c8..0000000000 --- a/spring-5-mvc/src/test/kotlin/com/baeldung/springbootkotlin/KotlinDemoApplicationIntegrationTest.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.springbootkotlin - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNotNull -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.boot.test.web.client.TestRestTemplate -import org.springframework.http.HttpStatus -import org.springframework.test.context.junit4.SpringRunner - -@RunWith(SpringRunner::class) -@SpringBootTest( - classes = arrayOf(KotlinDemoApplication::class), - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class KotlinDemoApplicationIntegrationTest { - - @Autowired - lateinit var testRestTemplate: TestRestTemplate - - @Test - fun whenCalled_thenShouldReturnHello() { - val result = testRestTemplate.withBasicAuth("user", "pass") - .getForEntity("/hello", String::class.java) - - assertNotNull(result) - assertEquals(HttpStatus.OK, result?.statusCode) - assertEquals("hello world", result?.body) - } - - @Test - fun whenCalled_thenShouldReturnHelloService() { - val result = testRestTemplate.withBasicAuth("user", "pass") - .getForEntity("/hello-service", String::class.java) - - assertNotNull(result) - assertEquals(HttpStatus.OK, result?.statusCode) - assertEquals(result?.body, "hello service") - } - - @Test - fun whenCalled_thenShouldReturnJson() { - val result = testRestTemplate.withBasicAuth("user", "pass") - .getForEntity("/hello-dto", HelloDto::class.java) - - assertNotNull(result) - assertEquals(HttpStatus.OK, result?.statusCode) - assertEquals(result?.body, HelloDto("Hello from the dto")) - } - -} diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 622a5c0f42..44b3e28291 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -49,7 +49,6 @@ spring-boot-libraries spring-boot-libraries-2 spring-boot-logging-log4j2 - spring-boot-kotlin spring-boot-mvc spring-boot-mvc-2 spring-boot-mvc-3 diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index faaee0962e..bf7e4abb76 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -4,4 +4,4 @@ This module contains articles about Spring Boot customization 2 ### Relevant Articles: - - [DispatcherServlet and web.xml in Spring Boot](https://www.baeldung.com/) + - [DispatcherServlet and web.xml in Spring Boot](https://www.baeldung.com/spring-boot-dispatcherservlet-web-xml) diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AppStartupRunner.java similarity index 99% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AppStartupRunner.java index 0495473704..0ba719d32b 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AppStartupRunner.java @@ -8,6 +8,7 @@ import org.springframework.stereotype.Component; @Component public class AppStartupRunner implements ApplicationRunner { + private static final Logger LOG = LoggerFactory.getLogger(AppStartupRunner.class); public static int counter; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java similarity index 99% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java index 48c5225cf1..bdedbbe94c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java @@ -7,6 +7,7 @@ import org.springframework.stereotype.Component; @Component public class CommandLineAppStartupRunner implements CommandLineRunner { + private static final Logger LOG = LoggerFactory.getLogger(CommandLineAppStartupRunner.class); public static int counter; @@ -15,4 +16,4 @@ public class CommandLineAppStartupRunner implements CommandLineRunner { LOG.info("Increment counter"); counter++; } -} \ No newline at end of file +} diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java index ad6492dadc..27c903955a 100644 --- a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java @@ -1,9 +1,15 @@ package com.baeldung.startup; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.baeldung.startup") public class SpringStartupConfig { + + @Bean(initMethod="init") + public InitMethodExampleBean initMethodExampleBean() { + return new InitMethodExampleBean(); + } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java index b58c093c31..ac2b98da6f 100644 --- a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java @@ -37,6 +37,11 @@ public class SpringStartupIntegrationTest { ctx.getBean(InitializingBeanExampleBean.class); } + @Test + public void whenInitMethod_shouldLogEnv() throws Exception { + ctx.getBean(InitMethodExampleBean.class); + } + @Test public void whenApplicationListener_shouldRunOnce() throws Exception { Assertions.assertThat(StartupApplicationListenerExample.counter).isEqualTo(1); diff --git a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java index 3dfd4835df..67b430fced 100644 --- a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java @@ -15,7 +15,7 @@ public class SpringStartupXMLConfigIntegrationTest { private ApplicationContext ctx; @Test - public void whenPostConstruct_shouldLogEnv() throws Exception { + public void whenInitMethod_shouldLogEnv() throws Exception { ctx.getBean(InitMethodExampleBean.class); } diff --git a/spring-boot-modules/spring-boot-kotlin/README.md b/spring-boot-modules/spring-boot-kotlin/README.md deleted file mode 100644 index fb91fdee15..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Spring Boot Kotlin - -This module contains articles about Kotlin in Spring Boot projects. - -### Relevant Articles: -- [Non-blocking Spring Boot with Kotlin Coroutines](https://www.baeldung.com/spring-boot-kotlin-coroutines) diff --git a/spring-boot-modules/spring-boot-kotlin/pom.xml b/spring-boot-modules/spring-boot-kotlin/pom.xml deleted file mode 100644 index 7ee048546a..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/pom.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - 4.0.0 - spring-boot-kotlin - spring-boot-kotlin - jar - Demo project showing how to use non-blocking in Kotlin with Spring Boot - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../../parent-kotlin - - - - - org.jetbrains.kotlin - kotlin-reflect - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - org.jetbrains.kotlinx - kotlinx-coroutines-core - ${kotlinx-coroutines.version} - - - org.jetbrains.kotlinx - kotlinx-coroutines-reactor - ${kotlinx-coroutines.version} - - - org.springframework.boot - spring-boot-starter-webflux - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - org.springframework.data - spring-data-r2dbc - ${r2dbc.version} - - - io.r2dbc - r2dbc-h2 - ${h2-r2dbc.version} - - - io.r2dbc - r2dbc-spi - ${r2dbc-spi.version} - - - org.springframework.boot - spring-boot-starter-test - test - - - junit - junit - - - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - io.projectreactor - reactor-test - test - - - - - - - org.jetbrains.kotlin - kotlin-maven-plugin - - - -Xjsr305=strict - - - spring - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - - - - 1.3.31 - 1.0.0.RELEASE - 0.8.2.RELEASE - 0.8.4.RELEASE - 1.2.1 - - - diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt deleted file mode 100644 index 23af4fe90b..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/SpringApplication.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.nonblockingcoroutines - -import org.springframework.boot.SpringApplication.run -import org.springframework.boot.autoconfigure.SpringBootApplication - -@SpringBootApplication -class SpringApplication - -fun main(args: Array) { - run(SpringApplication::class.java, *args) -} diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt deleted file mode 100644 index 52ef8a708b..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/DatastoreConfig.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.nonblockingcoroutines.config - -import io.r2dbc.h2.H2ConnectionConfiguration -import io.r2dbc.h2.H2ConnectionFactory -import io.r2dbc.spi.ConnectionFactory -import org.springframework.beans.factory.annotation.Value -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration -import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories - -@Configuration -@EnableR2dbcRepositories -class DatastoreConfig : AbstractR2dbcConfiguration() { - @Value("\${spring.datasource.username}") - private val userName: String = "" - - @Value("\${spring.datasource.password}") - private val password: String = "" - - @Value("\${spring.datasource.dbname}") - private val dbName: String = "" - - @Bean - override fun connectionFactory(): ConnectionFactory { - return H2ConnectionFactory(H2ConnectionConfiguration.builder() - .inMemory(dbName) - .username(userName) - .password(password) - .build()) - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt deleted file mode 100644 index bda1d26278..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/RouterConfiguration.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.nonblockingcoroutines.config - -import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler -import kotlinx.coroutines.FlowPreview -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.web.reactive.function.server.coRouter - -@Configuration -class RouterConfiguration { - - @FlowPreview - @Bean - fun productRoutes(productsHandler: ProductsHandler) = coRouter { - GET("/", productsHandler::findAll) - GET("/{id}", productsHandler::findOne) - GET("/{id}/stock", productsHandler::findOneInStock) - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt deleted file mode 100644 index 85938b8be2..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/config/WebClientConfiguration.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.nonblockingcoroutines.config - -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.web.reactive.function.client.WebClient - -@Configuration -class WebClientConfiguration { - - @Bean - fun webClient() = WebClient.builder().baseUrl("http://localhost:8080").build() -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt deleted file mode 100644 index 91b091859a..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductController.kt +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.nonblockingcoroutines.controller - -import com.baeldung.nonblockingcoroutines.model.Product -import com.baeldung.nonblockingcoroutines.repository.ProductRepository -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.reactive.function.client.WebClient -import org.springframework.web.reactive.function.client.bodyToMono -import reactor.core.publisher.Flux -import reactor.core.publisher.Mono - -class ProductController { - @Autowired - lateinit var webClient: WebClient - @Autowired - lateinit var productRepository: ProductRepository - - @GetMapping("/{id}") - fun findOne(@PathVariable id: Int): Mono { - return productRepository - .getProductById(id) - } - - @GetMapping("/{id}/stock") - fun findOneInStock(@PathVariable id: Int): Mono { - val product = productRepository.getProductById(id) - - val stockQuantity = webClient.get() - .uri("/stock-service/product/$id/quantity") - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono() - return product.zipWith(stockQuantity) { productInStock, stockQty -> - ProductStockView(productInStock, stockQty) - } - } - - @GetMapping("/stock-service/product/{id}/quantity") - fun getStockQuantity(): Mono { - return Mono.just(2) - } - - @GetMapping("/") - fun findAll(): Flux { - return productRepository.getAllProducts() - } -} diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt deleted file mode 100644 index 464ed2773a..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductControllerCoroutines.kt +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.nonblockingcoroutines.controller - -import com.baeldung.nonblockingcoroutines.model.Product -import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.async -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.flow.Flow -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType.APPLICATION_JSON -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.reactive.function.client.WebClient -import org.springframework.web.reactive.function.client.awaitBody - -class ProductControllerCoroutines { - @Autowired - lateinit var webClient: WebClient - - @Autowired - lateinit var productRepository: ProductRepositoryCoroutines - - @GetMapping("/{id}") - suspend fun findOne(@PathVariable id: Int): Product? { - return productRepository.getProductById(id) - } - - @GetMapping("/{id}/stock") - suspend fun findOneInStock(@PathVariable id: Int): ProductStockView = coroutineScope { - val product: Deferred = async(start = CoroutineStart.LAZY) { - productRepository.getProductById(id) - } - val quantity: Deferred = async(start = CoroutineStart.LAZY) { - webClient.get() - .uri("/stock-service/product/$id/quantity") - .accept(APPLICATION_JSON) - .retrieve().awaitBody() - } - ProductStockView(product.await()!!, quantity.await()) - } - - @FlowPreview - @GetMapping("/") - fun findAll(): Flow { - return productRepository.getAllProducts() - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt deleted file mode 100644 index 44611fd1de..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/controller/ProductStockView.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.nonblockingcoroutines.controller - -import com.baeldung.nonblockingcoroutines.model.Product - -class ProductStockView(product: Product, var stockQuantity: Int) { - var id: Int = 0 - var name: String = "" - var price: Float = 0.0f - - init { - this.id = product.id - this.name = product.name - this.price = product.price - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt deleted file mode 100644 index e05b718e64..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/handlers/ProductsHandler.kt +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.nonblockingcoroutines.handlers - -import com.baeldung.nonblockingcoroutines.controller.ProductStockView -import com.baeldung.nonblockingcoroutines.model.Product -import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.async -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.stereotype.Component -import org.springframework.web.reactive.function.client.WebClient -import org.springframework.web.reactive.function.client.awaitBody -import org.springframework.web.reactive.function.server.ServerRequest -import org.springframework.web.reactive.function.server.ServerResponse -import org.springframework.web.reactive.function.server.bodyAndAwait -import org.springframework.web.reactive.function.server.json - -@Component -class ProductsHandler( - @Autowired var webClient: WebClient, - @Autowired var productRepository: ProductRepositoryCoroutines) { - - @FlowPreview - suspend fun findAll(request: ServerRequest): ServerResponse = - ServerResponse.ok().json().bodyAndAwait(productRepository.getAllProducts()) - - suspend fun findOneInStock(request: ServerRequest): ServerResponse { - val id = request.pathVariable("id").toInt() - - val product: Deferred = GlobalScope.async { - productRepository.getProductById(id) - } - val quantity: Deferred = GlobalScope.async { - webClient.get() - .uri("/stock-service/product/$id/quantity") - .accept(MediaType.APPLICATION_JSON) - .retrieve().awaitBody() - } - return ServerResponse.ok().json().bodyAndAwait(ProductStockView(product.await()!!, quantity.await())) - } - - suspend fun findOne(request: ServerRequest): ServerResponse { - val id = request.pathVariable("id").toInt() - return ServerResponse.ok().json().bodyAndAwait(productRepository.getProductById(id)!!) - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt deleted file mode 100644 index c6dcbdc9c4..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/model/Product.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.nonblockingcoroutines.model - -data class Product( - var id: Int = 0, - var name: String = "", - var price: Float = 0.0f -) diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt deleted file mode 100644 index 64ffd014ad..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepository.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.nonblockingcoroutines.repository - -import com.baeldung.nonblockingcoroutines.model.Product -import org.springframework.data.r2dbc.core.DatabaseClient -import org.springframework.stereotype.Repository -import reactor.core.publisher.Flux -import reactor.core.publisher.Mono - -@Repository -class ProductRepository(private val client: DatabaseClient) { - - fun getProductById(id: Int): Mono { - return client.execute("SELECT * FROM products WHERE id = $1") - .bind(0, id) - .`as`(Product::class.java) - .fetch() - .one() - } - - fun addNewProduct(name: String, price: Float): Mono { - return client.execute("INSERT INTO products (name, price) VALUES($1, $2)") - .bind(0, name) - .bind(1, price) - .then() - } - - fun getAllProducts(): Flux { - return client.select().from("products") - .`as`(Product::class.java) - .fetch() - .all() - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt b/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt deleted file mode 100644 index f2667ec033..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/kotlin/com/baeldung/nonblockingcoroutines/repository/ProductRepositoryCoroutines.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.nonblockingcoroutines.repository - - -import com.baeldung.nonblockingcoroutines.model.Product -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.reactive.awaitFirstOrNull -import kotlinx.coroutines.reactive.flow.asFlow -import org.springframework.data.r2dbc.core.DatabaseClient -import org.springframework.stereotype.Repository - -@Repository -class ProductRepositoryCoroutines(private val client: DatabaseClient) { - - suspend fun getProductById(id: Int): Product? = - client.execute("SELECT * FROM products WHERE id = $1") - .bind(0, id) - .`as`(Product::class.java) - .fetch() - .one() - .awaitFirstOrNull() - - suspend fun addNewProduct(name: String, price: Float) = - client.execute("INSERT INTO products (name, price) VALUES($1, $2)") - .bind(0, name) - .bind(1, price) - .then() - .awaitFirstOrNull() - - @FlowPreview - fun getAllProducts(): Flow = - client.select() - .from("products") - .`as`(Product::class.java) - .fetch() - .all() - .log() - .asFlow() -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/resources/application.properties b/spring-boot-modules/spring-boot-kotlin/src/main/resources/application.properties deleted file mode 100644 index 0f84ff2d75..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -logging.level.org.springframework.data.r2dbc=DEBUG -logging.level.org.springframework.web.reactive.function.client.ExchangeFunctions=TRACE -spring.http.log-request-details=true -spring.h2.console.enabled=true -spring.datasource.username=sa -spring.datasource.url=jdbc:h2:mem:testdb -spring.datasource.password= -spring.datasource.dbname=testdb \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-kotlin/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt b/spring-boot-modules/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt deleted file mode 100644 index 53b1d50f21..0000000000 --- a/spring-boot-modules/spring-boot-kotlin/src/test/kotlin/com/baeldung/nonblockingcoroutines/ProductHandlerTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.nonblockingcoroutines - -import com.baeldung.nonblockingcoroutines.config.RouterConfiguration -import com.baeldung.nonblockingcoroutines.handlers.ProductsHandler -import com.baeldung.nonblockingcoroutines.model.Product -import com.baeldung.nonblockingcoroutines.repository.ProductRepositoryCoroutines -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.reactive.flow.asFlow -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.BDDMockito.given -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration -import org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration -import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest -import org.springframework.boot.test.mock.mockito.MockBean -import org.springframework.test.context.junit4.SpringRunner -import org.springframework.test.web.reactive.server.WebTestClient -import org.springframework.test.web.reactive.server.expectBodyList -import org.springframework.web.reactive.function.client.WebClient -import reactor.core.publisher.Flux -import org.springframework.test.context.ContextConfiguration - -@WebFluxTest( - excludeAutoConfiguration = [ReactiveUserDetailsServiceAutoConfiguration::class, ReactiveSecurityAutoConfiguration::class] -) -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [ProductsHandler::class, RouterConfiguration::class]) -class ProductHandlerTest { - - @Autowired - private lateinit var client: WebTestClient - - @MockBean - private lateinit var webClient: WebClient - - @MockBean - private lateinit var productsRepository: ProductRepositoryCoroutines - - - @FlowPreview - @Test - public fun `get all products`() { - val productsFlow = Flux.just( - Product(1, "product1", 1000.0F), - Product(2, "product2", 2000.0F), - Product(3, "product3", 3000.0F) - ).asFlow() - given(productsRepository.getAllProducts()).willReturn(productsFlow) - client.get() - .uri("/") - .exchange() - .expectStatus() - .isOk - .expectBodyList() - } - -} diff --git a/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java index b57a64a8c6..38f857b42e 100644 --- a/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java @@ -1,16 +1,5 @@ package com.baeldung.classpathfileaccess; -import static org.junit.Assert.assertEquals; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.file.Files; -import java.util.stream.Collectors; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -24,6 +13,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.util.ResourceUtils; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; + /** * Test class illustrating various methods of accessing a file from the classpath using Resource. * @author tritty @@ -55,7 +55,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceLoader_thenReadSuccessful() throws IOException { - final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); + final Resource resource = loadEmployeesWithResourceLoader(); final String employees = new String(Files.readAllBytes(resource.getFile() .toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); @@ -63,7 +63,7 @@ public class SpringResourceIntegrationTest { @Test public void whenApplicationContext_thenReadSuccessful() throws IOException { - final Resource resource = appContext.getResource("classpath:data/employees.dat"); + final Resource resource = loadEmployeesWithApplicationContext(); final String employees = new String(Files.readAllBytes(resource.getFile() .toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); @@ -85,7 +85,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceAsStream_thenReadSuccessful() throws IOException { - final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); + final InputStream resource = loadEmployeesWithClassPathResource().getInputStream(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { final String employees = reader.lines() .collect(Collectors.joining("\n")); @@ -95,7 +95,7 @@ public class SpringResourceIntegrationTest { @Test public void whenResourceAsFile_thenReadSuccessful() throws IOException { - final File resource = new ClassPathResource("data/employees.dat").getFile(); + final File resource = loadEmployeesWithClassPathResource().getFile(); final String employees = new String(Files.readAllBytes(resource.toPath())); assertEquals(EMPLOYEES_EXPECTED, employees); } @@ -114,7 +114,19 @@ public class SpringResourceIntegrationTest { assertEquals(EMPLOYEES_EXPECTED, employees); } - public File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { + private File loadEmployeesWithSpringInternalClass() throws FileNotFoundException { return ResourceUtils.getFile("classpath:data/employees.dat"); } + + private Resource loadEmployeesWithClassPathResource(){ + return new ClassPathResource("data/employees.dat"); + } + + private Resource loadEmployeesWithResourceLoader(){ + return resourceLoader.getResource("classpath:data/employees.dat"); + } + + private Resource loadEmployeesWithApplicationContext(){ + return appContext.getResource("classpath:data/employees.dat"); + } } diff --git a/spring-kafka/README.md b/spring-kafka/README.md index f2fecde894..ddb086c3bd 100644 --- a/spring-kafka/README.md +++ b/spring-kafka/README.md @@ -5,6 +5,7 @@ This module contains articles about Spring with Kafka ### Relevant articles - [Intro to Apache Kafka with Spring](https://www.baeldung.com/spring-kafka) +- [Testing Kafka and Spring Boot](https://www.baeldung.com/spring-boot-kafka-testing) ### Intro diff --git a/spring-mvc-kotlin/.gitignore b/spring-mvc-kotlin/.gitignore deleted file mode 100644 index 416395ffea..0000000000 --- a/spring-mvc-kotlin/.gitignore +++ /dev/null @@ -1 +0,0 @@ -transaction.log \ No newline at end of file diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md deleted file mode 100644 index 590c627cb6..0000000000 --- a/spring-mvc-kotlin/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Spring MVC with Kotlin - -This module contains articles about Spring MVC with Kotlin - -### Relevant articles -- [Spring MVC Setup with Kotlin](https://www.baeldung.com/spring-mvc-kotlin) -- [Working with Kotlin and JPA](https://www.baeldung.com/kotlin-jpa) -- [Kotlin-allopen and Spring](https://www.baeldung.com/kotlin-allopen-spring) -- [MockMvc Kotlin DSL](https://www.baeldung.com/mockmvc-kotlin-dsl) diff --git a/spring-mvc-kotlin/pom.xml b/spring-mvc-kotlin/pom.xml deleted file mode 100644 index 30d2c32ecf..0000000000 --- a/spring-mvc-kotlin/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - spring-mvc-kotlin - spring-mvc-kotlin - war - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-json - - - org.thymeleaf - thymeleaf - - - org.thymeleaf - thymeleaf-spring4 - ${thymeleaf.version} - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-testing - test - - - com.h2database - h2 - test - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - kotlin-maven-plugin - org.jetbrains.kotlin - ${kotlin.version} - - - spring - jpa - - - - - org.jetbrains.kotlin - kotlin-maven-noarg - ${kotlin.version} - - - - - - - - 3.0.7.RELEASE - - - \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt deleted file mode 100644 index 5d0a3e13bf..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/allopen/SimpleConfiguration.kt +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.kotlin.allopen - -import org.springframework.context.annotation.Configuration - -@Configuration -class SimpleConfiguration { -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt deleted file mode 100644 index 2b2a2bd6d9..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/Person.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.kotlin.jpa - -import javax.persistence.CascadeType -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.GenerationType -import javax.persistence.Id -import javax.persistence.OneToMany - -@Entity -data class Person @JvmOverloads constructor( - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - val id: Int, - @Column(nullable = false) - val name: String, - @Column(nullable = true) - val email: String? = null, - @OneToMany(cascade = [CascadeType.ALL]) - val phoneNumbers: List? = null) diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt deleted file mode 100644 index 734e8b4cc4..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/jpa/PhoneNumber.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.kotlin.jpa - -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.GenerationType -import javax.persistence.Id - -@Entity -data class PhoneNumber( - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - val id: Int, - @Column(nullable = false) - val number: String) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt deleted file mode 100644 index 68ab5f31a6..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcController.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.kotlin.mockmvc - -import org.springframework.http.MediaType -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RequestMethod -import org.springframework.web.bind.annotation.RestController - -@RestController -@RequestMapping("/mockmvc") -class MockMvcController { - - @RequestMapping(value = ["/validate"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) - fun validate(@RequestBody request: Request): Response { - val error = if (request.name.first == "admin") { - null - } else { - ERROR - } - return Response(error) - } - - companion object { - const val ERROR = "invalid user" - } -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt deleted file mode 100644 index 3231b6f186..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mockmvc/MockMvcModel.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.kotlin.mockmvc - -import com.fasterxml.jackson.annotation.JsonInclude - -data class Name(val first: String, val last: String) - -data class Request(val name: Name) - -@JsonInclude(JsonInclude.Include.NON_NULL) -data class Response(val error: String?) \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt deleted file mode 100644 index 23aadf282a..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.kotlin.mvc - -import org.springframework.context.ApplicationContext -import org.springframework.context.ApplicationContextAware -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.web.servlet.config.annotation.EnableWebMvc -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter -import org.thymeleaf.spring4.SpringTemplateEngine -import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver -import org.thymeleaf.spring4.view.ThymeleafViewResolver -import org.thymeleaf.templatemode.TemplateMode - -@EnableWebMvc -@Configuration -open class ApplicationWebConfig : WebMvcConfigurerAdapter(), ApplicationContextAware { - - private var applicationContext: ApplicationContext? = null - - override fun setApplicationContext(applicationContext: ApplicationContext?) { - this.applicationContext = applicationContext - } - - override fun addViewControllers(registry: ViewControllerRegistry?) { - super.addViewControllers(registry) - - registry!!.addViewController("/welcome.html") - } - - @Bean - open fun templateResolver(): SpringResourceTemplateResolver { - return SpringResourceTemplateResolver() - .apply { prefix = "/WEB-INF/view/" } - .apply { suffix = ".html"} - .apply { templateMode = TemplateMode.HTML } - .apply { setApplicationContext(applicationContext) } - } - - @Bean - open fun templateEngine(): SpringTemplateEngine { - return SpringTemplateEngine() - .apply { setTemplateResolver(templateResolver()) } - } - - @Bean - open fun viewResolver(): ThymeleafViewResolver { - return ThymeleafViewResolver() - .apply { templateEngine = templateEngine() } - .apply { order = 1 } - } -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt b/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt deleted file mode 100644 index 4c1a35823c..0000000000 --- a/spring-mvc-kotlin/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebInitializer.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.kotlin.mvc - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer - -class ApplicationWebInitializer : AbstractAnnotationConfigDispatcherServletInitializer() { - - override fun getRootConfigClasses(): Array>? { - return null - } - - override fun getServletMappings(): Array { - return arrayOf("/") - } - - override fun getServletConfigClasses(): Array> { - return arrayOf(ApplicationWebConfig::class.java) - } -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/resources/logback.xml b/spring-mvc-kotlin/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-mvc-kotlin/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml deleted file mode 100644 index c7f110ea94..0000000000 --- a/spring-mvc-kotlin/src/main/webapp/WEB-INF/spring-web-config.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp deleted file mode 100644 index 3f68f128bc..0000000000 --- a/spring-mvc-kotlin/src/main/webapp/WEB-INF/view/welcome.jsp +++ /dev/null @@ -1,7 +0,0 @@ - - Welcome - - -

This is the body of the welcome view

- - \ No newline at end of file diff --git a/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml b/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml deleted file mode 100755 index cbee6a1b11..0000000000 --- a/spring-mvc-kotlin/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - Spring Kotlin MVC Application - - - spring-web-mvc - org.springframework.web.servlet.DispatcherServlet - 1 - - contextConfigLocation - /WEB-INF/spring-web-config.xml - - - - - spring-web-mvc - / - - - \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt deleted file mode 100644 index 65a60c7157..0000000000 --- a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.kotlin.allopen - -import org.junit.Test -import org.junit.runner.RunWith -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner -import org.springframework.test.context.support.AnnotationConfigContextLoader - -@RunWith(SpringJUnit4ClassRunner::class) -@ContextConfiguration( - loader = AnnotationConfigContextLoader::class, - classes = arrayOf(SimpleConfiguration::class)) -class SimpleConfigurationTest { - - @Test - fun contextLoads() { - } - -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt deleted file mode 100644 index adac9d0cbf..0000000000 --- a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/jpa/HibernateKotlinIntegrationTest.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.kotlin.jpa - -import org.hibernate.cfg.Configuration -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase -import org.hibernate.testing.transaction.TransactionUtil.doInHibernate -import org.junit.Assert.assertTrue -import org.junit.Test -import java.io.IOException -import java.util.* - - -class HibernateKotlinIntegrationTest : BaseCoreFunctionalTestCase() { - - private val properties: Properties - @Throws(IOException::class) - get() { - val properties = Properties() - properties.load(javaClass.classLoader.getResourceAsStream("hibernate.properties")) - return properties - } - - override fun getAnnotatedClasses(): Array> { - return arrayOf(Person::class.java, PhoneNumber::class.java) - } - - override fun configure(configuration: Configuration) { - super.configure(configuration) - configuration.properties = properties - } - - @Test - fun givenPersonWithFullData_whenSaved_thenFound() { - doInHibernate(({ this.sessionFactory() }), { session -> - val personToSave = Person(0, "John", "jhon@test.com", Arrays.asList(PhoneNumber(0, "202-555-0171"), PhoneNumber(0, "202-555-0102"))) - session.persist(personToSave) - val personFound = session.find(Person::class.java, personToSave.id) - session.refresh(personFound) - - assertTrue(personToSave == personFound) - }) - } - - @Test - fun givenPerson_whenSaved_thenFound() { - doInHibernate(({ this.sessionFactory() }), { session -> - val personToSave = Person(0, "John") - session.persist(personToSave) - val personFound = session.find(Person::class.java, personToSave.id) - session.refresh(personFound) - - assertTrue(personToSave == personFound) - }) - } - - @Test - fun givenPersonWithNullFields_whenSaved_thenFound() { - doInHibernate(({ this.sessionFactory() }), { session -> - val personToSave = Person(0, "John", null, null) - session.persist(personToSave) - val personFound = session.find(Person::class.java, personToSave.id) - session.refresh(personFound) - - assertTrue(personToSave == personFound) - }) - } -} \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt b/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt deleted file mode 100644 index 802cd4c1e7..0000000000 --- a/spring-mvc-kotlin/src/test/kotlin/com/baeldung/kotlin/mockmvc/MockMvcControllerTest.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.kotlin.mockmvc - -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.Test -import org.junit.runner.RunWith -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest -import org.springframework.http.MediaType -import org.springframework.http.ResponseEntity.status -import org.springframework.test.context.junit4.SpringRunner -import org.springframework.test.web.servlet.MockMvc -import org.springframework.test.web.servlet.post -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders -import org.springframework.test.web.servlet.result.MockMvcResultHandlers -import org.springframework.test.web.servlet.result.MockMvcResultMatchers - -@RunWith(SpringRunner::class) -@WebMvcTest -class MockMvcControllerTest { - - @Autowired lateinit var mockMvc: MockMvc - @Autowired lateinit var mapper: ObjectMapper - - @Test - fun `when supported user is given then raw MockMvc-based validation is successful`() { - mockMvc.perform(MockMvcRequestBuilders - .post("/mockmvc/validate") - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content(mapper.writeValueAsString(Request(Name("admin", ""))))) - .andExpect(MockMvcResultMatchers.status().isOk) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.content().string("{}")) - } - - @Test - fun `when supported user is given then kotlin DSL-based validation is successful`() { - doTest(Request(Name("admin", "")), Response(null)) - } - - @Test - fun `when unsupported user is given then validation is failed`() { - doTest(Request(Name("some-name", "some-surname")), Response(MockMvcController.ERROR)) - } - - private fun doTest(input: Request, expectation: Response) { - mockMvc.post("/mockmvc/validate") { - contentType = MediaType.APPLICATION_JSON - content = mapper.writeValueAsString(input) - accept = MediaType.APPLICATION_JSON - }.andExpect { - status { isOk } - content { contentType(MediaType.APPLICATION_JSON) } - content { json(mapper.writeValueAsString(expectation)) } - } - } -} - -@SpringBootApplication -class MockMvcApplication \ No newline at end of file diff --git a/spring-mvc-kotlin/src/test/resources/hibernate.properties b/spring-mvc-kotlin/src/test/resources/hibernate.properties deleted file mode 100644 index 7b8764637b..0000000000 --- a/spring-mvc-kotlin/src/test/resources/hibernate.properties +++ /dev/null @@ -1,9 +0,0 @@ -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 -hibernate.connection.username=sa -hibernate.connection.autocommit=true -jdbc.password= - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java index 7269f917b4..73132704c8 100644 --- a/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java +++ b/spring-mvc-xml/src/main/java/com/baeldung/jsp/ExampleThree.java @@ -10,11 +10,15 @@ import javax.servlet.http.HttpServletResponse; @WebServlet(name = "ExampleThree", description = "JSP Servlet With Annotations", urlPatterns = { "/ExampleThree" }) public class ExampleThree extends HttpServlet { private static final long serialVersionUID = 1L; + + private String instanceMessage; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = request.getParameter("message"); + instanceMessage = request.getParameter("message"); request.setAttribute("text", message); + request.setAttribute("unsafeText", instanceMessage); request.getRequestDispatcher("/jsp/ExampleThree.jsp").forward(request, response); } } diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md deleted file mode 100644 index d6ce3b7645..0000000000 --- a/spring-reactive-kotlin/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Spring Reactive Kotlin - -This module contains articles about reactive Kotlin - -### Relevant Articles: -- [Spring Webflux with Kotlin](https://www.baeldung.com/spring-webflux-kotlin) -- [Kotlin Reactive Microservice With Spring Boot](https://www.baeldung.com/spring-boot-kotlin-reactive-microservice) diff --git a/spring-reactive-kotlin/pom.xml b/spring-reactive-kotlin/pom.xml deleted file mode 100644 index cbb143f6ec..0000000000 --- a/spring-reactive-kotlin/pom.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - 4.0.0 - spring-reactive-kotlin - spring-reactive-kotlin - Demo project for Spring Boot - - jar - - - com.baeldung - parent-kotlin - 1.0.0-SNAPSHOT - ../parent-kotlin - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-webflux - - - org.springframework.boot.experimental - spring-boot-starter-data-r2dbc - - - org.springframework.boot - spring-boot-starter-actuator - - - io.r2dbc - r2dbc-h2 - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - - org.springframework.boot - spring-boot-starter-test - test - - - io.projectreactor - reactor-test - test - - - - org.springframework.boot.experimental - spring-boot-test-autoconfigure-r2dbc - test - - - io.projectreactor - reactor-test - test - - - - - - - - org.springframework.boot.experimental - spring-boot-bom-r2dbc - 0.1.0.M3 - pom - import - - - - - - src/main/kotlin - src/test/kotlin - - - kotlin-maven-plugin - - - compile - compile - - compile - - - - test-compile - test-compile - - test-compile - - - - org.jetbrains.kotlin - ${kotlin.version} - - - -Xjsr305=strict - - 1.8 - - spring - jpa - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - org.jetbrains.kotlin - kotlin-maven-noarg - ${kotlin.version} - - - - - - - - 1.8 - 1.3.70 - 2.2.5.RELEASE - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - - - - diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt deleted file mode 100644 index c70057b5de..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/HealthTrackerApplication.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.bootmicroservice - -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.runApplication - -@SpringBootApplication -class HealthTrackerApplication - -fun main(args: Array) { - runApplication(*args) -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt deleted file mode 100644 index b14682cc5c..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/config/DBConfiguration.kt +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.bootmicroservice.config; - -import org.springframework.context.annotation.Configuration -import org.springframework.data.r2dbc.core.DatabaseClient - -@Configuration -class DBConfiguration(db: DatabaseClient) { - init { - val initDb = db.execute { - """ CREATE TABLE IF NOT EXISTS profile ( - id SERIAL PRIMARY KEY, - first_name VARCHAR(20) NOT NULL, - last_name VARCHAR(20) NOT NULL, - birth_date DATE NOT NULL - ); - CREATE TABLE IF NOT EXISTS health_record( - id SERIAL PRIMARY KEY, - profile_id LONG NOT NULL, - temperature DECIMAL NOT NULL, - blood_pressure DECIMAL NOT NULL, - heart_rate DECIMAL, - date DATE NOT NULL - ); - """ - } - initDb.then().subscribe() - } -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt deleted file mode 100644 index 620f187b7b..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/HealthRecordController.kt +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.bootmicroservice.controller - -import com.baeldung.bootmicroservice.model.AverageHealthStatus -import com.baeldung.bootmicroservice.model.HealthRecord -import com.baeldung.bootmicroservice.repository.HealthRecordRepository -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.PathVariable -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.RestController -import reactor.core.publisher.Mono - -@RestController -class HealthRecordController(val repository: HealthRecordRepository) { - - @PostMapping("/health/{profileId}/record") - fun storeHealthRecord(@PathVariable("profileId") profileId: Long, @RequestBody record: HealthRecord): Mono = - repository.save(HealthRecord(null - , profileId - , record.temperature - , record.bloodPressure - , record.heartRate - , record.date)) - - @GetMapping("/health/{profileId}/avg") - fun fetchHealthRecordAverage(@PathVariable("profileId") profileId: Long): Mono = - repository.findByProfileId(profileId) - .reduce( - AverageHealthStatus(0, 0.0, 0.0, 0.0) - , { s, r -> - AverageHealthStatus(s.cnt + 1 - , s.temperature + r.temperature - , s.bloodPressure + r.bloodPressure - , s.heartRate + r.heartRate - ) - } - ).map { s -> - AverageHealthStatus(s.cnt - , if (s.cnt != 0) s.temperature / s.cnt else 0.0 - , if (s.cnt != 0) s.bloodPressure / s.cnt else 0.0 - , if (s.cnt != 0) s.heartRate / s.cnt else 0.0) - } - -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt deleted file mode 100644 index 1dc3bcdc50..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/controller/ProfileController.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.bootmicroservice.controller - -import com.baeldung.bootmicroservice.model.Profile -import com.baeldung.bootmicroservice.repository.ProfileRepository -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.RestController -import reactor.core.publisher.Mono - -@RestController -class ProfileController(val repository: ProfileRepository) { - - @PostMapping("/profile") - fun save(@RequestBody profile: Profile): Mono = repository.save(profile) -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt deleted file mode 100644 index 3141146b9c..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/AverageHealthStatus.kt +++ /dev/null @@ -1,3 +0,0 @@ -package com.baeldung.bootmicroservice.model; - -class AverageHealthStatus(var cnt: Int, var temperature: Double, var bloodPressure: Double, var heartRate: Double) diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt deleted file mode 100644 index 71c534027f..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/HealthRecord.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.bootmicroservice.model - -import org.springframework.data.annotation.Id -import org.springframework.data.relational.core.mapping.Table -import java.time.LocalDate - -@Table -data class HealthRecord(@Id var id: Long?, var profileId: Long?, var temperature: Double, var bloodPressure: Double, var heartRate: Double, var date: LocalDate) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt deleted file mode 100644 index cbb7e675ea..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/model/Profile.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.bootmicroservice.model - -import org.springframework.data.annotation.Id -import org.springframework.data.relational.core.mapping.Table -import java.time.LocalDateTime - -@Table -data class Profile(@Id var id:Long?, var firstName : String, var lastName : String, var birthDate: LocalDateTime) \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt deleted file mode 100644 index 8cc91f06e4..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/HealthRecordRepository.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.bootmicroservice.repository - -import com.baeldung.bootmicroservice.model.HealthRecord -import org.springframework.data.r2dbc.repository.Query -import org.springframework.data.repository.reactive.ReactiveCrudRepository -import org.springframework.stereotype.Repository -import reactor.core.publisher.Flux - -@Repository -interface HealthRecordRepository: ReactiveCrudRepository { - @Query("select p.* from health_record p where p.profile_id = :profileId ") - fun findByProfileId(profileId: Long): Flux -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt deleted file mode 100644 index eee8c5fcbe..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/bootmicroservice/repository/ProfileRepository.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.bootmicroservice.repository - -import com.baeldung.bootmicroservice.model.Profile -import org.springframework.data.repository.reactive.ReactiveCrudRepository -import org.springframework.stereotype.Repository - -@Repository -interface ProfileRepository: ReactiveCrudRepository \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt deleted file mode 100644 index 87ac7417b7..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Application.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.springreactivekotlin - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.SpringBootApplication - -@SpringBootApplication -class Application - -fun main(args: Array) { - SpringApplication.run(Application::class.java, *args) -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt deleted file mode 100644 index 76f8a62b85..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Controller.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.springreactivekotlin - -import org.springframework.http.MediaType -import org.springframework.stereotype.Controller -import org.springframework.web.bind.annotation.GetMapping -import org.springframework.web.bind.annotation.ResponseBody -import reactor.core.publisher.Flux - -@Controller -class Controller { - - @GetMapping(path = ["/numbers"], produces = [MediaType.APPLICATION_STREAM_JSON_VALUE]) - @ResponseBody - fun getNumbers(): Flux { - return Flux.range(1, 100) - } - -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt deleted file mode 100644 index 9eb6eb8488..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Device.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.springreactivekotlin - -class Device(val name: String, val reading: Double) { - -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt deleted file mode 100644 index 0ef9f37f1b..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsHandler.kt +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.springreactivekotlin - -import org.springframework.stereotype.Component -import org.springframework.web.reactive.function.BodyInserters.fromObject -import org.springframework.web.reactive.function.server.ServerRequest -import org.springframework.web.reactive.function.server.ServerResponse -import reactor.core.publisher.Mono - -@Component -class HomeSensorsHandler { - - var data = mapOf("lamp" to arrayOf(0.7, 0.65, 0.67), "fridge" to arrayOf(12.0, 11.9, 12.5)) - - fun setLight(request: ServerRequest): Mono = ServerResponse.ok().build() - - fun getLightReading(request: ServerRequest): Mono = - ServerResponse.ok().body(fromObject(data["lamp"]!!)) - - fun getDeviceReadings(request: ServerRequest): Mono { - val id = request.pathVariable("id") - return ServerResponse.ok().body(fromObject(Device(id, 1.0))) - } - - fun getAllDevices(request: ServerRequest): Mono = - ServerResponse.ok().body(fromObject(arrayOf("lamp", "tv"))) - - fun getAllDeviceApi(request: ServerRequest): Mono = - ServerResponse.ok().body(fromObject(arrayListOf("kettle", "fridge"))) - - fun setDeviceReadingApi(request: ServerRequest): Mono { - return request.bodyToMono(Device::class.java).flatMap { it -> - ServerResponse.ok().body(fromObject(Device(it.name.toUpperCase(), it.reading))) - } - } - -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt deleted file mode 100644 index 27d87afd89..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/HomeSensorsRouters.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.springreactivekotlin - -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.http.MediaType.APPLICATION_JSON -import org.springframework.http.MediaType.TEXT_HTML -import org.springframework.web.reactive.function.server.router - -@Configuration -class HomeSensorsRouters(private val handler: HomeSensorsHandler) { - - @Bean - fun roomsRouter() = router { - (accept(TEXT_HTML) and "/room").nest { - GET("/light", handler::getLightReading) - POST("/light", handler::setLight) - } - } - - @Bean - fun deviceRouter() = router { - accept(TEXT_HTML).nest { - (GET("/device/") or GET("/devices/")).invoke(handler::getAllDevices) - GET("/device/{id}", handler::getDeviceReadings) - } - (accept(APPLICATION_JSON) and "/api").nest { - (GET("/device/") or GET("/devices/")).invoke(handler::getAllDeviceApi) - POST("/device/", handler::setDeviceReadingApi) - } - } - -} diff --git a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt b/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt deleted file mode 100644 index 9015fc5df8..0000000000 --- a/spring-reactive-kotlin/src/main/kotlin/com/baeldung/springreactivekotlin/Routes.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.springreactivekotlin - -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.web.reactive.function.server.ServerResponse -import org.springframework.web.reactive.function.server.router - -import org.springframework.web.reactive.function.BodyInserters.fromObject - -@Configuration -class SimpleRoute { - @Bean - fun route() = router { - GET("/route") { _ -> ServerResponse.ok().body(fromObject(arrayOf(1, 2, 3))) } - } -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/application.yml b/spring-reactive-kotlin/src/main/resources/application.yml deleted file mode 100644 index d75683f905..0000000000 --- a/spring-reactive-kotlin/src/main/resources/application.yml +++ /dev/null @@ -1 +0,0 @@ -management.endpoints.web.exposure.include: health,metrics \ No newline at end of file diff --git a/spring-reactive-kotlin/src/main/resources/logback.xml b/spring-reactive-kotlin/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-reactive-kotlin/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt b/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt deleted file mode 100644 index ba640070e3..0000000000 --- a/spring-reactive-kotlin/src/test/kotlin/RoutesTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package veontomo - -import com.baeldung.springreactivekotlin.SimpleRoute -import org.junit.Before -import org.junit.Test -import org.springframework.test.web.reactive.server.WebTestClient - -class RoutesTest { - - lateinit var client: WebTestClient - - @Before - fun init() { - this.client = WebTestClient.bindToRouterFunction(SimpleRoute().route()).build() - } - - - @Test - fun whenRequestToRoute_thenStatusShouldBeOk() { - client.get() - .uri("/route") - .exchange() - .expectStatus().isOk - } - - - @Test - fun whenRequestToRoute_thenBodyShouldContainArray123() { - client.get() - .uri("/route") - .exchange() - .expectBody() - .json("[1, 2, 3]") - } -} \ No newline at end of file diff --git a/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt b/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt deleted file mode 100644 index 51481af3d7..0000000000 --- a/spring-reactive-kotlin/src/test/kotlin/com/baeldung/bootmicroservice/controller/ProfileControllerTest.kt +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.bootmicroservice.controller; - -import com.baeldung.bootmicroservice.model.Profile -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.context.SpringBootTest -import org.springframework.http.MediaType -import org.springframework.test.web.reactive.server.WebTestClient -import java.time.LocalDateTime - -@SpringBootTest -class ProfileControllerTest { - @Autowired - lateinit var controller: ProfileController - - @Autowired - lateinit var mapper: ObjectMapper ; - - lateinit var client: WebTestClient - lateinit var profile: String - - @BeforeEach - fun setup() { - client = WebTestClient.bindToController(controller).build() - profile = mapper.writeValueAsString(Profile(null, "kotlin", "reactive", LocalDateTime.now())) - } - - @Test - fun whenRequestProfile_thenStatusShouldBeOk() { - client.post() - .uri("/profile") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(profile) - .exchange() - .expectStatus().isOk - } - - @Test - fun whenRequestProfile_thenIdShouldBeNotNull() { - client.post() - .uri("/profile") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(profile) - .exchange() - .expectBody() - .jsonPath("$.id") - .isNotEmpty - } -} diff --git a/spring-resttemplate-2/README.md b/spring-resttemplate-2/README.md index 37d8ac9740..aab6a188b6 100644 --- a/spring-resttemplate-2/README.md +++ b/spring-resttemplate-2/README.md @@ -8,4 +8,4 @@ This module contains articles about Spring RestTemplate - [Proxies With RestTemplate](https://www.baeldung.com/java-resttemplate-proxy) - [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type) - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) -- [How to compress requests using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests) +- [How to Compress Requests Using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests) diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 0fc2b49fa7..e32fadd671 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -38,7 +38,6 @@ spring-security-oauth2-sso spring-security-web-thymeleaf spring-security-web-x509 - spring-security-kotlin-dsl diff --git a/spring-security-modules/spring-security-kotlin-dsl/README.md b/spring-security-modules/spring-security-kotlin-dsl/README.md deleted file mode 100644 index 39e521d84e..0000000000 --- a/spring-security-modules/spring-security-kotlin-dsl/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Spring Security with Kotlin DSL](https://www.baeldung.com/kotlin/spring-security-dsl) diff --git a/spring-security-modules/spring-security-kotlin-dsl/pom.xml b/spring-security-modules/spring-security-kotlin-dsl/pom.xml deleted file mode 100644 index 24e99decfb..0000000000 --- a/spring-security-modules/spring-security-kotlin-dsl/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - com.baeldung.spring.security.dsl - spring-security-kotlin-dsl - 1.0 - spring-security-kotlin-dsl - Spring Security Kotlin DSL - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - com.fasterxml.jackson.module - jackson-module-kotlin - - - org.jetbrains.kotlin - kotlin-reflect - - - org.jetbrains.kotlin - kotlin-stdlib-jdk8 - - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - - ${project.basedir}/src/main/kotlin - ${project.basedir}/src/test/kotlin - - - org.springframework.boot - spring-boot-maven-plugin - - - org.jetbrains.kotlin - kotlin-maven-plugin - - - -Xjsr305=strict - - - spring - - - - - org.jetbrains.kotlin - kotlin-maven-allopen - ${kotlin.version} - - - - - - - - 11 - 1.3.72 - - - diff --git a/spring-security-modules/spring-security-kotlin-dsl/src/main/kotlin/com/baeldung/security/kotlin/dsl/SpringSecurityKotlinApplication.kt b/spring-security-modules/spring-security-kotlin-dsl/src/main/kotlin/com/baeldung/security/kotlin/dsl/SpringSecurityKotlinApplication.kt deleted file mode 100644 index 27cc41c1e5..0000000000 --- a/spring-security-modules/spring-security-kotlin-dsl/src/main/kotlin/com/baeldung/security/kotlin/dsl/SpringSecurityKotlinApplication.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.security.kotlin.dsl - -import org.springframework.boot.autoconfigure.SpringBootApplication -import org.springframework.boot.runApplication -import org.springframework.context.annotation.Configuration -import org.springframework.context.support.beans -import org.springframework.core.annotation.Order -import org.springframework.security.config.annotation.web.builders.HttpSecurity -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter -import org.springframework.security.config.web.servlet.invoke -import org.springframework.security.core.userdetails.User -import org.springframework.security.provisioning.InMemoryUserDetailsManager -import org.springframework.web.servlet.function.ServerResponse -import org.springframework.web.servlet.function.router - -@EnableWebSecurity -@SpringBootApplication -class SpringSecurityKotlinApplication - -@Order(1) -@Configuration -class AdminSecurityConfiguration : WebSecurityConfigurerAdapter() { - override fun configure(http: HttpSecurity?) { - http { - authorizeRequests { - authorize("/greetings/**", hasAuthority("ROLE_ADMIN")) - } - httpBasic {} - } - } -} - -@Configuration -class BasicSecurityConfiguration : WebSecurityConfigurerAdapter() { - override fun configure(http: HttpSecurity?) { - http { - authorizeRequests { - authorize("/**", permitAll) - } - httpBasic {} - } - } -} - -fun main(args: Array) { - runApplication(*args) { - addInitializers( beans { - bean { - fun user(user: String, password: String, vararg roles: String) = - User - .withDefaultPasswordEncoder() - .username(user) - .password(password) - .roles(*roles) - .build() - - InMemoryUserDetailsManager(user("user", "password", "USER") - , user("admin", "password", "USER", "ADMIN")) - } - - bean { - router { - GET("/greetings") { - request -> request.principal().map { it.name }.map { ServerResponse.ok().body(mapOf("greeting" to "Hello $it")) }.orElseGet { ServerResponse.badRequest().build() } - } - } - } - }) - } -} diff --git a/spring-security-modules/spring-security-kotlin-dsl/src/test/kotlin/com/spring/security/kotlin/dsl/SpringSecurityKotlinApplicationTests.kt b/spring-security-modules/spring-security-kotlin-dsl/src/test/kotlin/com/spring/security/kotlin/dsl/SpringSecurityKotlinApplicationTests.kt deleted file mode 100644 index 3da8110feb..0000000000 --- a/spring-security-modules/spring-security-kotlin-dsl/src/test/kotlin/com/spring/security/kotlin/dsl/SpringSecurityKotlinApplicationTests.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.spring.security.kotlin.dsl - -import org.junit.jupiter.api.Test -import org.junit.runner.RunWith -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc -import org.springframework.boot.test.context.SpringBootTest -import org.springframework.security.test.context.support.WithMockUser -import org.springframework.test.context.junit4.SpringRunner -import org.springframework.test.web.servlet.MockMvc -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.* -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic -import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated -import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated -import org.springframework.test.web.servlet.get -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.* -import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status - -@RunWith(SpringRunner::class) -@SpringBootTest -@AutoConfigureMockMvc -class SpringSecurityKotlinApplicationTests { - - @Autowired - private lateinit var mockMvc: MockMvc - - @Test - fun `ordinary user not permitted to access the endpoint`() { - this.mockMvc - .perform(get("/greetings") - .with(httpBasic("user", "password"))) - .andExpect(unauthenticated()) - } -} diff --git a/spring-security-modules/spring-security-oidc/README.md b/spring-security-modules/spring-security-oidc/README.md index 6a45824fcb..92ba60cad9 100644 --- a/spring-security-modules/spring-security-oidc/README.md +++ b/spring-security-modules/spring-security-oidc/README.md @@ -4,7 +4,6 @@ This module contains articles about OpenID with Spring Security ### Relevant articles -- [Spring Security and OpenID Connect (Legacy)](https://www.baeldung.com/spring-security-openid-connect-legacy) - [Spring Security and OpenID Connect](https://www.baeldung.com/spring-security-openid-connect) ### OpenID Connect with Spring Security diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index c5e94f3afc..f26b0f27ec 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -3,16 +3,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung spring-testing 0.1-SNAPSHOT spring-testing com.baeldung - parent-java + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-java + ../../parent-boot-2 @@ -32,25 +31,23 @@ org.springframework.boot spring-boot-starter - LATEST org.springframework.boot spring-boot-starter-test - LATEST test org.springframework spring-core - LATEST + ${spring.version} org.springframework spring-context - LATEST + ${spring.version} org.springframework @@ -65,7 +62,6 @@ org.springframework.data spring-data-jpa - LATEST org.junit.jupiter @@ -116,9 +112,9 @@ 2.0.0.0 3.1.6 - 5.5.0 - 1.5.2 - 5.1.4.RELEASE + 5.7.0 + 1.7.0 + 5.2.8.RELEASE 4.0.1 2.1.1
diff --git a/testing-modules/testing-libraries-2/pom.xml b/testing-modules/testing-libraries-2/pom.xml index 282583c882..42c84d0da9 100644 --- a/testing-modules/testing-libraries-2/pom.xml +++ b/testing-modules/testing-libraries-2/pom.xml @@ -9,9 +9,16 @@ com.baeldung testing-modules 1.0.0-SNAPSHOT + ../ + + org.assertj + assertj-core + 3.16.1 + test + com.github.stefanbirkner system-rules @@ -24,6 +31,44 @@ ${system-lambda.version} test + + uk.org.webcompere + system-stubs-jupiter + ${system-stubs.version} + test + + + uk.org.webcompere + system-stubs-junit4 + ${system-stubs.version} + test + + + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit.jupiter.version} + test + + + org.junit.jupiter + junit-jupiter-api + ${junit.jupiter.version} + test + @@ -39,5 +84,7 @@ 1.19.0 1.0.0 + 1.1.0 + 5.6.2 diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseJUnit5UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseJUnit5UnitTest.java new file mode 100644 index 0000000000..cb9371bd69 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseJUnit5UnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SystemStubsExtension.class) +class FakeDatabaseJUnit5UnitTest { + + @Test + void useFakeDatabase(FakeDatabaseTestResource fakeDatabase) { + assertThat(fakeDatabase.getDatabaseConnection()).isEqualTo("open"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResource.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResource.java new file mode 100644 index 0000000000..6cb1b1d607 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResource.java @@ -0,0 +1,22 @@ +package com.baeldung.systemstubs; + +import uk.org.webcompere.systemstubs.resource.TestResource; + +public class FakeDatabaseTestResource implements TestResource { + // let's pretend this is a database connection + private String databaseConnection = "closed"; + + @Override + public void setup() throws Exception { + databaseConnection = "open"; + } + + @Override + public void teardown() throws Exception { + databaseConnection = "closed"; + } + + public String getDatabaseConnection() { + return databaseConnection; + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResourceUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResourceUnitTest.java new file mode 100644 index 0000000000..6b8fdcecdd --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/FakeDatabaseTestResourceUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class FakeDatabaseTestResourceUnitTest { + @Nested + class ExecuteAround { + @Test + void theResourceIsClosedToStartWith() throws Exception { + FakeDatabaseTestResource fake = new FakeDatabaseTestResource(); + assertThat(fake.getDatabaseConnection()).isEqualTo("closed"); + + fake.execute(() -> { + assertThat(fake.getDatabaseConnection()).isEqualTo("open"); + }); + } + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsJUnit4UnitTest.java new file mode 100644 index 0000000000..6eaffac7ed --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsJUnit4UnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.systemstubs; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.runners.Enclosed; +import org.junit.runner.RunWith; +import uk.org.webcompere.systemstubs.rules.EnvironmentVariablesRule; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(Enclosed.class) +public class GettingStartedWithSystemStubsJUnit4UnitTest { + public static class SetEnvironmentInsideTest { + @Rule + public EnvironmentVariablesRule environmentVariablesRule = new EnvironmentVariablesRule(); + + @Test + public void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + environmentVariablesRule.set("ENV", "value1"); + + assertThat(System.getenv("ENV")).isEqualTo("value1"); + } + } + + public static class SetEnvironmentAtConstruction { + @Rule + public EnvironmentVariablesRule environmentVariablesRule = + new EnvironmentVariablesRule("ENV", "value1", + "ENV2", "value2"); + + + @Test + public void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + assertThat(System.getenv("ENV")).isEqualTo("value1"); + assertThat(System.getenv("ENV2")).isEqualTo("value2"); + } + } + + public static class SetEnvironmentInBefore { + @Rule + public EnvironmentVariablesRule environmentVariablesRule = + new EnvironmentVariablesRule(); + + @Before + public void before() { + environmentVariablesRule.set("ENV", "value1") + .set("ENV2", "value2"); + } + + + @Test + public void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + assertThat(System.getenv("ENV")).isEqualTo("value1"); + assertThat(System.getenv("ENV2")).isEqualTo("value2"); + } + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsUnitTest.java new file mode 100644 index 0000000000..76fb768d34 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/GettingStartedWithSystemStubsUnitTest.java @@ -0,0 +1,109 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.environment.EnvironmentVariables; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.org.webcompere.systemstubs.SystemStubs.withEnvironmentVariable; +import static uk.org.webcompere.systemstubs.resource.Resources.with; + +class GettingStartedWithSystemStubsUnitTest { + @Nested + @ExtendWith(SystemStubsExtension.class) + class EnvironmentVariablesJUnit5 { + @SystemStub + private EnvironmentVariables environmentVariables; + + @Test + void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + environmentVariables.set("ENV", "value1"); + + assertThat(System.getenv("ENV")).isEqualTo("value1"); + } + } + + @Nested + @ExtendWith(SystemStubsExtension.class) + class EnvironmentVariablesConstructedJUnit5 { + @SystemStub + private EnvironmentVariables environmentVariables = + new EnvironmentVariables("ENV", "value1"); + + @Test + void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + assertThat(System.getenv("ENV")).isEqualTo("value1"); + } + } + + @Nested + @ExtendWith(SystemStubsExtension.class) + class EnvironmentVariablesConstructedWithSetJUnit5 { + @SystemStub + private EnvironmentVariables environmentVariables = + new EnvironmentVariables() + .set("ENV", "value1") + .set("ENV2", "value2"); + + @Test + void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet() { + assertThat(System.getenv("ENV")).isEqualTo("value1"); + } + } + + @Nested + @ExtendWith(SystemStubsExtension.class) + class EnvironmentVariablesJUnit5ParameterInjection { + @Test + void givenEnvironmentCanBeModified_whenSetEnvironment_thenItIsSet(EnvironmentVariables environmentVariables) { + environmentVariables.set("ENV", "value1"); + + assertThat(System.getenv("ENV")).isEqualTo("value1"); + } + } + + @Nested + class EnvironmentVariablesExecuteAround { + @Test + void givenSetupUsingWithEnvironmentVariable_thenItIsSet() throws Exception { + withEnvironmentVariable("ENV3", "val") + .execute(() -> { + assertThat(System.getenv("ENV3")).isEqualTo("val"); + }); + } + + @Test + void givenSetupUsingConstructor_thenItIsSet() throws Exception { + EnvironmentVariables environment = new EnvironmentVariables() + .set("ENV3", "val"); + environment.execute(() -> { + assertThat(System.getenv("ENV3")).isEqualTo("val"); + }); + } + + @Test + void givenEnvironment_thenCanReturnValue() throws Exception { + String extracted = new EnvironmentVariables("PROXY", "none") + .execute(() -> System.getenv("PROXY")); + + assertThat(extracted).isEqualTo("none"); + } + } + + @Nested + class RunMultiple { + @Test + void runMultiple() throws Exception { + with(new EnvironmentVariables("FOO", "bar"), + new SystemProperties("prop", "val")) + .execute(() -> { + assertThat(System.getenv("FOO")).isEqualTo("bar"); + assertThat(System.getProperty("prop")).isEqualTo("val"); + }); + } + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit4SystemPropertiesUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit4SystemPropertiesUnitTest.java new file mode 100644 index 0000000000..111baf9e9c --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit4SystemPropertiesUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.systemstubs; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.SystemPropertiesRule; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JUnit4SystemPropertiesUnitTest { + @Rule + public SystemPropertiesRule systemProperties = + new SystemPropertiesRule("db.connection", "false"); + + @Before + public void before() { + systemProperties.set("before.prop", "before"); + } + + @Test + public void givenPropertyIsSet_thenCanBeUsedInTest() { + assertThat(System.getProperty("db.connection")).isEqualTo("false"); + } + + @Test + public void givenPropertyIsSet_thenAnotherCanBeSetAndBeUsedInTest() { + assertThat(System.getProperty("db.connection")).isEqualTo("false"); + + systemProperties.set("prop2", "true"); + assertThat(System.getProperty("prop2")).isEqualTo("true"); + } + + @Test + public void givenPropertySetInBefore_thenCanBeSeenInTest() { + assertThat(System.getProperty("before.prop")).isEqualTo("before"); + } + + @Test + public void givenPropertySetEarlier_thenNotVisibleLater() { + assertThat(System.getProperty("prop2")).isNull(); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit5SystemPropertiesUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit5SystemPropertiesUnitTest.java new file mode 100644 index 0000000000..7aaf4cebad --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/JUnit5SystemPropertiesUnitTest.java @@ -0,0 +1,89 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; +import uk.org.webcompere.systemstubs.resource.PropertySource; + +import static org.assertj.core.api.Assertions.assertThat; + +class JUnit5SystemPropertiesUnitTest { + + @ExtendWith(SystemStubsExtension.class) + @Nested + class RestoreSystemProperties { + @SystemStub + private SystemProperties systemProperties; + + @Test + void givenAPropertyIsSet_thenItIsOnlyAvailableInsideThisTest1() { + assertThat(System.getProperty("localProperty")).isNull(); + + System.setProperty("localProperty", "nonnull"); + assertThat(System.getProperty("localProperty")).isEqualTo("nonnull"); + } + + @Test + void givenAPropertyIsSet_thenItIsOnlyAvailableInsideThisTest2() { + assertThat(System.getProperty("localProperty")).isNull(); + + System.setProperty("localProperty", "true"); + assertThat(System.getProperty("localProperty")).isEqualTo("true"); + } + } + + @ExtendWith(SystemStubsExtension.class) + @Nested + class RestoreSystemPropertiesByParameter { + + @Test + void givenAPropertyIsSet_thenItIsOnlyAvailableInsideThisTest1(SystemProperties systemProperties) { + assertThat(System.getProperty("localProperty")).isNull(); + + System.setProperty("localProperty", "nonnull"); + assertThat(System.getProperty("localProperty")).isEqualTo("nonnull"); + } + + @Test + void givenAPropertyIsSet_thenItIsOnlyAvailableInsideThisTest2(SystemProperties systemProperties) { + assertThat(System.getProperty("localProperty")).isNull(); + + System.setProperty("localProperty", "true"); + assertThat(System.getProperty("localProperty")).isEqualTo("true"); + } + } + + @ExtendWith(SystemStubsExtension.class) + @Nested + class SetSomeSystemProperties { + @SystemStub + private SystemProperties systemProperties; + + @BeforeEach + void before() { + systemProperties.set("beforeProperty", "before"); + } + + @Test + void givenAPropertyIsSetInBefore_thenItIsAvailableInsideThisTest() { + assertThat(System.getProperty("beforeProperty")).isEqualTo("before"); + } + } + + @ExtendWith(SystemStubsExtension.class) + @Nested + class SetSomeSystemPropertiesFromResources { + @SystemStub + private SystemProperties systemProperties = + new SystemProperties(PropertySource.fromResource("test.properties")); + + @Test + void givenPropertiesReadFromResources_thenCanBeUsed() { + assertThat(System.getProperty("name")).isEqualTo("baeldung"); + } + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingJUnit4UnitTest.java new file mode 100644 index 0000000000..a178efbb9d --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingJUnit4UnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.systemstubs; + +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.SystemOutRule; +import uk.org.webcompere.systemstubs.stream.output.NoopStream; + +public class OutputMutingJUnit4UnitTest { + @Rule + public SystemOutRule systemOutRule = new SystemOutRule(new NoopStream()); + + @Test + public void givenMuteSystemOut() throws Exception { + System.out.println("nothing is output"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingUnitTest.java new file mode 100644 index 0000000000..c75a523fff --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/OutputMutingUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.stream.SystemOut; +import uk.org.webcompere.systemstubs.stream.output.NoopStream; + +import static uk.org.webcompere.systemstubs.SystemStubs.muteSystemOut; + +class OutputMutingUnitTest { + @Nested + class MutingWithFacade { + @Test + void givenMuteSystemOut() throws Exception { + muteSystemOut(() -> { + System.out.println("nothing is output"); + }); + } + } + + @ExtendWith(SystemStubsExtension.class) + @Nested + class MutingWithJUnit5 { + @SystemStub + private SystemOut systemOut = new SystemOut(new NoopStream()); + + @Test + void givenMuteSystemOut() throws Exception { + System.out.println("nothing is output"); + } + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitExecuteAroundUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitExecuteAroundUnitTest.java new file mode 100644 index 0000000000..b42cc43307 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitExecuteAroundUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; + + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.org.webcompere.systemstubs.SystemStubs.catchSystemExit; + +class SystemExitExecuteAroundUnitTest { + @Test + void canCheckExitCode() throws Exception { + int exitCode = catchSystemExit(() -> { + System.exit(123); + }); + assertThat(exitCode).isEqualTo(123); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit4UnitTest.java new file mode 100644 index 0000000000..c044e250dd --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit4UnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.systemstubs; + +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.SystemExitRule; +import uk.org.webcompere.systemstubs.security.AbortExecutionException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class SystemExitJUnit4UnitTest { + @Rule + public SystemExitRule systemExitRule = new SystemExitRule(); + + @Test + public void whenAccidentalSystemExit_thenTestFailsRatherThanJVMKilled() { + // uncomment this to try it + //System.exit(1); + } + + @Test + public void whenExit_thenExitCodeIsAvailable() { + assertThatThrownBy(() -> { + System.exit(123); + }).isInstanceOf(AbortExecutionException.class); + + assertThat(systemExitRule.getExitCode()).isEqualTo(123); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit5UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit5UnitTest.java new file mode 100644 index 0000000000..4451d7e31f --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemExitJUnit5UnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.security.AbortExecutionException; +import uk.org.webcompere.systemstubs.security.SystemExit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@ExtendWith(SystemStubsExtension.class) +class SystemExitJUnit5UnitTest { + @SystemStub + private SystemExit systemExit; + + @Test + void whenExit_thenExitCodeIsAvailable() { + assertThatThrownBy(() -> { + System.exit(123); + }).isInstanceOf(AbortExecutionException.class); + + assertThat(systemExit.getExitCode()).isEqualTo(123); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInExecuteAroundUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInExecuteAroundUnitTest.java new file mode 100644 index 0000000000..5a1d510e35 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInExecuteAroundUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; + +import java.util.Scanner; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.org.webcompere.systemstubs.SystemStubs.withTextFromSystemIn; + +class SystemInExecuteAroundUnitTest { + + @Test + void givenTextInSystemIn_thenCanReadIt() throws Exception { + withTextFromSystemIn("line1", "line2", "line3") + .execute(() -> { + assertThat(new Scanner(System.in).nextLine()) + .isEqualTo("line1"); + }); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit4UnitTest.java new file mode 100644 index 0000000000..ccd422ea24 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit4UnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.systemstubs; + +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.SystemInRule; + +import java.util.Scanner; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SystemInJUnit4UnitTest { + @Rule + public SystemInRule systemInRule = + new SystemInRule("line1", "line2", "line3"); + + @Test + public void givenInput_canReadFirstLine() { + assertThat(new Scanner(System.in).nextLine()) + .isEqualTo("line1"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit5UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit5UnitTest.java new file mode 100644 index 0000000000..ed506eb40e --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemInJUnit5UnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.stream.SystemIn; + +import java.util.Scanner; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SystemStubsExtension.class) +class SystemInJUnit5UnitTest { + @SystemStub + private SystemIn systemIn = new SystemIn("line1", "line2", "line3"); + + @Test + void givenInput_canReadFirstLine() { + assertThat(new Scanner(System.in).nextLine()) + .isEqualTo("line1"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemLambdaComparisonUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemLambdaComparisonUnitTest.java new file mode 100644 index 0000000000..23e65767a8 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemLambdaComparisonUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.environment.EnvironmentVariables; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.properties.SystemProperties; + +import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties; +import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable; +import static org.junit.Assert.assertEquals; + +@ExtendWith(SystemStubsExtension.class) +class SystemLambdaComparisonUnitTest { + @SystemStub + private EnvironmentVariables environmentVariables = + new EnvironmentVariables("ADDRESS", "https://www.baeldung.com"); + + @SystemStub + private SystemProperties systemProperties = new SystemProperties(); + + @Test + void aSingleSystemLambda() throws Exception { + restoreSystemProperties(() -> { + System.setProperty("log_dir", "test/resources"); + assertEquals("test/resources", System.getProperty("log_dir")); + }); + } + + @Test + void multipleSystemLambdas() throws Exception { + restoreSystemProperties(() -> { + withEnvironmentVariable("URL", "https://www.baeldung.com") + .execute(() -> { + System.setProperty("log_dir", "test/resources"); + assertEquals("test/resources", System.getProperty("log_dir")); + assertEquals("https://www.baeldung.com", System.getenv("URL")); + }); + }); + } + + @Test + void multipleSystemStubs() { + System.setProperty("log_dir", "test/resources"); + assertEquals("test/resources", System.getProperty("log_dir")); + assertEquals("https://www.baeldung.com", System.getenv("ADDRESS")); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutAndErrExecuteAroundUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutAndErrExecuteAroundUnitTest.java new file mode 100644 index 0000000000..36b127d3cb --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutAndErrExecuteAroundUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import uk.org.webcompere.systemstubs.properties.SystemProperties; +import uk.org.webcompere.systemstubs.stream.SystemOut; +import uk.org.webcompere.systemstubs.stream.output.DisallowWriteStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static uk.org.webcompere.systemstubs.SystemStubs.tapSystemOutNormalized; +import static uk.org.webcompere.systemstubs.resource.Resources.with; + +class SystemOutAndErrExecuteAroundUnitTest { + @Test + void givenTapOutput_thenGetOutput() throws Exception { + String output = tapSystemOutNormalized(() -> { + System.out.println("a"); + System.out.println("b"); + }); + + assertThat(output).isEqualTo("a\nb\n"); + } + + @Test + void givenCaptureOutputWithSystemOut_thenGetOutput() throws Exception { + SystemOut systemOut = new SystemOut(); + SystemProperties systemProperties = new SystemProperties("a", "!"); + with(systemOut, systemProperties) + .execute(() -> { + System.out.println("a: " + System.getProperty("a")); + }); + + assertThat(systemOut.getLines()).containsExactly("a: !"); + } + + @Test + void givenCannotWrite_thenWritingIsError() { + assertThatThrownBy(() -> { + new SystemOut(new DisallowWriteStream()) + .execute(() -> System.out.println("boo")); + }).isInstanceOf(AssertionError.class); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit4UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit4UnitTest.java new file mode 100644 index 0000000000..d6ff70a49b --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit4UnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.systemstubs; + +import org.junit.Rule; +import org.junit.Test; +import uk.org.webcompere.systemstubs.rules.SystemErrRule; +import uk.org.webcompere.systemstubs.rules.SystemOutRule; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SystemOutJUnit4UnitTest { + @Rule + public SystemOutRule systemOutRule = new SystemOutRule(); + + @Rule + public SystemErrRule systemErrRule = new SystemErrRule(); + + @Test + public void whenCodeWritesToSystemOut_itCanBeRead() { + System.out.println("line1"); + System.out.println("line2"); + + assertThat(systemOutRule.getLines()) + .containsExactly("line1", "line2"); + } + + @Test + public void whenCodeWritesToSystemOut_itCanBeReadAsText() { + System.out.println("line1"); + System.out.println("line2"); + + assertThat(systemOutRule.getText()) + .startsWith("line1"); + } + + @Test + public void whenCodeWritesToSystemOut_itCanBeReadAsNormalizedLines() { + System.out.println("line1"); + System.out.println("line2"); + + assertThat(systemOutRule.getLinesNormalized()) + .isEqualTo("line1\nline2\n"); + } + + @Test + public void whenCodeWritesToSystemErr_itCanBeRead() { + System.err.println("line1"); + System.err.println("line2"); + + assertThat(systemErrRule.getLines()) + .containsExactly("line1", "line2"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit5UnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit5UnitTest.java new file mode 100644 index 0000000000..caa8a9264d --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemOutJUnit5UnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import uk.org.webcompere.systemstubs.jupiter.SystemStub; +import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension; +import uk.org.webcompere.systemstubs.stream.SystemErr; +import uk.org.webcompere.systemstubs.stream.SystemOut; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(SystemStubsExtension.class) +class SystemOutJUnit5UnitTest { + @SystemStub + private SystemOut systemOut; + + @SystemStub + private SystemErr systemErr; + + @Test + void whenWriteToOutput_thenItCanBeAsserted() { + System.out.println("to out"); + System.err.println("to err"); + + assertThat(systemOut.getLines()).containsExactly("to out"); + assertThat(systemErr.getLines()).containsExactly("to err"); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemPropertiesExecuteAroundUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemPropertiesExecuteAroundUnitTest.java new file mode 100644 index 0000000000..3f0f780238 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/SystemPropertiesExecuteAroundUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import uk.org.webcompere.systemstubs.properties.SystemProperties; + +import static org.assertj.core.api.Assertions.assertThat; +import static uk.org.webcompere.systemstubs.SystemStubs.restoreSystemProperties; + +class SystemPropertiesExecuteAroundUnitTest { + @Test + void givenRestoreSystemProperties_thenPropertyRestored() throws Exception { + restoreSystemProperties(() -> { + // test code + System.setProperty("unrestored", "true"); + }); + + assertThat(System.getProperty("unrestored")).isNull(); + } + + @Test + void givenSystemPropertiesObject_thenPropertyRestored() throws Exception { + String result = new SystemProperties() + .execute(() -> { + System.setProperty("unrestored", "true"); + return "it works"; + }); + + assertThat(result).isEqualTo("it works"); + assertThat(System.getProperty("unrestored")).isNull(); + } +} diff --git a/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/WithMockedInputStreamUnitTest.java b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/WithMockedInputStreamUnitTest.java new file mode 100644 index 0000000000..1019781837 --- /dev/null +++ b/testing-modules/testing-libraries-2/src/test/java/com/baeldung/systemstubs/WithMockedInputStreamUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.systemstubs; + +import org.junit.jupiter.api.Test; +import uk.org.webcompere.systemstubs.stream.input.LinesAltStream; + +import java.util.Scanner; + +import static org.assertj.core.api.Assertions.assertThat; + +class WithMockedInputStreamUnitTest { + @Test + void givenInputStream_thenCanRead() { + LinesAltStream testInput = new LinesAltStream("line1", "line2"); + + Scanner scanner = new Scanner(testInput); + assertThat(scanner.nextLine()).isEqualTo("line1"); + } +}