diff --git a/.gitignore b/.gitignore index 1890e8bd0e..a8f09b4135 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties +/vertx-and-rxjava/.vertx/ diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java b/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java new file mode 100755 index 0000000000..45ac53e039 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java @@ -0,0 +1,194 @@ +package com.baeldung.algorithms.string.search; + +import java.math.BigInteger; +import java.util.Random; + +public class StringSearchAlgorithms { + public static long getBiggerPrime(int m) { + BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random()); + return prime.longValue(); + } + + public static long getLowerPrime(long number) { + BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random()); + return prime.longValue(); + } + + private static int getNumberOfBits(final int number) { + return Integer.SIZE - Integer.numberOfLeadingZeros(number); + } + + private static int getNumberOfBits(final long number) { + return Long.SIZE - Long.numberOfLeadingZeros(number); + } + + public static int simpleTextSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; + int textSize = text.length; + + int i = 0; + + while ((i + patternSize) <= textSize) { + int j = 0; + while (text[i + j] == pattern[j]) { + j += 1; + if (j >= patternSize) + return i; + } + i += 1; + } + + return -1; + } + + public static int RabinKarpMethod(char[] pattern, char[] text) { + int patternSize = pattern.length; // m + int textSize = text.length; // n + + long prime = getBiggerPrime(patternSize); + + long r = 1; + for (int i = 0; i < patternSize - 1; i++) { + r *= 2; + r = r % prime; + } + + long[] t = new long[textSize]; + t[0] = 0; + + long pfinger = 0; + + for (int j = 0; j < patternSize; j++) { + t[0] = (2 * t[0] + text[j]) % prime; + pfinger = (2 * pfinger + pattern[j]) % prime; + } + + int i = 0; + boolean passed = false; + + int diff = textSize - patternSize; + for (i = 0; i <= diff; i++) { + if (t[i] == pfinger) { + passed = true; + for (int k = 0; k < patternSize; k++) { + if (text[i + k] != pattern[k]) { + passed = false; + break; + } + } + + if (passed) { + return i; + } + } + + if (i < diff) { + long value = 2 * (t[i] - r * text[i]) + text[i + patternSize]; + t[i + 1] = ((value % prime) + prime) % prime; + } + } + return -1; + + } + + public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; // m + int textSize = text.length; // n + + int i = 0, j = 0; + + int[] shift = KnuthMorrisPrattShift(pattern); + + while ((i + patternSize) <= textSize) { + while (text[i + j] == pattern[j]) { + j += 1; + if (j >= patternSize) + return i; + } + + if (j > 0) { + i += shift[j - 1]; + j = Math.max(j - shift[j - 1], 0); + } else { + i++; + j = 0; + } + } + return -1; + } + + public static int[] KnuthMorrisPrattShift(char[] pattern) { + int patternSize = pattern.length; + + int[] shift = new int[patternSize]; + shift[0] = 1; + + int i = 1, j = 0; + + while ((i + j) < patternSize) { + if (pattern[i + j] == pattern[j]) { + shift[i + j] = i; + j++; + } else { + if (j == 0) + shift[i] = i + 1; + + if (j > 0) { + i = i + shift[j - 1]; + j = Math.max(j - shift[j - 1], 0); + } else { + i = i + 1; + j = 0; + } + } + } + return shift; + } + + public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) { + int patternSize = pattern.length; + int textSize = text.length; + + int i = 0, j = 0; + + while ((i + patternSize) <= textSize) { + j = patternSize - 1; + while (text[i + j] == pattern[j]) { + j--; + if (j < 0) + return i; + } + i++; + } + return -1; + } + + public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) { + + int shift[] = new int[256]; + + for (int k = 0; k < 256; k++) { + shift[k] = pattern.length; + } + + for (int k = 0; k < pattern.length - 1; k++) { + shift[pattern[k]] = pattern.length - 1 - k; + } + + int i = 0, j = 0; + + while ((i + pattern.length) <= text.length) { + j = pattern.length - 1; + + while (text[i + j] == pattern[j]) { + j -= 1; + if (j < 0) + return i; + } + + i = i + shift[text[i + pattern.length - 1]]; + + } + return -1; + } +} diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java new file mode 100755 index 0000000000..e260cd7e5b --- /dev/null +++ b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java @@ -0,0 +1,25 @@ +package algorithms; + + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.algorithms.string.search.StringSearchAlgorithms; + +public class StringSearchAlgorithmsTest { + + + @Test + public void testStringSearchAlgorithms(){ + String text = "This is some nice text."; + String pattern = "some"; + + int realPosition = text.indexOf(pattern); + Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray())); + Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray())); + } + +} diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java new file mode 100644 index 0000000000..8663609d2d --- /dev/null +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/callable/FactorialTask.java @@ -0,0 +1,30 @@ +package com.baeldung.concurrent.callable; + + +import java.util.concurrent.Callable; + +public class FactorialTask implements Callable { + int number; + + public FactorialTask(int number) { + this.number = number; + } + + public Integer call() throws InvalidParamaterException { + int fact=1; + if(number < 0) + throw new InvalidParamaterException("Number must be positive"); + + for(int count=number;count>1;count--){ + fact=fact * count; + } + + return fact; + } + + private class InvalidParamaterException extends Exception { + public InvalidParamaterException(String message) { + super(message); + } + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java new file mode 100644 index 0000000000..c55e04af94 --- /dev/null +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/callable/FactorialTaskManualTest.java @@ -0,0 +1,48 @@ +package com.baeldung.concurrent.callable; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static junit.framework.Assert.assertEquals; + +public class FactorialTaskManualTest { + + private ExecutorService executorService; + + @Before + public void setup(){ + executorService = Executors.newSingleThreadExecutor(); + } + + @Test + public void whenTaskSubmitted_ThenFutureResultObtained() throws ExecutionException, InterruptedException { + FactorialTask task = new FactorialTask(5); + Future future= executorService.submit(task); + assertEquals(120,future.get().intValue()); + } + + @Test(expected = ExecutionException.class) + public void whenException_ThenCallableThrowsIt() throws ExecutionException, InterruptedException { + FactorialTask task = new FactorialTask(-5); + Future future= executorService.submit(task); + Integer result=future.get().intValue(); + } + + @Test + public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){ + FactorialTask task = new FactorialTask(-5); + Future future= executorService.submit(task); + assertEquals(false,future.isDone()); + } + + @After + public void cleanup(){ + executorService.shutdown(); + } +} diff --git a/core-java/pom.xml b/core-java/pom.xml index 25029c237f..7920566a1a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -162,6 +162,12 @@ ${avaitility.version} test + + org.springframework + spring-core + ${spring-core.version} + test + commons-codec @@ -186,6 +192,16 @@ fscontext ${fscontext.version} + + com.codepoetics + protonpack + ${protonpack.version} + + + one.util + streamex + ${streamex.version} + @@ -408,12 +424,16 @@ 1.8.7 1.16.12 4.6-b01 + 1.13 + 0.6.5 + 1.3 4.12 2.8.9 3.6.1 1.7.0 + 4.3.10.RELEASE diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java index 0d69d0e7ec..9d4fcf3574 100644 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AdapterPatternDriver.java @@ -5,9 +5,16 @@ import static com.baeldung.designpatterns.util.LogerUtil.LOG; public class AdapterPatternDriver { public static void main(String args[]) { - LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); - LOG.info("Bugatti Veyron Super Sport's top speed is " + luxuryCars.bugattiVeyronInKMPH() + " Kmph."); - LOG.info("McLaren F1 top speed is " + luxuryCars.mcLarenInKMPH() + " Kmph."); - LOG.info("Aston Martin One-77 top speed is " + luxuryCars.astonMartinInKMPH() + " Kmph."); + LuxuryCars bugattiVeyron = new BugattiVeyron(); + LuxuryCarsAdapter bugattiVeyronAdapter = new LuxuryCarsAdapterImpl(bugattiVeyron); + LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.speedInKMPH() + " Kmph."); + + LuxuryCars mcLaren = new McLaren(); + LuxuryCarsAdapter mcLarenAdapter = new LuxuryCarsAdapterImpl(mcLaren); + LOG.info("McLaren F1 top speed is " + mcLarenAdapter.speedInKMPH() + " Kmph."); + + LuxuryCars astonMartin = new AstonMartin(); + LuxuryCarsAdapter astonMartinAdapter = new LuxuryCarsAdapterImpl(astonMartin); + LOG.info("McLaren F1 top speed is " + astonMartinAdapter.speedInKMPH() + " Kmph."); } } diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java new file mode 100644 index 0000000000..b1fba0dae3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/AstonMartin.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class AstonMartin implements LuxuryCars { + @Override + public double speedInMPH() { + return 220; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java new file mode 100644 index 0000000000..1b0b834448 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/BugattiVeyron.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class BugattiVeyron implements LuxuryCars { + @Override + public double speedInMPH() { + return 268; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCars.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCars.java new file mode 100644 index 0000000000..9926f5f8bc --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCars.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCars { + public double speedInMPH(); +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapter.java new file mode 100644 index 0000000000..f945e1b389 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapter.java @@ -0,0 +1,5 @@ +package com.baeldung.designpatterns.adapter; + +public interface LuxuryCarsAdapter { + public double speedInKMPH(); +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapterImpl.java new file mode 100644 index 0000000000..f2bf553292 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsAdapterImpl.java @@ -0,0 +1,19 @@ +package com.baeldung.designpatterns.adapter; + +public class LuxuryCarsAdapterImpl implements LuxuryCarsAdapter { + private LuxuryCars luxuryCars; + + public LuxuryCarsAdapterImpl(LuxuryCars luxuryCars) { + this.luxuryCars = luxuryCars; + } + + @Override + public double speedInKMPH() { + double mph = luxuryCars.speedInMPH(); + return convertMPHtoKMPH(mph); + } + + private double convertMPHtoKMPH(double mph) { + return mph * 1.60934; + } +} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java deleted file mode 100644 index 0b97b8228c..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeed.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public class LuxuryCarsSpeed { - public double bugattiVeyronInMPH() { - return 268; - } - - public double mcLarenInMPH() { - return 241; - } - - public double astonMartinInMPH() { - return 220; - } -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java deleted file mode 100644 index d9255f0910..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public interface LuxuryCarsSpeedAdapter { - public double bugattiVeyronInKMPH(); - - public double mcLarenInKMPH(); - - public double astonMartinInKMPH(); -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java deleted file mode 100644 index 2767b78e38..0000000000 --- a/core-java/src/main/java/com/baeldung/designpatterns/adapter/LuxuryCarsSpeedAdapterImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.designpatterns.adapter; - -public class LuxuryCarsSpeedAdapterImpl extends LuxuryCarsSpeed implements LuxuryCarsSpeedAdapter { - - @Override - public double bugattiVeyronInKMPH() { - double mph = super.bugattiVeyronInMPH(); - return convertMPHtoKMPH(mph); - } - - @Override - public double mcLarenInKMPH() { - double mph = super.mcLarenInMPH(); - return convertMPHtoKMPH(mph); - } - - @Override - public double astonMartinInKMPH() { - double mph = super.astonMartinInMPH(); - return convertMPHtoKMPH(mph); - } - - private double convertMPHtoKMPH(double mph) { - return mph * 1.60934; - } -} diff --git a/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java b/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java new file mode 100644 index 0000000000..e2ba2b830d --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/adapter/McLaren.java @@ -0,0 +1,8 @@ +package com.baeldung.designpatterns.adapter; + +public class McLaren implements LuxuryCars { + @Override + public double speedInMPH() { + return 241; + } +} diff --git a/core-java/src/main/java/com/baeldung/stream/StreamIndices.java b/core-java/src/main/java/com/baeldung/stream/StreamIndices.java new file mode 100644 index 0000000000..b101bc2740 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/stream/StreamIndices.java @@ -0,0 +1,37 @@ +package com.baeldung.stream; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; + +public class StreamIndices { + + public static List getEvenIndexedStrings(String[] names) { + List evenIndexedNames = IntStream.range(0, names.length) + .filter(i -> i % 2 == 0).mapToObj(i -> names[i]) + .collect(Collectors.toList()); + return evenIndexedNames; + } + + public static List> getEvenIndexedStrings(List names) { + List> list = StreamUtils.zipWithIndex(names.stream()) + .filter(i -> i.getIndex() % 2 == 0).collect(Collectors.toList()); + return list; + } + + public static List> getOddIndexedStrings(List names) { + List> list = StreamUtils.zipWithIndex(names.stream()) + .filter(i -> i.getIndex() % 2 == 1).collect(Collectors.toList()); + return list; + } + + public static List getOddIndexedStrings(String[] names) { + List oddIndexedNames = IntStream.range(0, names.length) + .filter(i -> i % 2 == 1).mapToObj(i -> names[i]) + .collect(Collectors.toList()); + return oddIndexedNames; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java index fb483a8a68..e56e271743 100644 --- a/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java +++ b/core-java/src/test/java/com/baeldung/designpatterns/AdapterPatternIntegrationTest.java @@ -1,20 +1,20 @@ package com.baeldung.designpatterns; - -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; -import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapter; -import com.baeldung.designpatterns.adapter.LuxuryCarsSpeedAdapterImpl; +import com.baeldung.designpatterns.adapter.AstonMartin; +import com.baeldung.designpatterns.adapter.BugattiVeyron; +import com.baeldung.designpatterns.adapter.LuxuryCarsAdapterImpl; +import com.baeldung.designpatterns.adapter.McLaren; public class AdapterPatternIntegrationTest { @Test public void givenLuxuryCarsAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() { - LuxuryCarsSpeedAdapter luxuryCars = new LuxuryCarsSpeedAdapterImpl(); - assertEquals(luxuryCars.bugattiVeyronInKMPH(), 431.30312, 0.00001); - assertEquals(luxuryCars.mcLarenInKMPH(), 387.85094, 0.00001); - assertEquals(luxuryCars.astonMartinInKMPH(), 354.0548, 0.00001); + assertEquals(new LuxuryCarsAdapterImpl(new BugattiVeyron()).speedInKMPH(), 431.30312, 0.00001); + assertEquals(new LuxuryCarsAdapterImpl(new McLaren()).speedInKMPH(), 387.85094, 0.00001); + assertEquals(new LuxuryCarsAdapterImpl(new AstonMartin()).speedInKMPH(), 354.0548, 0.00001); } } diff --git a/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java new file mode 100644 index 0000000000..ca60544788 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/stream/StreamIndicesTest.java @@ -0,0 +1,50 @@ +package com.baeldung.stream; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.codepoetics.protonpack.Indexed; + +public class StreamIndicesTest { + + @Test + public void givenArray_whenGetIndexedStrings_thenReturnListOfEvenIndexedStrings() { + String[] names = { "Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim" }; + List expectedResult = Arrays.asList("Afrim", "Besim", "Durim"); + List actualResult = StreamIndices.getEvenIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenArray_whenGetIndexedStrings_thenReturnListOfOddStrings() { + String[] names = { "Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim" }; + List expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim"); + List actualResult = StreamIndices.getOddIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenList_whenGetIndexedStrings_thenReturnListOfEvenIndexedStrings() { + List names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"); + List> expectedResult = Arrays.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed.index(4, "Durim")); + List> actualResult = StreamIndices.getEvenIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenList_whenGetIndexedStrings_thenReturnListOfOddIndexedStrings() { + List names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"); + List> expectedResult = Arrays.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed.index(5, "Shpetim")); + List> actualResult = StreamIndices.getOddIndexedStrings(names); + + assertEquals(expectedResult, actualResult); + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaDirectoryDeleteUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaDirectoryDeleteUnitTest.java new file mode 100644 index 0000000000..b1f800eef3 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/io/JavaDirectoryDeleteUnitTest.java @@ -0,0 +1,143 @@ +package org.baeldung.java.io; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.util.FileSystemUtils; + +public class JavaDirectoryDeleteUnitTest { + private static Path TEMP_DIRECTORY; + private static final String DIRECTORY_NAME = "toBeDeleted"; + + public static final List ALL_LINES = Arrays.asList(new String[] { "This is line 1", "This is line 2", "This is line 3", "This is line 4", "This is line 5", "This is line 6" }); + + @BeforeClass + public static void initializeTempDirectory() throws IOException { + TEMP_DIRECTORY = Files.createTempDirectory("tmpForJUnit"); + } + + @AfterClass + public static void cleanTempDirectory() throws IOException { + FileUtils.deleteDirectory(TEMP_DIRECTORY.toFile()); + } + + @Before + public void setupDirectory() throws IOException { + Path tempPathForEachTest = Files.createDirectory(TEMP_DIRECTORY.resolve(DIRECTORY_NAME)); + + // Create a directory structure + Files.write(tempPathForEachTest.resolve("file1.txt"), ALL_LINES.subList(0, 2)); + Files.write(tempPathForEachTest.resolve("file2.txt"), ALL_LINES.subList(2, 4)); + + Files.createDirectories(tempPathForEachTest.resolve("Empty")); + + Path aSubDir = Files.createDirectories(tempPathForEachTest.resolve("notEmpty")); + Files.write(aSubDir.resolve("file3.txt"), ALL_LINES.subList(3, 5)); + Files.write(aSubDir.resolve("file4.txt"), ALL_LINES.subList(0, 3)); + + aSubDir = Files.createDirectories(aSubDir.resolve("anotherSubDirectory")); + Files.write(aSubDir.resolve("file5.txt"), ALL_LINES.subList(4, 5)); + Files.write(aSubDir.resolve("file6.txt"), ALL_LINES.subList(0, 2)); + } + + @After + public void checkAndCleanupIfRequired() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + if (Files.exists(pathToBeDeleted)) { + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + } + } + + boolean deleteDirectory(File directoryToBeDeleted) { + File[] allContents = directoryToBeDeleted.listFiles(); + + for (File file : allContents) { + if (file.isDirectory()) { + deleteDirectory(file); + } else { + file.delete(); + } + } + + return directoryToBeDeleted.delete(); + } + + @Test + public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = deleteDirectory(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithCommonsIOFileUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + FileUtils.deleteDirectory(pathToBeDeleted.toFile()); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithSpringFileSystemUtils_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + boolean result = FileSystemUtils.deleteRecursively(pathToBeDeleted.toFile()); + + assertTrue("Could not delete directory", result); + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithFilesWalk_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walk(pathToBeDeleted) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } + + @Test + public void givenDirectory_whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException { + Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); + + Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor() { + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + }); + + assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); + } +} diff --git a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java b/ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java similarity index 92% rename from ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java rename to ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java index b65c21100d..3b63761c73 100644 --- a/ejb/ejbclient/src/main/java/com/baeldung/ejbclient/application/TextApplication.java +++ b/ejb/ejb-client/src/main/java/com/baeldung/ejb/wildfly/TextApplication.java @@ -1,7 +1,5 @@ -package com.baeldung.ejbclient.application; +package com.baeldung.ejb.wildfly; -import com.baeldung.ejbmodule.TextProcessorBean; -import com.baeldung.ejbmodule.TextProcessorRemote; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; diff --git a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java similarity index 94% rename from ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java rename to ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java index 947c72d0b0..c0446eaea6 100644 --- a/ejb/ejbclient/src/test/java/com/baeldung/ejbclient/application/TextApplicationTest.java +++ b/ejb/ejb-client/src/test/java/com/baeldung/ejb/wildfly/TextApplicationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbclient.application; +package com.baeldung.ejb.wildfly; import org.junit.AfterClass; import org.junit.BeforeClass; diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java similarity index 85% rename from ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java rename to ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java index dc0db5fc53..4f0c013b0f 100644 --- a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorBean.java +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorBean.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbmodule; +package com.baeldung.ejb.wildfly; import javax.ejb.Stateless; diff --git a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java similarity index 76% rename from ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java rename to ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java index 680d8f4e10..b51af8528d 100644 --- a/ejb/ejbmodule/src/main/java/com/baeldung/ejbmodule/TextProcessorRemote.java +++ b/ejb/ejb-remote/src/main/java/com/baeldung/ejb/wildfly/TextProcessorRemote.java @@ -1,4 +1,4 @@ -package com.baeldung.ejbmodule; +package com.baeldung.ejb.wildfly; import javax.ejb.Remote; diff --git a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties b/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties deleted file mode 100644 index 67533b7825..0000000000 --- a/ejb/ejbclient/src/main/resources/jboss-ejb-client.properties +++ /dev/null @@ -1,8 +0,0 @@ -endpoint.name=client-endpoint -remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED=false -remote.connections=default -remote.connection.default.host=127.0.0.1 -remote.connection.default.port=8080 -remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false -remote.connection.default.username=myusername -remote.connection.default.password=mypassword \ No newline at end of file diff --git a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java b/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java deleted file mode 100644 index d8693420d4..0000000000 --- a/ejb/ejbmodule/src/test/java/com/baeldung/ejbmodule/TextProcessorBeanTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.ejbmodule; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; - -public class TextProcessorBeanTest { - @Test - public void givenInputString_whenComparedToStringParsedByBean_thenSuccessful() { - TextProcessorBean textProcessor = new TextProcessorBean(); - assertEquals("TEST", textProcessor.processText("test")); - } -} \ No newline at end of file diff --git a/ejb/pom.xml b/ejb/pom.xml index b8aa32fab1..78e40a7b7c 100755 --- a/ejb/pom.xml +++ b/ejb/pom.xml @@ -81,6 +81,5 @@ ejb-remote ejb-client ejb-session-beans - ejb-session-beans-client \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/createUser.json b/graphql/graphql-java/payload-examples/createUser.json new file mode 100644 index 0000000000..3ade405b16 --- /dev/null +++ b/graphql/graphql-java/payload-examples/createUser.json @@ -0,0 +1,8 @@ +{ + "query": "mutation($name: String! $email: String! $age: String! ){ createUser ( name: $name email: $email age: $age) { id name email age } }", + "parameters": { + "name": "John", + "email": "john@email.com", + "age": 34 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/deleteUser.json b/graphql/graphql-java/payload-examples/deleteUser.json new file mode 100644 index 0000000000..204496f19b --- /dev/null +++ b/graphql/graphql-java/payload-examples/deleteUser.json @@ -0,0 +1,6 @@ +{ + "query": "mutation($name: String! ){ deleteUser ( id: $id) { id name email age} }", + "parameters": { + "id": 2 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/listUsers.json b/graphql/graphql-java/payload-examples/listUsers.json new file mode 100644 index 0000000000..dde887bb07 --- /dev/null +++ b/graphql/graphql-java/payload-examples/listUsers.json @@ -0,0 +1,4 @@ +{ + "query": "{ listUsers{ id name email age}}", + "parameters": {} +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/retrieveUser.json b/graphql/graphql-java/payload-examples/retrieveUser.json new file mode 100644 index 0000000000..27b5f422eb --- /dev/null +++ b/graphql/graphql-java/payload-examples/retrieveUser.json @@ -0,0 +1,6 @@ +{ + "query": "query($id: String!){ retrieveUser ( id: $id) { id name email} }", + "parameters": { + "id": 1 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/searchName.json b/graphql/graphql-java/payload-examples/searchName.json new file mode 100644 index 0000000000..df8f080b86 --- /dev/null +++ b/graphql/graphql-java/payload-examples/searchName.json @@ -0,0 +1,6 @@ +{ + "query": "query($id: String!){ searchName ( id: $id) { id name email} }", + "parameters": { + "id": 2 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/payload-examples/updateUser.json b/graphql/graphql-java/payload-examples/updateUser.json new file mode 100644 index 0000000000..aa68151111 --- /dev/null +++ b/graphql/graphql-java/payload-examples/updateUser.json @@ -0,0 +1,9 @@ +{ + "query": "mutation($id: String! $name: String! $email: String! $age: String! ){ updateUser ( id: $id name: $name email: $email age: $age) { id name email age} }", + "parameters": { + "id": 1, + "name":"John updated", + "email": "johnupdate@email.com", + "age": 50 + } +} \ No newline at end of file diff --git a/graphql/graphql-java/pom.xml b/graphql/graphql-java/pom.xml new file mode 100644 index 0000000000..c031ddc694 --- /dev/null +++ b/graphql/graphql-java/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung.graphql + graphql-java + 1.0 + + graphql-java + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.graphql-java + graphql-java-annotations + 3.0.3 + + + io.ratpack + ratpack-core + 1.4.6 + + + \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java new file mode 100644 index 0000000000..6e9b2a5c80 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.graphql; + +import ratpack.server.RatpackServer; + +import com.baeldung.graphql.handler.UserHandler; + +public class Application { + public static void main(String[] args) throws Exception { + new Application(); + } + + private Application() throws Exception { + final RatpackServer server = RatpackServer.of(s -> s.handlers(chain -> chain.post("users", new UserHandler()))); + server.start(); + } + +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java new file mode 100644 index 0000000000..a4a776cfff --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/entity/User.java @@ -0,0 +1,78 @@ +package com.baeldung.graphql.entity; + +import java.util.List; + +import com.baeldung.graphql.handler.UserHandler; +import com.baeldung.graphql.utils.SchemaUtils; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; + +@GraphQLName(SchemaUtils.USER) +public class User { + + @GraphQLField + private Long id; + @GraphQLField + private String name; + @GraphQLField + private String email; + @GraphQLField + private Integer age; + + public User(String name, String email, Integer age) { + this.id = genId(); + this.name = name; + this.email = email; + this.age = age; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public static Long genId() { + Long id = 1L; + try { + List users = new UserHandler().getUsers(); + for (User user : users) + id = (user.getId() > id ? user.getId() : id) + 1; + + } catch (Exception e) { + e.printStackTrace(); + } + return id; + } + + public String toString() { + return "[id=" + id + ", name=" + name + ", email="+email+ ", age="+ age +"]"; + } +} \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java new file mode 100644 index 0000000000..a6d474a70d --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/handler/UserHandler.java @@ -0,0 +1,56 @@ +package com.baeldung.graphql.handler; + +import graphql.ExecutionResult; +import graphql.GraphQL; +import graphql.schema.DataFetchingEnvironment; +import ratpack.handling.Context; +import ratpack.handling.Handler; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.schema.UserSchema; +import com.baeldung.graphql.utils.SchemaUtils; + +import static ratpack.jackson.Jackson.json; + +public class UserHandler implements Handler { + private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); + private GraphQL graphql; + private static List users = new ArrayList<>(); + + public UserHandler() throws Exception { + graphql = new GraphQL(new UserSchema().getSchema()); + } + + @Override + public void handle(Context context) throws Exception { + context.parse(Map.class) + .then(payload -> { + Map parameters = (Map) payload.get("parameters"); + ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) + .toString(), null, this, parameters); + Map result = new LinkedHashMap<>(); + if (executionResult.getErrors() + .isEmpty()) { + result.put(SchemaUtils.DATA, executionResult.getData()); + } else { + result.put(SchemaUtils.ERRORS, executionResult.getErrors()); + LOGGER.warning("Errors: " + executionResult.getErrors()); + } + context.render(json(result)); + }); + } + + public static List getUsers() { + return users; + } + + public static List getUsers(DataFetchingEnvironment env) { + return ((UserHandler) env.getSource()).getUsers(); + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java new file mode 100644 index 0000000000..3c6f53a382 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/mutation/UserMutation.java @@ -0,0 +1,57 @@ +package com.baeldung.graphql.mutation; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; +import graphql.schema.DataFetchingEnvironment; + +import javax.validation.constraints.NotNull; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.utils.SchemaUtils; + +import java.util.List; +import java.util.Optional; + +import static com.baeldung.graphql.handler.UserHandler.getUsers; + +@GraphQLName(SchemaUtils.MUTATION) +public class UserMutation { + @GraphQLField + public static User createUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email, @NotNull @GraphQLName(SchemaUtils.AGE) final String age) { + List users = getUsers(env); + final User user = new User(name, email, Integer.valueOf(age)); + users.add(user); + return user; + } + + @GraphQLField + public static User updateUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email, + @NotNull @GraphQLName(SchemaUtils.AGE) final String age) { + final Optional user = getUsers(env).stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + if (!user.isPresent()) { + return null; + } + user.get() + .setName(name); + user.get() + .setEmail(email); + user.get() + .setAge(Integer.valueOf(age)); + return user.get(); + } + + @GraphQLField + public static User deleteUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) { + final List users = getUsers(env); + final Optional user = users.stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + if (!user.isPresent()) { + return null; + } + users.removeIf(c -> c.getId() == Long.parseLong(id)); + return user.get(); + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java new file mode 100644 index 0000000000..6f1521c5cf --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/query/UserQuery.java @@ -0,0 +1,42 @@ +package com.baeldung.graphql.query; + +import graphql.annotations.GraphQLField; +import graphql.annotations.GraphQLName; +import graphql.schema.DataFetchingEnvironment; + +import javax.validation.constraints.NotNull; + +import com.baeldung.graphql.entity.User; +import com.baeldung.graphql.utils.SchemaUtils; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.baeldung.graphql.handler.UserHandler.getUsers; + +@GraphQLName(SchemaUtils.QUERY) +public class UserQuery { + + @GraphQLField + public static User retrieveUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) { + final Optional any = getUsers(env).stream() + .filter(c -> c.getId() == Long.parseLong(id)) + .findFirst(); + return any.orElse(null); + } + + @GraphQLField + public static List searchName(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.NAME) final String name) { + return getUsers(env).stream() + .filter(c -> c.getName() + .contains(name)) + .collect(Collectors.toList()); + } + + @GraphQLField + public static List listUsers(final DataFetchingEnvironment env) { + return getUsers(env); + } + +} \ No newline at end of file diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java new file mode 100644 index 0000000000..ebb3569aac --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/schema/UserSchema.java @@ -0,0 +1,24 @@ +package com.baeldung.graphql.schema; + +import graphql.annotations.GraphQLAnnotations; +import graphql.schema.GraphQLSchema; + +import static graphql.schema.GraphQLSchema.newSchema; + +import com.baeldung.graphql.mutation.UserMutation; +import com.baeldung.graphql.query.UserQuery; + +public class UserSchema { + + private final GraphQLSchema schema; + + public UserSchema() throws IllegalAccessException, NoSuchMethodException, InstantiationException { + schema = newSchema().query(GraphQLAnnotations.object(UserQuery.class)) + .mutation(GraphQLAnnotations.object(UserMutation.class)) + .build(); + } + + public GraphQLSchema getSchema() { + return schema; + } +} diff --git a/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java b/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java new file mode 100644 index 0000000000..680d7e3ea9 --- /dev/null +++ b/graphql/graphql-java/src/main/java/com/baeldung/graphql/utils/SchemaUtils.java @@ -0,0 +1,14 @@ +package com.baeldung.graphql.utils; + +public class SchemaUtils { + public static final String USER = "user"; + public static final String ID = "id"; + public static final String NAME = "name"; + public static final String EMAIL = "email"; + public static final String AGE = "age"; + + public static final String MUTATION = "mutation"; + public static final String QUERY = "query"; + public static final String ERRORS = "errors"; + public static final String DATA = "data"; +} diff --git a/libraries/pom.xml b/libraries/pom.xml index ee92642b62..9bbc0c41d2 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -538,7 +538,7 @@ 0.7.0 3.2.4 - 3.5 + 3.6 1.1 1.9.3 1.2 @@ -583,4 +583,4 @@ 2.9.9 1.5.1 - \ No newline at end of file + diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java new file mode 100644 index 0000000000..c64f7e7511 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java @@ -0,0 +1,60 @@ +package com.baeldung.commons.lang3; + +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +public class BuilderMethods { + + private final int intValue; + private final String strSample; + + public BuilderMethods(final int newId, final String newName) { + this.intValue = newId; + this.strSample = newName; + } + + public int getId() { + return this.intValue; + } + + public String getName() { + return this.strSample; + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(this.intValue) + .append(this.strSample) + .toHashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof BuilderMethods == false) { + return false; + } + if (this == obj) { + return true; + } + final BuilderMethods otherObject = (BuilderMethods) obj; + + return new EqualsBuilder().append(this.intValue, otherObject.intValue) + .append(this.strSample, otherObject.strSample) + .isEquals(); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("INTVALUE", this.intValue) + .append("STRINGVALUE", this.strSample) + .toString(); + } + + public static void main(final String[] arguments) { + final BuilderMethods simple1 = new BuilderMethods(1, "The First One"); + System.out.println(simple1.getName()); + System.out.println(simple1.hashCode()); + System.out.println(simple1.toString()); + } +} diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java new file mode 100644 index 0000000000..2e74ad3c24 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/commons/lang3/Lang3UtilsTest.java @@ -0,0 +1,118 @@ +package com.baeldung.commons.lang3; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.lang.reflect.Field; +import java.util.Locale; +import java.util.concurrent.Future; + +import org.apache.commons.lang3.ArchUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.SystemUtils; +import org.apache.commons.lang3.arch.Processor; +import org.apache.commons.lang3.concurrent.ConcurrentRuntimeException; +import org.apache.commons.lang3.concurrent.ConcurrentUtils; +import org.apache.commons.lang3.event.EventUtils; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.time.FastDateFormat; +import org.junit.Assert; +import org.junit.Test; + +public class Lang3UtilsTest { + + @Test + public void test_to_Boolean_fromString() { + assertFalse(BooleanUtils.toBoolean("off")); + assertTrue(BooleanUtils.toBoolean("true")); + assertTrue(BooleanUtils.toBoolean("tRue")); + assertFalse(BooleanUtils.toBoolean("no")); + assertFalse(BooleanUtils.isTrue(Boolean.FALSE)); + assertFalse(BooleanUtils.isTrue(null)); + } + + @Test + public void testGetUserHome() { + final File dir = SystemUtils.getUserHome(); + Assert.assertNotNull(dir); + Assert.assertTrue(dir.exists()); + } + + @Test + public void testGetJavaHome() { + final File dir = SystemUtils.getJavaHome(); + Assert.assertNotNull(dir); + Assert.assertTrue(dir.exists()); + } + + @Test + public void testProcessorArchType() { + Processor processor = ArchUtils.getProcessor("x86"); + assertTrue(processor.is32Bit()); + assertFalse(processor.is64Bit()); + } + + @Test + public void testProcessorArchType64Bit() { + Processor processor = ArchUtils.getProcessor("x86_64"); + assertFalse(processor.is32Bit()); + assertTrue(processor.is64Bit()); + } + + @Test(expected = IllegalArgumentException.class) + public void testConcurrentRuntimeExceptionCauseError() { + new ConcurrentRuntimeException("An error", new Error()); + } + + @Test + public void testConstantFuture_Integer() throws Exception { + Future test = ConcurrentUtils.constantFuture(5); + assertTrue(test.isDone()); + assertSame(5, test.get()); + assertFalse(test.isCancelled()); + } + + @Test + public void testFieldUtilsGetAllFields() { + final Field[] fieldsNumber = Number.class.getDeclaredFields(); + assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class)); + } + + @Test + public void test_getInstance_String_Locale() { + final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.US); + final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); + + assertNotSame(format1, format3); + } + + @Test + public void testAddEventListenerThrowsException() { + final ExceptionEventSource src = new ExceptionEventSource(); + try { + EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent e) { + // Do nothing! + } + }); + fail("Add method should have thrown an exception, so method should fail."); + } catch (final RuntimeException e) { + + } + } + + public static class ExceptionEventSource { + public void addPropertyChangeListener(final PropertyChangeListener listener) { + throw new RuntimeException(); + } + } + +} diff --git a/pom.xml b/pom.xml index da38d65df3..004e4b3df9 100644 --- a/pom.xml +++ b/pom.xml @@ -240,6 +240,7 @@ spring-boot-property-exp mockserver undertow + vertx-and-rxjava diff --git a/vertx-and-rxjava/pom.xml b/vertx-and-rxjava/pom.xml new file mode 100644 index 0000000000..47510e60f7 --- /dev/null +++ b/vertx-and-rxjava/pom.xml @@ -0,0 +1,71 @@ + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + 4.0.0 + com.baeldung + vertx-and-rxjava + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + io.vertx + vertx-rx-java2 + 3.5.0.Beta1 + + + io.vertx + vertx-core + 3.5.0.Beta1 + + + io.vertx + vertx-unit + 3.5.0.Beta1 + test + + + junit + junit + 4.12 + test + + + org.slf4j + slf4j-api + 1.7.25 + + + ch.qos.logback + logback-classic + 1.2.3 + + + junit + junit + 4.12 + + + + + \ No newline at end of file diff --git a/vertx-and-rxjava/pom.xml.orig b/vertx-and-rxjava/pom.xml.orig new file mode 100644 index 0000000000..47510e60f7 --- /dev/null +++ b/vertx-and-rxjava/pom.xml.orig @@ -0,0 +1,71 @@ + + + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + 4.0.0 + com.baeldung + vertx-and-rxjava + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + + + + + + io.vertx + vertx-rx-java2 + 3.5.0.Beta1 + + + io.vertx + vertx-core + 3.5.0.Beta1 + + + io.vertx + vertx-unit + 3.5.0.Beta1 + test + + + junit + junit + 4.12 + test + + + org.slf4j + slf4j-api + 1.7.25 + + + ch.qos.logback + logback-classic + 1.2.3 + + + junit + junit + 4.12 + + + + + \ No newline at end of file diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/CityAndDayLength.java b/vertx-and-rxjava/src/test/java/com/baeldung/CityAndDayLength.java new file mode 100644 index 0000000000..dec4aa4852 --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/CityAndDayLength.java @@ -0,0 +1,18 @@ +package com.baeldung; + +import java.text.MessageFormat; + +class CityAndDayLength { + + private final String city; + private final double dayLengthInHours; + + public CityAndDayLength(String city, long dayLengthInSeconds) { + this.city = city; + this.dayLengthInHours = dayLengthInSeconds / (60.0 * 60.0); + } + + @Override public String toString() { + return MessageFormat.format("In {0} there are {1,number,#0.0} hours of light.", city, dayLengthInHours); + } +} diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/MetaWeatherClient.java b/vertx-and-rxjava/src/test/java/com/baeldung/MetaWeatherClient.java new file mode 100644 index 0000000000..0a3e9d8713 --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/MetaWeatherClient.java @@ -0,0 +1,45 @@ +package com.baeldung; + +import io.reactivex.Flowable; +import io.vertx.core.http.RequestOptions; +import io.vertx.reactivex.core.http.HttpClient; +import io.vertx.reactivex.core.http.HttpClientRequest; +import io.vertx.reactivex.core.http.HttpClientResponse; + +import static java.lang.String.format; + +public class MetaWeatherClient { + + private static RequestOptions metawether = new RequestOptions() + .setHost("www.metaweather.com") + .setPort(443) + .setSsl(true); + + /** + * @return A flowable backed by vertx that automatically sends an HTTP request at soon as the first subscription is received. + */ +private static Flowable autoPerformingReq(HttpClient httpClient, String uri) { + HttpClientRequest req = httpClient.get(new RequestOptions(metawether).setURI(uri)); + return req.toFlowable() + .doOnSubscribe(subscription -> req.end()); +} + +static Flowable searchByCityName(HttpClient httpClient, String cityName) { + HttpClientRequest req = httpClient.get( + new RequestOptions() + .setHost("www.metaweather.com") + .setPort(443) + .setSsl(true) + .setURI(format("/api/location/search/?query=%s", cityName))); + return req + .toFlowable() + .doOnSubscribe(subscription -> req.end()); +} + + static Flowable getDataByPlaceId(HttpClient httpClient, long placeId) { + return autoPerformingReq( + httpClient, + format("/api/location/%s/", placeId)); + } + +} diff --git a/vertx-and-rxjava/src/test/java/com/baeldung/VertxWithRxJavaTest.java b/vertx-and-rxjava/src/test/java/com/baeldung/VertxWithRxJavaTest.java new file mode 100644 index 0000000000..f02792c3d7 --- /dev/null +++ b/vertx-and-rxjava/src/test/java/com/baeldung/VertxWithRxJavaTest.java @@ -0,0 +1,94 @@ +package com.baeldung; + +import io.reactivex.Flowable; +import io.vertx.reactivex.core.Vertx; +import io.vertx.reactivex.core.buffer.Buffer; +import io.vertx.reactivex.core.file.FileSystem; +import io.vertx.reactivex.core.http.HttpClient; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.ZonedDateTime; + +import static com.baeldung.MetaWeatherClient.getDataByPlaceId; +import static com.baeldung.MetaWeatherClient.searchByCityName; + +public class VertxWithRxJavaTest { + + private Vertx vertx; + private HttpClient httpClient; + private FileSystem fileSystem; + static Logger log = LoggerFactory.getLogger(VertxWithRxJavaTest.class); + + @Before public void setUp() { + vertx = io.vertx.reactivex.core.Vertx.vertx(); + httpClient = vertx.createHttpClient(); + fileSystem = vertx.fileSystem(); + } + + @After public void tearDown() { + vertx.close(); + } + + @Test public void lightLengthTest() throws InterruptedException { + + // read the file that contains one city name per line + fileSystem + .rxReadFile("cities.txt").toFlowable() + .doOnNext(buffer -> log.info("File buffer ---\n{}\n---", buffer)) + + // split file content in lines to obtain one city per line + .flatMap(buffer -> Flowable.fromArray(buffer.toString().split("\\r?\\n"))) + .doOnNext(city -> log.info("City from file: '{}'", city)) + + // discard cities that are commented out with a leading '#' + .filter(city -> !city.startsWith("#")) + .doOnNext(city -> log.info("City that survived filtering: '{}'", city)) + + // for each city sends a request to obtain its 'woeid' + // and collect the buffer from the answer + .flatMap(city -> searchByCityName(httpClient, city) ) + .flatMap(response -> response.toFlowable()) + .doOnNext(buffer -> log.info("JSON of city detail: '{}'", buffer)) + + // get the woeid of each city + .map(cityBuffer -> cityBuffer + .toJsonArray() + .getJsonObject(0) + .getLong("woeid")) + + // use the id to ask for data + .flatMap(cityId -> getDataByPlaceId(httpClient, cityId)) + .flatMap(response -> response + .toObservable() + .reduce( + Buffer.buffer(), + (total, newBuf) -> total.appendBuffer( newBuf )).toFlowable() ) + + // get the JSON object out of the response + .doOnNext(buffer -> log.info("JSON of place detail: '{}'", buffer)) + .map(buffer -> buffer.toJsonObject()) + + // map the JSON in a POJO + .map(json -> { + ZonedDateTime sunRise = ZonedDateTime.parse(json.getString("sun_rise")); + ZonedDateTime sunSet = ZonedDateTime.parse(json.getString("sun_set")); + String cityName = json.getString("title"); + return new CityAndDayLength( + cityName,sunSet.toEpochSecond() - sunRise.toEpochSecond()); + }) + + // consume the events + .subscribe( + cityAndDayLength -> System.out.println(cityAndDayLength), + ex -> ex.printStackTrace()); + + // enough to give time to complete the execution + Thread.sleep(20000); + + } + +} diff --git a/vertx-and-rxjava/src/test/resources/cities.txt b/vertx-and-rxjava/src/test/resources/cities.txt new file mode 100644 index 0000000000..dbe6e96758 --- /dev/null +++ b/vertx-and-rxjava/src/test/resources/cities.txt @@ -0,0 +1,6 @@ +Milan +Chicago +Cairo +Santiago +Moscow +Auckland \ No newline at end of file diff --git a/vertx-and-rxjava/src/test/resources/logback-test.xml b/vertx-and-rxjava/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..71e05a4e24 --- /dev/null +++ b/vertx-and-rxjava/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + [%thread{32}] %-5level %msg - %logger%n + + + + + + + + \ No newline at end of file