Merge branch 'master' into study-groovy

This commit is contained in:
Alex Golub
2023-01-20 20:08:17 +02:00
103 changed files with 2149 additions and 362 deletions
+7
View File
@@ -72,6 +72,13 @@ Building a single module
To build a specific module, run the command: `mvn clean install` in the module directory.
Building modules from the root of the repository
====================
To build specific modules from the root of the repository, run the command: `mvn clean install --pl asm,atomikos -Pdefault-first` in the root directory.
Here `asm` and `atomikos` are the modules that we want to build and `default-first` is the maven profile in which these modules are present.
Running a Spring Boot module
====================
To run a Spring Boot module, run the command: `mvn spring-boot:run` in the module directory.
@@ -1,46 +1,50 @@
package com.baeldung.httpclient.cookies;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.cookie.BasicCookieStore;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class HttpClientGettingCookieValueUnitTest {
class HttpClientGettingCookieValueUnitTest {
private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class);
private static final String SAMPLE_URL = "http://www.baeldung.com/";
@Test
public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore());
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) {
CookieStore cookieStore = context.getCookieStore();
Cookie customCookie = cookieStore.getCookies()
.stream()
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
.findFirst()
.orElseThrow(IllegalStateException::new);
final HttpGet request = new HttpGet(SAMPLE_URL);
assertEquals("test_value", customCookie.getValue());
}
try (CloseableHttpClient client = HttpClientBuilder.create()
.build()) {
client.execute(request, context, new BasicHttpClientResponseHandler());
CookieStore cookieStore = context.getCookieStore();
Cookie customCookie = cookieStore.getCookies()
.stream()
.peek(cookie -> log.info("cookie name:{}", cookie.getName()))
.filter(cookie -> "custom_cookie".equals(cookie.getName()))
.findFirst()
.orElseThrow(IllegalStateException::new);
assertEquals("test_value", customCookie.getValue());
}
}
@@ -48,7 +52,7 @@ public class HttpClientGettingCookieValueUnitTest {
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");
cookie.setDomain("baeldung.com");
cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookie.setAttribute("domain", "true");
cookie.setPath("/");
cookieStore.addCookie(cookie);
return cookieStore;
+1
View File
@@ -11,4 +11,5 @@ This module contains articles about Java 8 core features
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)
- [Monads in Java](https://www.baeldung.com/java-monads)
- [[More -->]](/core-java-modules/core-java-8-2)
@@ -28,30 +28,16 @@ class MonadSample1 extends MonadBaseExample {
public double apply(double n) {
return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(2)))));
}
public static void main(String[] args) {
final MonadSample1 test = new MonadSample1();
System.out.println(test.apply(2));
//6.0
}
}
class MonadSample2 extends MonadBaseExample {
public double apply(double n) {
final double n1 = multiplyBy2(n);
final double n2 = multiplyBy2(n1);
final double n3 = divideBy2(n2);
final double n4 = add3(n3);
double n1 = multiplyBy2(n);
double n2 = multiplyBy2(n1);
double n3 = divideBy2(n2);
double n4 = add3(n3);
return subtract1(n4);
}
public static void main(String[] args) {
final MonadSample2 test = new MonadSample2();
System.out.println(test.apply(2));
//6.0
}
}
class MonadSample3 extends MonadBaseExample {
@@ -66,11 +52,6 @@ class MonadSample3 extends MonadBaseExample {
.get();
}
public static void main(String[] args) {
final MonadSample3 test = new MonadSample3();
System.out.println(test.apply(2));
//6.0
}
}
class MonadSample4 extends MonadBaseExample {
@@ -90,13 +71,6 @@ class MonadSample3 extends MonadBaseExample {
return leftSide.equals(rightSide);
}
public static void main(String[] args) {
final MonadSample4 test = new MonadSample4();
System.out.println(test.leftIdentity()); //true
System.out.println(test.rightIdentity()); //true
System.out.println(test.associativity()); //true
}
}
class MonadSample5 extends MonadBaseExample {
@@ -104,10 +78,5 @@ class MonadSample5 extends MonadBaseExample {
Function<Integer, Optional<Integer>> mapping = value -> Optional.of(value == null ? -1 : value + 1);
return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null));
}
public static void main(String[] args) {
final MonadSample5 test = new MonadSample5();
System.out.println(test.fail());
}
}
@@ -9,3 +9,6 @@ This module contains articles about the Java ArrayList collection
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
- [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element)
- [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size)
- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search)
- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple)
- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings)
@@ -5,6 +5,33 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-array-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.plugin.version}</version>
<configuration>
<argLine>
--add-opens java.base/java.util=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>16</maven-compiler-plugin.source>
<maven-compiler-plugin.target>16</maven-compiler-plugin.target>
<surefire.plugin.version>3.0.0-M3</surefire.plugin.version>
</properties>
<name>core-java-collections-array-list</name>
<packaging>jar</packaging>
@@ -20,6 +47,12 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,14 @@
package com.baeldung.list.ignorecase;
import java.util.List;
public class IgnoreCaseSearchUtil {
public static boolean ignoreCaseContains(List<String> theList, String searchStr) {
for (String s : theList) {
if (searchStr.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.list.ignorecase;
import java.util.ArrayList;
import java.util.Collection;
public class IgnoreCaseStringList extends ArrayList<String> {
public IgnoreCaseStringList() {
}
public IgnoreCaseStringList(Collection<? extends String> c) {
super(c);
}
@Override
public boolean contains(Object o) {
String searchStr = (String) o;
// Using Stream API:
// return this.stream().anyMatch(searchStr::equalsIgnoreCase);
for (String s : this) {
if (searchStr.equalsIgnoreCase(s)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.listofobjectstolistofstring;
public class Node {
private final int x;
private final int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Node (" + "x=" + x + ", y=" + y + ')';
}
}
@@ -0,0 +1,14 @@
package com.baeldung.listofobjectstolistofstring;
public class User {
private final String fullName;
public User(String fullName) {
this.fullName = fullName;
}
@Override
public String toString() {
return "User (" + "full name='" + fullName + ')';
}
}
@@ -0,0 +1,26 @@
package com.baeldung.triple;
public class Triple<L, M, R> {
private final L left;
private final M middle;
private final R right;
public Triple(L left, M middle, R right) {
this.left = left;
this.middle = middle;
this.right = right;
}
public L getLeft() {
return left;
}
public M getMiddle() {
return middle;
}
public R getRight() {
return right;
}
}
@@ -0,0 +1,45 @@
package com.baeldung.list.ignorecase;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class IgnoreCaseContainsUnitTest {
private static final List<String> LANGUAGES = Arrays.asList("Java", "Python", "Kotlin", "Ruby", "Javascript", "Go");
@Test
void givenStringList_whenCallTheStandardContains_shouldReturnFalse() {
String searchStr = "jAvA";
boolean result = LANGUAGES.contains(searchStr);
assertFalse(result);
}
@Test
void givenStringList_whenSearchIgnoreCaseUsingStreamAPI_shouldReturnTrue() {
String searchStr = "koTliN";
boolean result = LANGUAGES.stream().anyMatch(searchStr::equalsIgnoreCase);
assertTrue(result);
}
@Test
void givenStringList_whenUsingUtilClass_shouldReturnTrue() {
String searchStr = "ruBY";
boolean result = IgnoreCaseSearchUtil.ignoreCaseContains(LANGUAGES, searchStr);
assertTrue(result);
}
@Test
void givenStringList_whenUsingIgnoreCaseStringList_shouldReturnTrue() {
String searchStr = "pYtHoN";
List<String> ignoreCaseList = new IgnoreCaseStringList(LANGUAGES);
boolean result = ignoreCaseList.contains(searchStr);
assertTrue(result);
boolean resultContainAll = ignoreCaseList.containsAll(Arrays.asList("pYtHon", "jAvA", "koTliN", "ruBY"));
assertTrue(resultContainAll);
}
}
@@ -0,0 +1,92 @@
package com.baeldung.listofobjectstolistofstring;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class ConvertObjectListToStringListUnitTest {
@Test
public void givenObjectList_whenForEachUsedToConvert_thenReturnSuccess() {
List<String> outputList = new ArrayList<>(objectListWithNull().size());
for (Object obj : objectListWithNull()) {
outputList.add(Objects.toString(obj, null));
}
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectList_whenUsingStreamsToConvert_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithNull().stream()
.map((obj) -> Objects.toString(obj, null))
.collect(Collectors.toList());
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectList_whenUsingStreamsUnmodifiableListToConvert_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithNull().stream()
.filter(Objects::nonNull)
.map((obj) -> Objects.toString(obj, null))
.collect(Collectors.toUnmodifiableList());
Assert.assertEquals(expectedStringListWithoutNull(), outputList);
}
@Test
public void givenObjectList_whenUsingGuavaTransform_thenReturnSuccess() {
List<String> outputList;
outputList = Lists.transform(objectListWithNull(), obj -> Objects.toString(obj, null));
Assert.assertEquals(expectedStringListWithNull(), outputList);
}
@Test
public void givenObjectListWithNoNull_whenUsingToList_thenReturnSuccess() {
List<String> outputList;
outputList = objectListWithoutNull().stream()
.map((obj) -> Objects.toString(obj, null))
.toList();
Assert.assertEquals(expectedStringListWithoutNull(), outputList);
}
private List<String> expectedStringListWithNull() {
List<String> listOfStrings = new ArrayList<>();
listOfStrings.add("1");
listOfStrings.add("true");
listOfStrings.add("hello");
listOfStrings.add(Double.toString(273773.98));
listOfStrings.add(null);
listOfStrings.add(new Node(2, 4).toString());
listOfStrings.add(new User("John Doe").toString());
return listOfStrings;
}
private List<Object> objectListWithNull() {
List<Object> listOfStrings = new ArrayList<>();
listOfStrings.add(1);
listOfStrings.add(true);
listOfStrings.add("hello");
listOfStrings.add(Double.valueOf(273773.98));
listOfStrings.add(null);
listOfStrings.add(new Node(2, 4));
listOfStrings.add(new User("John Doe"));
return listOfStrings;
}
private List<String> expectedStringListWithoutNull() {
return List.of("1", "true", "hello", Double.toString(273773.98), new Node(2, 4).toString(), new User("John Doe").toString());
}
private List<Object> objectListWithoutNull() {
return List.of(1, true, "hello", Double.valueOf(273773.98), new Node(2, 4), new User("John Doe"));
}
}
@@ -0,0 +1,105 @@
package com.baeldung.triple;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class TripleInListUnitTest {
enum OP {
PLUS("+"), MINUS("-"), MULTIPLY("x");
final String opSign;
OP(String x) {
this.opSign = x;
}
}
private String createQuestion(Long num1, OP operator, Long num2) {
long result;
switch (operator) {
case PLUS:
result = num1 + num2;
break;
case MINUS:
result = num1 - num2;
break;
case MULTIPLY:
result = num1 * num2;
break;
default:
throw new IllegalArgumentException("Unknown operator");
}
return String.format("%d %s %d = ? ( answer: %d )", num1, operator.opSign, num2, result);
}
private static final List<String> EXPECTED_QUESTIONS = Arrays.asList(
"100 - 42 = ? ( answer: 58 )",
"100 + 42 = ? ( answer: 142 )",
"100 x 42 = ? ( answer: 4200 )");
@Test
void givenTripleValues_whenStoreAsList_thenTypeIsNotSafe() {
List myTriple1 = new ArrayList(3);
myTriple1.add(100L);
myTriple1.add(OP.MINUS);
myTriple1.add(42L);
List myTriple2 = new ArrayList(3);
myTriple2.add(100L);
myTriple2.add(OP.PLUS);
myTriple2.add(42L);
List myTriple3 = new ArrayList(3);
myTriple3.add(100L);
myTriple3.add(OP.MULTIPLY);
myTriple3.add(42L);
List<List> listOfTriples = new ArrayList<>(Arrays.asList(myTriple1, myTriple2, myTriple3));
List oopsTriple = new ArrayList(3);
oopsTriple.add("Oops");
oopsTriple.add(911L);
oopsTriple.add("The type is wrong");
listOfTriples.add(oopsTriple);
assertEquals(4, listOfTriples.size());
List<String> questions = listOfTriples.stream()
.filter(
triple -> triple.size() == 3
&& triple.get(0) instanceof Long
&& triple.get(1) instanceof OP
&& triple.get(2) instanceof Long
).map(triple -> {
Long left = (Long) triple.get(0);
OP op = (OP) triple.get(1);
Long right = (Long) triple.get(2);
return createQuestion(left, op, right);
}).collect(Collectors.toList());
assertEquals(EXPECTED_QUESTIONS, questions);
}
@Test
void givenTripleValues_whenUsingTheTripleClass_thenTypeIsSafeAndNeat() {
Triple<Long, OP, Long> triple1 = new Triple<>(100L, OP.MINUS, 42L);
Triple<Long, OP, Long> triple2 = new Triple<>(100L, OP.PLUS, 42L);
Triple<Long, OP, Long> triple3 = new Triple<>(100L, OP.MULTIPLY, 42L);
Triple<String, Long, String> tripleOops = new Triple<>("Oops", 911L, "The type is wrong");
List<Triple<Long, OP, Long>> listOfTriples = new ArrayList<>(Arrays.asList(triple1, triple2, triple3));
// listOfTriples.add(tripleOops); // Compiler error: "java: incompatible types ... "
List<String> questions = listOfTriples.stream()
.map(triple -> createQuestion(triple.getLeft(), triple.getMiddle(), triple.getRight()))
.collect(Collectors.toList());
assertEquals(EXPECTED_QUESTIONS, questions);
}
}
@@ -5,4 +5,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
### Relevant Articles:
- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource)
- [Compiling and Executing Code From a String in Java](https://www.baeldung.com/java-string-compile-execute-code)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2)
@@ -0,0 +1,6 @@
package com.baeldung.inmemorycompilation;
public interface InMemoryClass {
void runCode();
}
@@ -0,0 +1,30 @@
package com.baeldung.inmemorycompilation;
import static java.util.Objects.requireNonNull;
import java.util.Map;
public class InMemoryClassLoader extends ClassLoader {
private final InMemoryFileManager manager;
public InMemoryClassLoader(ClassLoader parent, InMemoryFileManager manager) {
super(parent);
this.manager = requireNonNull(manager, "manager must not be null");
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Map<String, JavaClassAsBytes> compiledClasses = manager
.getBytesMap();
if (compiledClasses.containsKey(name)) {
byte[] bytes = compiledClasses.get(name)
.getBytes();
return defineClass(name, bytes, 0, bytes.length);
} else {
throw new ClassNotFoundException();
}
}
}
@@ -0,0 +1,52 @@
package com.baeldung.inmemorycompilation;
import java.util.Hashtable;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.StandardJavaFileManager;
public class InMemoryFileManager extends ForwardingJavaFileManager<JavaFileManager> {
private final Map<String, JavaClassAsBytes> compiledClasses;
private final ClassLoader loader;
public InMemoryFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
this.compiledClasses = new Hashtable<>();
this.loader = new InMemoryClassLoader(this.getClass()
.getClassLoader(),
this
);
}
/**
* Used to get the class loader for our compiled class. It creates an anonymous class extending
* the SecureClassLoader which uses the byte code created by the compiler and stored in the
* JavaClassObject, and returns the Class for it
*
* @param location where to place or search for file objects.
*/
@Override
public ClassLoader getClassLoader(Location location) {
return loader;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind,
FileObject sibling) {
JavaClassAsBytes classAsBytes = new JavaClassAsBytes(
className, kind);
compiledClasses.put(className, classAsBytes);
return classAsBytes;
}
public Map<String, JavaClassAsBytes> getBytesMap() {
return compiledClasses;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.inmemorycompilation;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import javax.tools.SimpleJavaFileObject;
/**
* Represents a Java class file (compiled byte-code)
*/
public class JavaClassAsBytes extends SimpleJavaFileObject {
protected final ByteArrayOutputStream bos = new ByteArrayOutputStream();
public JavaClassAsBytes(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind);
}
public byte[] getBytes() {
return bos.toByteArray();
}
@Override
public OutputStream openOutputStream() {
return bos;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.inmemorycompilation;
import static java.util.Objects.requireNonNull;
import java.net.URI;
import javax.tools.SimpleJavaFileObject;
/**
* Represents a Java source code file
*/
public class JavaSourceFromString extends SimpleJavaFileObject {
private final String sourceCode;
public JavaSourceFromString(String name, String sourceCode) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
Kind.SOURCE
);
this.sourceCode = requireNonNull(sourceCode, "sourceCode must not be null");
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return sourceCode;
}
}
@@ -0,0 +1,57 @@
package com.baeldung.inmemorycompilation;
import java.util.Collections;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InMemoryCompilationUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(InMemoryCompilationUnitTest.class);
final static String QUALIFIED_CLASS_NAME = "com.baeldung.inmemorycompilation.TestClass";
final static String SOURCE_CODE =
"package com.baeldung.inmemorycompilation;\n"
+ "public class TestClass implements InMemoryClass {\n"
+ "@Override\n"
+ " public void runCode() {\n"
+ " System.out.println(\"code is running...\");\n"
+ " }\n"
+ "}\n";
@Test
public void whenStringIsCompiled_ThenCodeShouldExecute() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
InMemoryFileManager manager = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null));
List<JavaFileObject> sourceFiles = Collections.singletonList(new JavaSourceFromString(QUALIFIED_CLASS_NAME, SOURCE_CODE));
JavaCompiler.CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, sourceFiles);
boolean result = task.call();
if (result) {
diagnostics.getDiagnostics()
.forEach(d -> LOGGER.error(String.valueOf(d)));
} else {
ClassLoader classLoader = manager.getClassLoader(null);
Class<?> clazz = classLoader.loadClass(QUALIFIED_CLASS_NAME);
InMemoryClass instanceOfClass = (InMemoryClass) clazz.newInstance();
Assertions.assertInstanceOf(InMemoryClass.class, instanceOfClass);
instanceOfClass.runCode();
}
}
}
@@ -1,10 +1,12 @@
package com.baeldung.resource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.net.URL;
@Disabled
class ClassGetResourceUnitTest {
@Test
@@ -1,10 +1,12 @@
package com.baeldung.resource;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.net.URL;
@Disabled
class ClassLoaderGetResourceUnitTest {
@Test
@@ -2,68 +2,76 @@ package com.baeldung.convertnumberbases;
public class ConvertNumberBases {
public static String convertNumberToNewBase(String number, int base, int newBase){
public static String convertNumberToNewBase(String number, int base, int newBase) {
return Integer.toString(Integer.parseInt(number, base), newBase);
}
public static String convertNumberToNewBaseCustom(String num, int base, int newBase) {
int decimalNumber = convertFromAnyBaseToDecimal(num, base);
return convertFromDecimalToBaseX(decimalNumber, newBase);
String targetBase = "";
try {
targetBase = convertFromDecimalToBaseX(decimalNumber, newBase);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return targetBase;
}
public static String convertFromDecimalToBaseX(int num, int newBase) {
public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException {
if ((newBase < 2 || newBase > 10) && newBase != 16) {
throw new IllegalArgumentException("New base must be from 2 - 10 or 16");
}
String result = "";
int remainder;
while (num > 0) {
remainder = num % newBase;
if (newBase == 16) {
if (remainder == 10)
if (remainder == 10) {
result += 'A';
else if (remainder == 11)
} else if (remainder == 11) {
result += 'B';
else if (remainder == 12)
} else if (remainder == 12) {
result += 'C';
else if (remainder == 13)
} else if (remainder == 13) {
result += 'D';
else if (remainder == 14)
} else if (remainder == 14) {
result += 'E';
else if (remainder == 15)
} else if (remainder == 15) {
result += 'F';
else
} else {
result += remainder;
} else
}
} else {
result += remainder;
}
num /= newBase;
}
return new StringBuffer(result).reverse().toString();
}
public static int convertFromAnyBaseToDecimal(String num, int base) {
if (base < 2 || (base > 10 && base != 16))
if (base < 2 || (base > 10 && base != 16)) {
return -1;
}
int val = 0;
int power = 1;
for (int i = num.length() - 1; i >= 0; i--) {
int digit = charToDecimal(num.charAt(i));
if (digit < 0 || digit >= base)
if (digit < 0 || digit >= base) {
return -1;
}
val += digit * power;
power = power * base;
}
return val;
}
public static int charToDecimal(char c) {
if (c >= '0' && c <= '9')
if (c >= '0' && c <= '9') {
return (int) c - '0';
else
} else {
return (int) c - 'A' + 10;
}
}
}
@@ -1,5 +1,6 @@
package com.baeldung.convertnumberbases;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertFromDecimalToBaseX;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBase;
import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBaseCustom;
import static org.junit.jupiter.api.Assertions.*;
@@ -17,4 +18,15 @@ class ConvertNumberBasesUnitTest {
assertEquals(convertNumberToNewBaseCustom("11001000", 2, 8), "310");
}
@Test
void whenInputIsOutOfRange_thenIllegalArgumentExceptionIsThrown() {
Exception exception = assertThrows(IllegalArgumentException.class, ()-> {
convertFromDecimalToBaseX(100, 12);
});
String expectedMessage = "New base must be from 2 - 10 or 16";
String actualMessage = exception.getMessage();
assertTrue(actualMessage.contains(expectedMessage));
}
}
@@ -6,3 +6,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
- [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null)
@@ -5,3 +5,4 @@
- [Filter Java Stream to 1 and Only 1 Element](https://www.baeldung.com/java-filter-stream-unique-element)
- [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition)
- [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams)
- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing)
@@ -59,6 +59,36 @@
<version>3.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava3</groupId>
<artifactId>rxjava</artifactId>
<version>${rx.java3.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${io.varv.version}</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>${io.reactor3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${apache.commons.collection4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${google.guava.version}</version>
</dependency>
<dependency>
<groupId>com.oath.cyclops</groupId>
<artifactId>cyclops</artifactId>
<version>${cyclops.version}</version>
</dependency>
</dependencies>
<build>
@@ -90,6 +120,12 @@
<maven.compiler.target>12</maven.compiler.target>
<rx.java.version>1.2.5</rx.java.version>
<rx.java2.version>2.2.2</rx.java2.version>
<rx.java3.version>3.1.5</rx.java3.version>
<io.varv.version>1.0.0-alpha-4</io.varv.version>
<io.reactor3.version>3.5.1</io.reactor3.version>
<apache.commons.collection4.version>4.4</apache.commons.collection4.version>
<google.guava.version>31.1-jre</google.guava.version>
<cyclops.version>10.4.1</cyclops.version>
</properties>
</project>
@@ -0,0 +1,47 @@
package com.baeldung.streams.processing;
import static java.util.Spliterator.ORDERED;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CustomBatchIterator<T> implements Iterator<List<T>> {
private final int batchSize;
private List<T> currentBatch;
private final Iterator<T> iterator;
public CustomBatchIterator(Iterator<T> sourceIterator, int batchSize) {
this.batchSize = batchSize;
this.iterator = sourceIterator;
}
@Override
public List<T> next() {
return currentBatch;
}
@Override
public boolean hasNext() {
prepareNextBatch();
return currentBatch != null && !currentBatch.isEmpty();
}
public static <T> Stream<List<T>> batchStreamOf(Stream<T> stream, int batchSize) {
return stream(new CustomBatchIterator<>(stream.iterator(), batchSize));
}
private static <T> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, ORDERED), false);
}
private void prepareNextBatch() {
currentBatch = new ArrayList<>(batchSize);
while (iterator.hasNext() && currentBatch.size() < batchSize) {
currentBatch.add(iterator.next());
}
}
}
@@ -0,0 +1,141 @@
package com.baeldung.streams.processing;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.collections4.ListUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.google.common.collect.Iterators;
import cyclops.data.LazySeq;
import cyclops.reactive.ReactiveSeq;
import io.reactivex.rxjava3.core.Observable;
import reactor.core.publisher.Flux;
public class StreamProcessingUnitTest {
public final int BATCH_SIZE = 10;
private final List<Integer> firstBatch = List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
private final List<Integer> secondBatch = List.of(10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
private final List<Integer> thirdBatch = List.of(20, 21, 22, 23, 24, 25, 26, 27, 28, 29);
private final List<Integer> fourthBatch = List.of(30, 31, 32, 33);
public Stream<Integer> data;
@BeforeEach
public void setUp() {
data = IntStream.range(0, 34)
.boxed();
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingSpliterator_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>();
CustomBatchIterator.batchStreamOf(data, BATCH_SIZE)
.forEach(result::add);
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingCollectionAPI_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = data.collect(Collectors.groupingBy(it -> it / BATCH_SIZE))
.values();
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchParallelUsingCollectionAPI_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = data.parallel()
.collect(Collectors.groupingBy(it -> it / BATCH_SIZE))
.values();
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingRxJavaV3_thenFourBatchesAreObtained() {
// RxJava v3
Collection<List<Integer>> result = new ArrayList<>();
Observable.fromStream(data)
.buffer(BATCH_SIZE)
.subscribe(result::add);
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingReactor_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>();
Flux.fromStream(data)
.buffer(BATCH_SIZE)
.subscribe(result::add);
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingApacheCommon_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>(ListUtils.partition(data.collect(Collectors.toList()), BATCH_SIZE));
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingGuava_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>();
Iterators.partition(data.iterator(), BATCH_SIZE)
.forEachRemaining(result::add);
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingCyclops_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>();
ReactiveSeq.fromStream(data)
.grouped(BATCH_SIZE)
.toList()
.forEach(value -> result.add(value.collect(Collectors.toList())));
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
@Test
public void givenAStreamOfData_whenIsProcessingInBatchUsingCyclopsLazy_thenFourBatchesAreObtained() {
Collection<List<Integer>> result = new ArrayList<>();
LazySeq.fromStream(data)
.grouped(BATCH_SIZE)
.toList()
.forEach(value -> result.add(value.collect(Collectors.toList())));
assertTrue(result.contains(firstBatch));
assertTrue(result.contains(secondBatch));
assertTrue(result.contains(thirdBatch));
assertTrue(result.contains(fourthBatch));
}
}

Some files were not shown because too many files have changed in this diff Show More