Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -10,3 +10,4 @@ This module contains complete guides about arrays in Java
|
||||
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
|
||||
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
|
||||
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)
|
||||
- [Print a Java 2D Array](https://www.baeldung.com/java-2d-array-print)
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
class EquilibriumIndexFinder {
|
||||
|
||||
List<Integer> findEquilibriumIndexes(int[] array) {
|
||||
int[] partialSums = new int[array.length + 1];
|
||||
partialSums[0] = 0;
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
partialSums[i+1] = partialSums[i] + array[i];
|
||||
}
|
||||
|
||||
List<Integer> equilibriumIndexes = new ArrayList<Integer>();
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
if (partialSums[i] == (partialSums[array.length] - (partialSums[i+1]))) {
|
||||
equilibriumIndexes.add(i);
|
||||
}
|
||||
}
|
||||
return equilibriumIndexes;
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.equilibriumindex;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EquilibriumIndexFinderUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayHasEquilibriumIndexes_whenFindEquilibriumIndexes_thenListAllEquilibriumIndexes() {
|
||||
int[] array = {1, -3, 0, 4, -5, 4, 0, 1, -2, -1};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(1, 4, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutEquilibriumIndexes_whenFindEquilibriumIndexes_thenEmptyList() {
|
||||
int[] array = {1, 2, 3};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithOneElement_whenFindEquilibriumIndexes_thenListFirstIndex() {
|
||||
int[] array = {5};
|
||||
assertThat(new EquilibriumIndexFinder().findEquilibriumIndexes(array)).containsExactly(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,3 +6,4 @@ This module contains articles about Java Character Class
|
||||
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
|
||||
- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
|
||||
- [Increment Character in Java](https://www.baeldung.com/java-char-sequence)
|
||||
- [Creating Unicode Character From Its Code Point Hex String](https://www.baeldung.com/java-unicode-character-from-code-point-hex-string)
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
public class CountDownLatchDemo {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
// Create a CountDownLatch with an initial count equal to the number of tasks to be completed
|
||||
int numberOfTasks = 3;
|
||||
CountDownLatch latch = new CountDownLatch(numberOfTasks);
|
||||
|
||||
// Simulate completion of tasks by worker threads
|
||||
for (int i = 1; i <= numberOfTasks; i++) {
|
||||
new Thread(() -> {
|
||||
System.out.println("Task completed by Thread " + Thread.currentThread()
|
||||
.getId());
|
||||
|
||||
// Decrement the latch count to signal completion of a task
|
||||
latch.countDown();
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Main thread waits until all tasks are completed
|
||||
latch.await();
|
||||
System.out.println("All tasks completed. Main thread proceeds.");
|
||||
|
||||
// Attempting to reset will have no effect
|
||||
latch.countDown();
|
||||
// Latch is already at zero, await() returns immediately
|
||||
latch.await(); // This line won't block
|
||||
System.out.println("Latch is already at zero and cannot be reset.");
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.countdownlatchvssemaphore;
|
||||
|
||||
import java.util.concurrent.Semaphore;
|
||||
|
||||
public class SemaphoreDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Create a Semaphore with a fixed number of permits
|
||||
int NUM_PERMITS = 3;
|
||||
Semaphore semaphore = new Semaphore(NUM_PERMITS);
|
||||
|
||||
// Simulate resource access by worker threads
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Acquire a permit to access the resource
|
||||
semaphore.acquire();
|
||||
System.out.println("Thread " + Thread.currentThread().getId() + " accessing resource.");
|
||||
|
||||
// Simulate resource usage
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// Release the permit after resource access is complete
|
||||
semaphore.release();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
// Simulate resetting the Semaphore by releasing additional permits after a delay
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
|
||||
// Resetting the semaphore permits to the initial count
|
||||
semaphore.release(NUM_PERMITS);
|
||||
System.out.println("Semaphore permits reset to initial count.");
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,4 @@ This module contains articles about date operations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Calculate Number of Weekdays Between Two Dates in Java](https://www.baeldung.com/java-count-weekdays-between-two-dates)
|
||||
|
||||
- [Convert Long to Date in Java](https://www.baeldung.com/java-long-date-conversion)
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
This module contains articles about converting between Java date and time objects.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Convert Gregorian to Hijri Date in Java](https://www.baeldung.com/java-date-gregorian-hijri-conversion)
|
||||
|
||||
@@ -14,3 +14,4 @@ This module contains articles about core features in the Java language
|
||||
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
||||
- [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context)
|
||||
- [Recursively Sum the Integers in an Array](https://www.baeldung.com/java-recursive-sum-integer-array)
|
||||
- [Set an Environment Variable at Runtime in Java](https://www.baeldung.com/java-set-environment-variable-runtime)
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.customurlconnection;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
public class CustomURLConnection extends URLConnection {
|
||||
private final String simulatedData = "This is the simulated data from the resource.";
|
||||
private URL url;
|
||||
private boolean connected = false;
|
||||
private String headerValue = "SimulatedHeaderValue";
|
||||
|
||||
protected CustomURLConnection(URL url) {
|
||||
super(url);
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect() throws IOException {
|
||||
connected = true;
|
||||
System.out.println("Connection established to: " + url);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
if (!connected) {
|
||||
connect();
|
||||
}
|
||||
return new ByteArrayInputStream(simulatedData.getBytes());
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream getOutputStream() throws IOException {
|
||||
ByteArrayOutputStream simulatedOutput = new ByteArrayOutputStream();
|
||||
return simulatedOutput;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getContentLength() {
|
||||
return simulatedData.length();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeaderField(String name) {
|
||||
if ("SimulatedHeader".equalsIgnoreCase(name)) { // Example header name
|
||||
return headerValue;
|
||||
} else {
|
||||
return null; // Header not found
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.customurlconnection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
import java.net.URLStreamHandler;
|
||||
|
||||
public class CustomURLStreamHandler extends URLStreamHandler {
|
||||
|
||||
@Override
|
||||
protected URLConnection openConnection(URL u) throws IOException {
|
||||
// Create and return an instance of CustomURLConnection
|
||||
return new CustomURLConnection(u);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.customurlconnection;
|
||||
|
||||
import java.net.URLStreamHandler;
|
||||
import java.net.URLStreamHandlerFactory;
|
||||
|
||||
public class CustomURLStreamHandlerFactory implements URLStreamHandlerFactory {
|
||||
|
||||
@Override
|
||||
public URLStreamHandler createURLStreamHandler(String protocol) {
|
||||
// Check if the requested protocol is our custom protocol
|
||||
if ("myprotocol".equals(protocol)) {
|
||||
return new CustomURLStreamHandler();
|
||||
}
|
||||
return null; // Let the default handler deal with other protocols
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.customurlconnection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
URL.setURLStreamHandlerFactory(new CustomURLStreamHandlerFactory());
|
||||
|
||||
try {
|
||||
URL url = new URL("myprotocol://example.com/resource");
|
||||
|
||||
CustomURLConnection customConnection = (CustomURLConnection) url.openConnection();
|
||||
customConnection.connect();
|
||||
|
||||
InputStream inputStream = customConnection.getInputStream();
|
||||
|
||||
String content = new Scanner(inputStream).useDelimiter("\\A").next();
|
||||
System.out.println(content);
|
||||
|
||||
int contentLength = customConnection.getContentLength();
|
||||
System.out.println("Content Length: " + contentLength);
|
||||
|
||||
String headerValue = customConnection.getHeaderField("SimulatedHeader");
|
||||
System.out.println("Header Value: " + headerValue);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.urlencoder;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SpaceURLEncoderUnitTest {
|
||||
|
||||
@Test
|
||||
void givenSpaceInString_whenUsingDefaultEncoding_thenReturnPlusSign() {
|
||||
String originalString = "Welcome to the Baeldung Website!";
|
||||
String encodedString = URLEncoder.encode(originalString);
|
||||
assertEquals("Welcome+to+the+Baeldung+Website%21", encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSpaceInString_whenUsingUTF8Encoding_thenReturnPlusSign() throws UnsupportedEncodingException {
|
||||
String originalString = "Welcome to the Baeldung Website!";
|
||||
String encodedString = URLEncoder.encode(originalString, StandardCharsets.UTF_8.toString());
|
||||
assertEquals("Welcome+to+the+Baeldung+Website%21", encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSpaceInString_whenUsingDefaultEncodingAndReplace_thenReturnPct20() throws UnsupportedEncodingException {
|
||||
String originalString = "Welcome to the Baeldung Website!";
|
||||
String encodedString = URLEncoder.encode(originalString)
|
||||
.replace("+", "%20");
|
||||
assertEquals("Welcome%20to%20the%20Baeldung%20Website%21", encodedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSpaceInString_whenUsingDefaultEncodingAndReplaceAll_thenReturnPct20() throws UnsupportedEncodingException {
|
||||
String originalString = "Welcome to the Baeldung Website!";
|
||||
String encodedString = URLEncoder.encode(originalString)
|
||||
.replaceAll("\\+", "%20");
|
||||
assertEquals("Welcome%20to%20the%20Baeldung%20Website%21", encodedString);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -22,7 +22,7 @@ public class URLNormalizationUnitTest {
|
||||
String normalizedUri = originalUrl.split("\\?")[0];
|
||||
assertEquals(expectedNormalizedUrl, normalizedUri);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid URL: " + originalUrl);
|
||||
fail(originalUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ public class URLNormalizationUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOriginalUrl_whenUsingRegularExpression_thenNormalizedUrl() throws URISyntaxException, UnsupportedEncodingException {
|
||||
public void givenOriginalUrl_whenUsingRegularExpression_thenNormalizedUrl() {
|
||||
String regex = "^(https?://[^/]+/[^?#]+)";
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matcher = pattern.matcher(originalUrl);
|
||||
@@ -44,7 +44,7 @@ public class URLNormalizationUnitTest {
|
||||
String normalizedUrl = matcher.group(1);
|
||||
assertEquals(expectedNormalizedUrl, normalizedUrl);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid URL: " + originalUrl);
|
||||
fail(originalUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.reflection.innerclass;
|
||||
|
||||
public class Person {
|
||||
String name;
|
||||
Address address;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public class Address {
|
||||
String zip;
|
||||
|
||||
public Address(String zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.reflection.innerclass;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CreateInnerClassWithReflectionUnitTest {
|
||||
|
||||
static Logger logger = LoggerFactory.getLogger(CreateInnerClassWithReflectionUnitTest.class);
|
||||
|
||||
@Test
|
||||
void givenInnerClass_whenUseReflection_thenShowConstructors() {
|
||||
final String personBuilderClassName = "com.baeldung.reflection.innerclass.Person$Builder";
|
||||
final String personAddressClassName = "com.baeldung.reflection.innerclass.Person$Address";
|
||||
assertDoesNotThrow(() -> logConstructors(Class.forName(personAddressClassName)));
|
||||
assertDoesNotThrow(() -> logConstructors(Class.forName(personBuilderClassName)));
|
||||
}
|
||||
|
||||
private static void logConstructors(Class<?> clazz) {
|
||||
Arrays.stream(clazz.getDeclaredConstructors())
|
||||
.map(c -> formatConstructorSignature(c))
|
||||
.forEach(logger::info);
|
||||
}
|
||||
|
||||
private static String formatConstructorSignature(Constructor<?> constructor) {
|
||||
String params = Arrays.stream(constructor.getParameters())
|
||||
.map(parameter -> parameter.getType().getSimpleName() + " " + parameter.getName())
|
||||
.collect(Collectors.joining(", "));
|
||||
return constructor.getName() + "(" + params + ")";
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStaticInnerClass_whenUseReflection_thenInstantiate()
|
||||
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
|
||||
InstantiationException, IllegalAccessException {
|
||||
final String personBuilderClassName = "com.baeldung.reflection.innerclass.Person$Builder";
|
||||
Class<Person.Builder> personBuilderClass = (Class<Person.Builder>) Class.forName(personBuilderClassName);
|
||||
Person.Builder personBuilderObj = personBuilderClass.getDeclaredConstructor().newInstance();
|
||||
assertTrue(personBuilderObj instanceof Person.Builder);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonStaticInnerClass_whenUseReflection_thenInstantiate()
|
||||
throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
|
||||
InstantiationException, IllegalAccessException {
|
||||
final String personClassName = "com.baeldung.reflection.innerclass.Person";
|
||||
final String personAddressClassName = "com.baeldung.reflection.innerclass.Person$Address";
|
||||
|
||||
Class<Person> personClass = (Class<Person>) Class.forName(personClassName);
|
||||
Person personObj = personClass.getConstructor().newInstance();
|
||||
|
||||
Class<Person.Address> personAddressClass = (Class<Person.Address>) Class.forName(personAddressClassName);
|
||||
|
||||
assertThrows(NoSuchMethodException.class, () -> personAddressClass.getDeclaredConstructor(String.class));
|
||||
|
||||
Constructor<Person.Address> constructorOfPersonAddress = personAddressClass.getDeclaredConstructor(Person.class, String.class);
|
||||
Person.Address personAddressObj = constructorOfPersonAddress.newInstance(personObj, "751003");
|
||||
assertTrue(personAddressObj instanceof Person.Address);
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.stream.range;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class StreamRangeUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenRangeStreamUsingLimitSkip_thenPrintsRange() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
List<Integer> expectedRange = Arrays.asList(3, 4, 5, 6, 7);
|
||||
|
||||
List<Integer> range = numbers.stream()
|
||||
.skip(2)
|
||||
.limit(5)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(expectedRange, range);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRangeStreamUsingCollectingAndThen_thenPrintsRange() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
List<Integer> expectedRange = Arrays.asList(3, 4, 5, 6, 7);
|
||||
|
||||
List<Integer> range = numbers.stream()
|
||||
.filter(n -> n >= 3 && n <= 7)
|
||||
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
|
||||
|
||||
assertEquals(expectedRange, range);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.string.runlength;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class RunLengthEncodingUnitTest {
|
||||
private static final String INPUT = "WWWWWWWWWWWWBAAACCDEEEEE";
|
||||
private static final String RLE = "12W1B3A2C1D5E";
|
||||
|
||||
String runLengthEncode(String input) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
int count = 1;
|
||||
char[] chars = input.toCharArray();
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
char c = chars[i];
|
||||
if (i + 1 < chars.length && c == chars[i + 1]) {
|
||||
count++;
|
||||
} else {
|
||||
result.append(count).append(c);
|
||||
count = 1;
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
|
||||
String runLengthDecode(String rle) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
char[] chars = rle.toCharArray();
|
||||
|
||||
int count = 0;
|
||||
for (char c : chars) {
|
||||
if (Character.isDigit(c)) {
|
||||
count = 10 * count + Character.getNumericValue(c);
|
||||
} else {
|
||||
result.append(String.join("", Collections.nCopies(count, String.valueOf(c))));
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
String runLengthEncodeByRegEx(String input) {
|
||||
String[] arr = input.split("(?<=(\\D))(?!\\1)");
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (String run : arr) {
|
||||
result.append(run.length()).append(run.charAt(0));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
String runLengthDecodeByRegEx(String rle) {
|
||||
if (rle.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String[] arr = rle.split("(?<=\\D)|(?=\\D+)");
|
||||
if (arr.length % 2 != 0) {
|
||||
throw new IllegalArgumentException("Not a RLE string");
|
||||
}
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int i = 1; i <= arr.length; i += 2) {
|
||||
int count = Integer.parseInt(arr[i - 1]);
|
||||
String c = arr[i];
|
||||
|
||||
result.append(String.join("", Collections.nCopies(count, c)));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInvokingRunLengthEncode_thenGetExpectedResult() {
|
||||
assertEquals(RLE, runLengthEncode(INPUT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInvokingRunLengthDecode_thenGetExpectedResult() {
|
||||
assertEquals(INPUT, runLengthDecode(RLE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInvokingRunLengthEncodeByRegEx_thenGetExpectedResult() {
|
||||
assertEquals(RLE, runLengthEncodeByRegEx(INPUT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenInvokingRunLengthDecodeByRegEx_thenGetExpectedResult() {
|
||||
assertEquals(INPUT, runLengthDecodeByRegEx(RLE));
|
||||
}
|
||||
}
|
||||
@@ -14,3 +14,4 @@
|
||||
- [UTF-8 Validation in Java](https://www.baeldung.com/java-utf-8-validation)
|
||||
- [Simple Morse Code Translation in Java](https://www.baeldung.com/java-morse-code-english-translate)
|
||||
- [How to Determine if a String Contains Invalid Encoded Characters](https://www.baeldung.com/java-check-string-contains-invalid-encoded-characters)
|
||||
- [Regular Expression for Password Validation in Java](https://www.baeldung.com/java-regex-password-validation)
|
||||
|
||||
+3
-3
@@ -14,7 +14,7 @@ public class DecodeUUIDStringFromBase64UnitTest {
|
||||
private final UUID originalUUID = UUID.fromString("cc5f93f7-8cf1-4a51-83c6-e740313a0c6c");
|
||||
|
||||
@Test
|
||||
public void shouldDecodeUUIDUsingByteArrayAndBase64Decoder() {
|
||||
public void givenEncodedString_whenDecodingUsingBase64Decoder_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] decodedBytes = Base64.getDecoder()
|
||||
.decode(expectedEncodedString);
|
||||
@@ -23,7 +23,7 @@ public class DecodeUUIDStringFromBase64UnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeUUIDUsingByteBufferAndBase64UrlDecoder() {
|
||||
public void givenEncodedString_whenDecodingUsingByteBufferAndBase64UrlDecoder_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "zF-T94zxSlGDxudAMToMbA";
|
||||
byte[] decodedBytes = Base64.getUrlDecoder()
|
||||
.decode(expectedEncodedString);
|
||||
@@ -35,7 +35,7 @@ public class DecodeUUIDStringFromBase64UnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDecodeUUIDUsingApacheUtils() {
|
||||
public void givenEncodedString_whenDecodingUsingApacheUtils_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] decodedBytes = decodeBase64(expectedEncodedString);
|
||||
UUID uuid = Conversion.byteArrayToUuid(decodedBytes, 0);
|
||||
|
||||
+3
-3
@@ -14,7 +14,7 @@ public class EncodeUUIDToBase64StringUnitTest {
|
||||
private final UUID originalUUID = UUID.fromString("cc5f93f7-8cf1-4a51-83c6-e740313a0c6c");
|
||||
|
||||
@Test
|
||||
public void shouldEncodeUUIDUsingByteArrayAndBase64Encoder() {
|
||||
public void givenUUID_whenEncodingUsingBase64Encoder_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] uuidBytes = convertToByteArray(originalUUID);
|
||||
String encodedUUID = Base64.getEncoder().withoutPadding()
|
||||
@@ -23,7 +23,7 @@ public class EncodeUUIDToBase64StringUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeUUIDUsingByteBufferAndBase64UrlEncoder() {
|
||||
public void givenUUID_whenEncodingUsingByteBufferAndBase64UrlEncoder_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "zF-T94zxSlGDxudAMToMbA";
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(originalUUID.getMostSignificantBits());
|
||||
@@ -34,7 +34,7 @@ public class EncodeUUIDToBase64StringUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldEncodeUUIDUsingApacheUtils() {
|
||||
public void givenUUID_whenEncodingUsingApacheUtils_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] bytes = Conversion.uuidToByteArray(originalUUID, new byte[16], 0, 16);
|
||||
String encodedUUID = encodeBase64URLSafeString(bytes);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Structured Logging in Java](https://www.baeldung.com/java-structured-logging)
|
||||
@@ -8,6 +8,36 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>maven-exec-plugin</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven.shared</groupId>
|
||||
<artifactId>maven-invoker</artifactId>
|
||||
<version>${apache.maven.invoker.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.maven</groupId>
|
||||
<artifactId>maven-embedder</artifactId>
|
||||
<version>${apache.maven.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@@ -38,6 +68,9 @@
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.12.1</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>3.1.0</exec-maven-plugin.version>
|
||||
<junit.jupiter.version>5.10.0</junit.jupiter.version>
|
||||
<apache.maven.version>3.9.6</apache.maven.version>
|
||||
<apache.maven.invoker.version>3.2.0</apache.maven.invoker.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.learningplatform;
|
||||
|
||||
public enum JavaVersion {
|
||||
|
||||
JAVA_8("1.8"), JAVA_9("9"), JAVA_17("17");
|
||||
|
||||
private final String version;
|
||||
|
||||
|
||||
JavaVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return this.version;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.learningplatform;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public interface Maven {
|
||||
String POM_XML = "pom.xml";
|
||||
String COMPILE_GOAL = "compile";
|
||||
String USE_CUSTOM_POM = "-f";
|
||||
int OK = 0;
|
||||
String MVN = "mvn";
|
||||
|
||||
void compile(Path projectFolder);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.learningplatform;
|
||||
|
||||
public class MavenCompilationException extends RuntimeException {
|
||||
|
||||
public MavenCompilationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public MavenCompilationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.learningplatform;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import org.apache.maven.cli.MavenCli;
|
||||
|
||||
public class MavenEmbedder implements Maven {
|
||||
|
||||
public static final String MVN_HOME = "maven.multiModuleProjectDirectory";
|
||||
|
||||
@Override
|
||||
public void compile(Path projectFolder) {
|
||||
MavenCli cli = new MavenCli();
|
||||
System.setProperty(MVN_HOME, projectFolder.toString());
|
||||
cli.doMain(new String[]{COMPILE_GOAL}, projectFolder.toString(), null, null);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user