fix conflicts
This commit is contained in:
commit
04fa170603
1
.gitignore
vendored
1
.gitignore
vendored
@ -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/
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
25
algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java
Executable file
25
algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java
Executable file
@ -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()));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.baeldung.concurrent.callable;
|
||||
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class FactorialTask implements Callable<Integer> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
@ -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<Integer> 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<Integer> future= executorService.submit(task);
|
||||
Integer result=future.get().intValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){
|
||||
FactorialTask task = new FactorialTask(-5);
|
||||
Future<Integer> future= executorService.submit(task);
|
||||
assertEquals(false,future.isDone());
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup(){
|
||||
executorService.shutdown();
|
||||
}
|
||||
}
|
@ -162,6 +162,12 @@
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
@ -186,6 +192,16 @@
|
||||
<artifactId>fscontext</artifactId>
|
||||
<version>${fscontext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@ -408,12 +424,16 @@
|
||||
<grep4j.version>1.8.7</grep4j.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<fscontext.version>4.6-b01</fscontext.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>2.8.9</mockito.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<spring-core.version>4.3.10.RELEASE</spring-core.version>
|
||||
|
||||
|
||||
<!-- maven plugins -->
|
||||
|
@ -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.");
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class AstonMartin implements LuxuryCars {
|
||||
@Override
|
||||
public double speedInMPH() {
|
||||
return 220;
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class BugattiVeyron implements LuxuryCars {
|
||||
@Override
|
||||
public double speedInMPH() {
|
||||
return 268;
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface LuxuryCars {
|
||||
public double speedInMPH();
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface LuxuryCarsAdapter {
|
||||
public double speedInKMPH();
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public interface LuxuryCarsSpeedAdapter {
|
||||
public double bugattiVeyronInKMPH();
|
||||
|
||||
public double mcLarenInKMPH();
|
||||
|
||||
public double astonMartinInKMPH();
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.baeldung.designpatterns.adapter;
|
||||
|
||||
public class McLaren implements LuxuryCars {
|
||||
@Override
|
||||
public double speedInMPH() {
|
||||
return 241;
|
||||
}
|
||||
}
|
@ -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<String> getEvenIndexedStrings(String[] names) {
|
||||
List<String> evenIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 0).mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return evenIndexedNames;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 0).collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 1).collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String> getOddIndexedStrings(String[] names) {
|
||||
List<String> oddIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 1).mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return oddIndexedNames;
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -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<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
|
||||
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenGetIndexedStrings_thenReturnListOfOddStrings() {
|
||||
String[] names = { "Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim" };
|
||||
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
|
||||
List<String> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetIndexedStrings_thenReturnListOfEvenIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed.index(4, "Durim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetIndexedStrings_thenReturnListOfOddIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed.index(5, "Shpetim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
}
|
@ -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<String> 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<Path>() {
|
||||
@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));
|
||||
}
|
||||
}
|
@ -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;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.ejbclient.application;
|
||||
package com.baeldung.ejb.wildfly;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.ejbmodule;
|
||||
package com.baeldung.ejb.wildfly;
|
||||
|
||||
import javax.ejb.Stateless;
|
||||
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.ejbmodule;
|
||||
package com.baeldung.ejb.wildfly;
|
||||
|
||||
import javax.ejb.Remote;
|
||||
|
@ -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
|
@ -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"));
|
||||
}
|
||||
}
|
@ -81,6 +81,5 @@
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
<module>ejb-session-beans</module>
|
||||
<module>ejb-session-beans-client</module>
|
||||
</modules>
|
||||
</project>
|
8
graphql/graphql-java/payload-examples/createUser.json
Normal file
8
graphql/graphql-java/payload-examples/createUser.json
Normal file
@ -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
|
||||
}
|
||||
}
|
6
graphql/graphql-java/payload-examples/deleteUser.json
Normal file
6
graphql/graphql-java/payload-examples/deleteUser.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"query": "mutation($name: String! ){ deleteUser ( id: $id) { id name email age} }",
|
||||
"parameters": {
|
||||
"id": 2
|
||||
}
|
||||
}
|
4
graphql/graphql-java/payload-examples/listUsers.json
Normal file
4
graphql/graphql-java/payload-examples/listUsers.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"query": "{ listUsers{ id name email age}}",
|
||||
"parameters": {}
|
||||
}
|
6
graphql/graphql-java/payload-examples/retrieveUser.json
Normal file
6
graphql/graphql-java/payload-examples/retrieveUser.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"query": "query($id: String!){ retrieveUser ( id: $id) { id name email} }",
|
||||
"parameters": {
|
||||
"id": 1
|
||||
}
|
||||
}
|
6
graphql/graphql-java/payload-examples/searchName.json
Normal file
6
graphql/graphql-java/payload-examples/searchName.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"query": "query($id: String!){ searchName ( id: $id) { id name email} }",
|
||||
"parameters": {
|
||||
"id": 2
|
||||
}
|
||||
}
|
9
graphql/graphql-java/payload-examples/updateUser.json
Normal file
9
graphql/graphql-java/payload-examples/updateUser.json
Normal file
@ -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
|
||||
}
|
||||
}
|
29
graphql/graphql-java/pom.xml
Normal file
29
graphql/graphql-java/pom.xml
Normal file
@ -0,0 +1,29 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.graphql</groupId>
|
||||
<artifactId>graphql-java</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<name>graphql-java</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.graphql-java</groupId>
|
||||
<artifactId>graphql-java-annotations</artifactId>
|
||||
<version>3.0.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.ratpack</groupId>
|
||||
<artifactId>ratpack-core</artifactId>
|
||||
<version>1.4.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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<User> 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 +"]";
|
||||
}
|
||||
}
|
@ -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<User> 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<String, Object> parameters = (Map<String, Object>) payload.get("parameters");
|
||||
ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY)
|
||||
.toString(), null, this, parameters);
|
||||
Map<String, Object> 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<User> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public static List<User> getUsers(DataFetchingEnvironment env) {
|
||||
return ((UserHandler) env.getSource()).getUsers();
|
||||
}
|
||||
}
|
@ -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<User> 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> 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<User> users = getUsers(env);
|
||||
final Optional<User> 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();
|
||||
}
|
||||
}
|
@ -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<User> any = getUsers(env).stream()
|
||||
.filter(c -> c.getId() == Long.parseLong(id))
|
||||
.findFirst();
|
||||
return any.orElse(null);
|
||||
}
|
||||
|
||||
@GraphQLField
|
||||
public static List<User> 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<User> listUsers(final DataFetchingEnvironment env) {
|
||||
return getUsers(env);
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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";
|
||||
}
|
@ -538,7 +538,7 @@
|
||||
<properties>
|
||||
<multiverse.version>0.7.0</multiverse.version>
|
||||
<cglib.version>3.2.4</cglib.version>
|
||||
<commons-lang.version>3.5</commons-lang.version>
|
||||
<commons-lang.version>3.6</commons-lang.version>
|
||||
<commons-text.version>1.1</commons-text.version>
|
||||
<commons-beanutils.version>1.9.3</commons-beanutils.version>
|
||||
<commons-chain.version>1.2</commons-chain.version>
|
||||
@ -583,4 +583,4 @@
|
||||
<joda-time.version>2.9.9</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
</properties>
|
||||
</project>
|
||||
</project>
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
@ -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<Integer> 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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
1
pom.xml
1
pom.xml
@ -240,6 +240,7 @@
|
||||
<module>spring-boot-property-exp</module>
|
||||
<module>mockserver</module>
|
||||
<module>undertow</module>
|
||||
<module>vertx-and-rxjava</module>
|
||||
</modules>
|
||||
|
||||
<dependencies>
|
||||
|
71
vertx-and-rxjava/pom.xml
Normal file
71
vertx-and-rxjava/pom.xml
Normal file
@ -0,0 +1,71 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>vertx-and-rxjava</artifactId>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-rx-java2</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-core</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-unit</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.25</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
71
vertx-and-rxjava/pom.xml.orig
Normal file
71
vertx-and-rxjava/pom.xml.orig
Normal file
@ -0,0 +1,71 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>vertx-and-rxjava</artifactId>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-rx-java2</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-core</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vertx</groupId>
|
||||
<artifactId>vertx-unit</artifactId>
|
||||
<version>3.5.0.Beta1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.25</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@ -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);
|
||||
}
|
||||
}
|
@ -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<HttpClientResponse> autoPerformingReq(HttpClient httpClient, String uri) {
|
||||
HttpClientRequest req = httpClient.get(new RequestOptions(metawether).setURI(uri));
|
||||
return req.toFlowable()
|
||||
.doOnSubscribe(subscription -> req.end());
|
||||
}
|
||||
|
||||
static Flowable<HttpClientResponse> 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<HttpClientResponse> getDataByPlaceId(HttpClient httpClient, long placeId) {
|
||||
return autoPerformingReq(
|
||||
httpClient,
|
||||
format("/api/location/%s/", placeId));
|
||||
}
|
||||
|
||||
}
|
@ -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);
|
||||
|
||||
}
|
||||
|
||||
}
|
6
vertx-and-rxjava/src/test/resources/cities.txt
Normal file
6
vertx-and-rxjava/src/test/resources/cities.txt
Normal file
@ -0,0 +1,6 @@
|
||||
Milan
|
||||
Chicago
|
||||
Cairo
|
||||
Santiago
|
||||
Moscow
|
||||
Auckland
|
12
vertx-and-rxjava/src/test/resources/logback-test.xml
Normal file
12
vertx-and-rxjava/src/test/resources/logback-test.xml
Normal file
@ -0,0 +1,12 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>[%thread{32}] %-5level %msg - %logger%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="warn">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
Loading…
x
Reference in New Issue
Block a user