[JAVA-29427] Consolidate libraries modules (#15536)

This commit is contained in:
panos-kakos
2024-01-03 20:39:23 +02:00
committed by GitHub
parent 5c6e53c15a
commit 21d3e16584
60 changed files with 364 additions and 453 deletions
@@ -0,0 +1,117 @@
package com.baeldung.fj;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import fj.F;
import fj.Show;
import fj.data.Array;
import fj.data.List;
import fj.data.Option;
import fj.function.Characters;
import fj.function.Integers;
public class FunctionalJavaUnitTest {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static final Integer timesTwoRegular(Integer i) {
return i * 2;
}
public static final F<Integer, Integer> timesTwo = i -> i * 2;
public static final F<Integer, Integer> plusOne = i -> i + 1;
@Test
public void multiplyNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo);
List<Integer> fList2 = fList.map(i -> i * 2);
assertTrue(fList1.equals(fList2));
}
@Test
public void applyMultipleFunctions_givenIntList_returnFalse() {
List<Integer> fList = List.list(1, 2, 3, 4);
List<Integer> fList1 = fList.map(timesTwo).map(plusOne);
Show.listShow(Show.intShow).println(fList1);
List<Integer> fList2 = fList.map(plusOne).map(timesTwo);
Show.listShow(Show.intShow).println(fList2);
assertFalse(fList1.equals(fList2));
}
@Test
public void calculateEvenNumbers_givenIntList_returnTrue() {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
List<Boolean> evenListTrueResult = List.list(false, true, false, true);
assertTrue(evenList.equals(evenListTrueResult));
}
@Test
public void mapList_givenIntList_returnResult() {
List<Integer> fList = List.list(3, 4, 5, 6);
fList = fList.map(i -> i + 100);
List<Integer> resultList = List.list(103, 104, 105, 106);
assertTrue(fList.equals(resultList));
}
@Test
public void filterList_givenIntList_returnResult() {
Array<Integer> array = Array.array(3, 4, 5, 6);
Array<Integer> filteredArray = array.filter(isEven);
Array<Integer> result = Array.array(4, 6);
assertTrue(filteredArray.equals(result));
}
@Test
public void checkForLowerCase_givenStringArray_returnResult() {
Array<String> array = Array.array("Welcome", "To", "baeldung");
assertTrue(array.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
Array<String> array2 = Array.array("Welcome", "To", "Baeldung");
assertFalse(array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase)));
assertFalse(array.forall(s -> List.fromString(s).forall(Characters.isLowerCase)));
}
@Test
public void checkOptions_givenOptions_returnResult() {
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
Option<Integer> n3 = Option.none();
F<Integer, Option<Integer>> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(function);
Option<Integer> result2 = n2.bind(function);
Option<Integer> result3 = n3.bind(function);
Assert.assertEquals(Option.none(), result1);
Assert.assertEquals(Option.some(102), result2);
Assert.assertEquals(Option.none(), result3);
}
@Test
public void foldLeft_givenArray_returnResult() {
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sumAll = intArray.foldLeft(Integers.add, 0);
assertEquals(260, sumAll);
int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
assertEquals(148, sumEven);
}
}
@@ -0,0 +1,100 @@
package com.baeldung.javapoet.test;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.baeldung.javapoet.PersonGenerator;
@RunWith(JUnit4.class)
public class PersonGeneratorUnitTest {
private PersonGenerator generator;
private Path generatedFolderPath;
private Path expectedFolderPath;
@Before
public void setUp() {
String packagePath = this
.getClass()
.getPackage()
.getName()
.replace(".", "/") + "/person";
generator = new PersonGenerator();
generatedFolderPath = generator
.getOutputPath()
.resolve(packagePath);
expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath);
}
@After
public void tearDown() throws Exception {
FileUtils.deleteDirectory(new File(generator
.getOutputPath()
.toUri()));
}
@Test
public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException {
generator.generateGenderEnum();
String fileName = "Gender.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
@Test
public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException {
generator.generatePersonInterface();
String fileName = "Person.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
@Test
public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException {
generator.generateStudentClass();
String fileName = "Student.java";
assertThatFileIsGeneratedAsExpected(fileName);
deleteGeneratedFile(fileName);
}
private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException {
String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName));
String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName));
assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent)));
}
private void deleteGeneratedFile(String fileName) throws IOException {
Path generatedFilePath = generatedFolderPath.resolve(fileName);
Files.delete(generatedFilePath);
}
private String extractFileContent(Path filePath) throws IOException {
byte[] fileContentAsBytes = Files.readAllBytes(filePath);
String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8);
if (!fileContentAsString.contains("\r\n")) {
// file is not in DOS format
// convert it first, so that the content comparison will be relevant
return fileContentAsString.replaceAll("\n", "\r\n");
}
return fileContentAsString;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.javapoet.test.person;
public enum Gender {
MALE,
FEMALE,
UNSPECIFIED
}
@@ -0,0 +1,13 @@
package com.baeldung.javapoet.test.person;
import java.lang.String;
public interface Person {
String DEFAULT_NAME = "Alice";
String getName();
default String getDefaultName() {
return DEFAULT_NAME;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.javapoet.test.person;
import java.lang.Override;
import java.lang.String;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
public class Student implements Person {
private String name;
@Override
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void printNameMultipleTimes() {
List<String> names = new ArrayList<>();
IntStream.range(0, 10).forEach(i -> names.add(name));
names.forEach(System.out::println);
}
public static void sortByLength(List<String> strings) {
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
}
}
@@ -0,0 +1,79 @@
package com.baeldung.libphonenumber;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
public class LibPhoneNumberUnitTest {
private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
@Test
public void givenPhoneNumber_whenValid_thenOK() throws Exception {
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", CountryCodeSource.UNSPECIFIED.name());
assertTrue(phoneNumberUtil.isValidNumber(phone));
assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
}
@Test
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
}
@Test
public void givenPhoneNumber_whenPossibleForType_thenValid() {
PhoneNumber number = new PhoneNumber();
number.setCountryCode(54);
number.setNationalNumber(123456);
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
number.setNationalNumber(12345678901L);
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
}
@Test
public void givenPhoneNumber_whenPossible_thenValid() {
PhoneNumber number = new PhoneNumber();
number.setCountryCode(1)
.setNationalNumber(123000L);
assertFalse(phoneNumberUtil.isPossibleNumber(number));
assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
}
@Test
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
assertTrue(phoneNumberUtil.isNumberGeographical(phone));
phone = new PhoneNumber().setCountryCode(1)
.setNationalNumber(2530000L);
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
phone = new PhoneNumber().setCountryCode(800)
.setNationalNumber(12345678L);
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
}
}
@@ -0,0 +1,30 @@
package com.baeldung.r;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for {@link FastRMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class FastRMeanUnitTest {
/**
* Object to test.
*/
private FastRMean fastrMean = new FastRMean();
/**
* Test for {@link FastRMeanUnitTest#mean(int[])}.
*/
@Test
public void givenValues_whenMean_thenCorrect() {
int[] input = { 1, 2, 3, 4, 5 };
double result = fastrMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.script.ScriptException;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for {@link RCallerMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class RCallerMeanIntegrationTest {
/**
* Object to test.
*/
private RCallerMean rcallerMean = new RCallerMean();
/**
* Test for {@link RCallerMeanIntegrationTest#mean(int[])}.
*
* @throws ScriptException if an error occurs
* @throws URISyntaxException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException {
int[] input = { 1, 2, 3, 4, 5 };
double result = rcallerMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.r;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.script.ScriptException;
import org.junit.Assert;
import org.junit.Test;
/**
* Test for {@link RenjinMean}.
*
* @author Donato Rimenti
*/
public class RenjinMeanUnitTest {
/**
* Object to test.
*/
private RenjinMean renjinMean = new RenjinMean();
/**
* Test for {@link RenjinMeanUnitTest#mean(int[])}.
*
* @throws ScriptException if an error occurs
* @throws URISyntaxException if an error occurs
* @throws IOException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws IOException, URISyntaxException, ScriptException {
int[] input = { 1, 2, 3, 4, 5 };
double result = renjinMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.r;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
/**
* Test for {@link RserveMean}.
*
* @author Donato Rimenti
*/
@Ignore
public class RserveMeanIntegrationTest {
/**
* Object to test.
*/
private RserveMean rserveMean = new RserveMean();
/**
* Test for {@link RserveMeanIntegrationTest#mean(int[])}.
*
* @throws REXPMismatchException if an error occurs
* @throws REngineException if an error occurs
*/
@Test
public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException {
int[] input = { 1, 2, 3, 4, 5 };
double result = rserveMean.mean(input);
Assert.assertEquals(3.0, result, 0.000001);
}
}
@@ -0,0 +1,136 @@
package com.baeldung.resilence4j;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;
import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.bulkhead.BulkheadRegistry;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
public class Resilience4jUnitTest {
interface RemoteService {
int process(int i);
}
private RemoteService service;
@Before
public void setUp() {
service = mock(RemoteService.class);
}
@Test
public void whenCircuitBreakerIsUsed_thenItWorksAsExpected() {
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
// Percentage of failures to start short-circuit
.failureRateThreshold(20)
// Min number of call attempts
.slidingWindowSize(5)
.build();
CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config);
CircuitBreaker circuitBreaker = registry.circuitBreaker("my");
Function<Integer, Integer> decorated = CircuitBreaker.decorateFunction(circuitBreaker, service::process);
when(service.process(anyInt())).thenThrow(new RuntimeException());
for (int i = 0; i < 10; i++) {
try {
decorated.apply(i);
} catch (Exception ignore) {
}
}
verify(service, times(5)).process(any(Integer.class));
}
@Test
public void whenBulkheadIsUsed_thenItWorksAsExpected() throws InterruptedException {
BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(1).build();
BulkheadRegistry registry = BulkheadRegistry.of(config);
Bulkhead bulkhead = registry.bulkhead("my");
Function<Integer, Integer> decorated = Bulkhead.decorateFunction(bulkhead, service::process);
Future<?> taskInProgress = callAndBlock(decorated);
try {
assertThat(bulkhead.tryAcquirePermission()).isFalse();
} finally {
taskInProgress.cancel(true);
}
}
private Future<?> callAndBlock(Function<Integer, Integer> decoratedService) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
when(service.process(anyInt())).thenAnswer(invocation -> {
latch.countDown();
Thread.currentThread().join();
return null;
});
ForkJoinTask<?> result = ForkJoinPool.commonPool().submit(() -> {
decoratedService.apply(1);
});
latch.await();
return result;
}
@Test
public void whenRetryIsUsed_thenItWorksAsExpected() {
RetryConfig config = RetryConfig.custom().maxAttempts(2).build();
RetryRegistry registry = RetryRegistry.of(config);
Retry retry = registry.retry("my");
Function<Integer, Void> decorated = Retry.decorateFunction(retry, (Integer s) -> {
service.process(s);
return null;
});
when(service.process(anyInt())).thenThrow(new RuntimeException());
try {
decorated.apply(1);
fail("Expected an exception to be thrown if all retries failed");
} catch (Exception e) {
verify(service, times(2)).process(any(Integer.class));
}
}
@SuppressWarnings("unchecked")
@Test
public void whenTimeLimiterIsUsed_thenItWorksAsExpected() throws Exception {
long ttl = 1;
TimeLimiterConfig config = TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(ttl)).build();
TimeLimiter timeLimiter = TimeLimiter.of(config);
Future futureMock = mock(Future.class);
Callable restrictedCall = TimeLimiter.decorateFutureSupplier(timeLimiter, () -> futureMock);
restrictedCall.call();
verify(futureMock).get(ttl, TimeUnit.MILLISECONDS);
}
}
@@ -0,0 +1,75 @@
package com.baeldung.test;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import org.agrona.concurrent.UnsafeBuffer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.sbe.MarketData;
import com.baeldung.sbe.stub.Currency;
import com.baeldung.sbe.stub.Market;
import com.baeldung.sbe.stub.MessageHeaderDecoder;
import com.baeldung.sbe.stub.MessageHeaderEncoder;
import com.baeldung.sbe.stub.TradeDataDecoder;
import com.baeldung.sbe.stub.TradeDataEncoder;
public class EncodeDecodeMarketDataUnitTest {
private MarketData marketData;
@BeforeEach
public void setup() {
marketData = new MarketData(2, 128.99, Market.NYSE, Currency.USD, "IBM");
}
@Test
public void givenMarketData_whenEncode_thenDecodedValuesMatch() {
// our buffer to write encoded data, initial cap. 128 bytes
UnsafeBuffer buffer = new UnsafeBuffer(ByteBuffer.allocate(128));
// necessary encoders
MessageHeaderEncoder headerEncoder = new MessageHeaderEncoder();
TradeDataEncoder dataEncoder = new TradeDataEncoder();
// we parse price data (double) into two parts: mantis and exponent
BigDecimal priceDecimal = BigDecimal.valueOf(marketData.getPrice());
int priceMantissa = priceDecimal.scaleByPowerOfTen(priceDecimal.scale())
.intValue();
int priceExponent = priceDecimal.scale() * -1;
// encode data
TradeDataEncoder encoder = dataEncoder.wrapAndApplyHeader(buffer, 0, headerEncoder);
encoder.amount(marketData.getAmount());
encoder.quote()
.market(marketData.getMarket())
.currency(marketData.getCurrency())
.symbol(marketData.getSymbol())
.price()
.mantissa(priceMantissa)
.exponent((byte) priceExponent);
// necessary decoders
MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder();
TradeDataDecoder dataDecoder = new TradeDataDecoder();
// decode data
dataDecoder.wrapAndApplyHeader(buffer, 0, headerDecoder);
// decode price data (from mantissa and exponent) into a double
double price = BigDecimal.valueOf(dataDecoder.quote()
.price()
.mantissa())
.scaleByPowerOfTen(dataDecoder.quote()
.price()
.exponent())
.doubleValue();
// ensure we have the exact same values
Assertions.assertEquals(2, dataDecoder.amount());
Assertions.assertEquals("IBM", dataDecoder.quote()
.symbol());
Assertions.assertEquals(Market.NYSE, dataDecoder.quote()
.market());
Assertions.assertEquals(Currency.USD, dataDecoder.quote()
.currency());
Assertions.assertEquals(128.99, price);
}
}
+3
View File
@@ -0,0 +1,3 @@
customMean <- function(vector) {
mean(vector)
}