Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
e1dcefafa8
|
@ -64,13 +64,13 @@ core-java-io/hard_link.txt
|
|||
core-java-io/target_link.txt
|
||||
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||
ethereum/logs/
|
||||
jmeter/src/main/resources/*-JMeter.csv
|
||||
jmeter/src/main/resources/*-Basic*.csv
|
||||
jmeter/src/main/resources/*-JMeter*.csv
|
||||
jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
jmeter/src/main/resources/*FileExtractionExample.csv
|
||||
jmeter/src/main/resources/*_Summary-Report.csv
|
||||
testing-modules/jmeter/src/main/resources/*-JMeter.csv
|
||||
testing-modules/jmeter/src/main/resources/*-Basic*.csv
|
||||
testing-modules/jmeter/src/main/resources/*-JMeter*.csv
|
||||
testing-modules/jmeter/src/main/resources/*ReportsDashboard*.csv
|
||||
testing-modules/jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
|
||||
testing-modules/jmeter/src/main/resources/*FileExtractionExample.csv
|
||||
testing-modules/jmeter/src/main/resources/*_Summary-Report.csv
|
||||
|
||||
ninja/devDb.mv.db
|
||||
|
||||
|
@ -128,3 +128,6 @@ persistence-modules/neo4j/data/**
|
|||
/deep-shallow-copy/.mvn/wrapper
|
||||
/deep-shallow-copy/mvnw
|
||||
/deep-shallow-copy/mvnw.cmd
|
||||
|
||||
#spring-5-webflux-2
|
||||
**/testdb.mv.db
|
|
@ -14,16 +14,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
|
||||
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Node;
|
||||
|
|
|
@ -6,4 +6,5 @@
|
|||
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
||||
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
||||
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
|
||||
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class FirstNonRepeatingElement {
|
||||
public static Integer findFirstNonRepeatingUsingForLoop(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
int current = list.get(i);
|
||||
boolean isRepeating = false;
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (i != j && current == list.get(j)) {
|
||||
isRepeating = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isRepeating) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatedElementUsingIndex(List<Integer> list) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (list.indexOf(list.get(i)) == list.lastIndexOf(list.get(i))) {
|
||||
return list.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingHashMap(List<Integer> list) {
|
||||
Map<Integer, Integer> counts = new HashMap<>();
|
||||
for (int num : list) {
|
||||
counts.put(num, counts.getOrDefault(num, 0) + 1);
|
||||
}
|
||||
for (int num : list) {
|
||||
if (counts.get(num) == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer findFirstNonRepeatingUsingArray(List<Integer> list) {
|
||||
int maxElement = Collections.max(list);
|
||||
int[] frequency = new int[maxElement + 1];
|
||||
for (int num : list) {
|
||||
frequency[num]++;
|
||||
}
|
||||
for (int num : list) {
|
||||
if (frequency[num] == 1) {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.algorithms.firstnonrepeating;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class FirstNonRepeatingElementUnitTest {
|
||||
|
||||
private List<Integer> list;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
list = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingForLoop_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingForLoop(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingIndexOf_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatedElementUsingIndex(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingHashMap_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingHashMap(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingArray_thenReturnFirstNonRepeatingElement() {
|
||||
int result = FirstNonRepeatingElement.findFirstNonRepeatingUsingArray(list);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
}
|
|
@ -20,8 +20,4 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -48,7 +48,6 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
<jakarta-xml.version>4.0.0</jakarta-xml.version>
|
||||
<jakarta.jws.version>3.0.0</jakarta.jws.version>
|
||||
</properties>
|
||||
|
|
|
@ -16,12 +16,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http-jetty</artifactId>
|
||||
<version>4.0.0</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.xml.ws</groupId>
|
||||
|
|
|
@ -115,6 +115,7 @@
|
|||
</profiles>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<spring.version>5.3.25</spring.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
|
|
|
@ -35,7 +35,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<cxf.version>4.0.0</cxf.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -16,12 +16,12 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-client</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-rs-sse</artifactId>
|
||||
<version>${cxf-version}</version>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.ws.rs</groupId>
|
||||
|
@ -60,7 +60,6 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<cxf-version>4.0.0</cxf-version>
|
||||
<jakarta-ws.version>3.1.0</jakarta-ws.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
## Relevant Articles
|
||||
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
|
||||
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)
|
||||
- [Apply Bold Text Style for an Entire Row Using Apache POI](https://www.baeldung.com/appache-poi-apply-bold-text-style-entire-row)
|
||||
|
|
|
@ -97,7 +97,7 @@
|
|||
<json-simple.version>1.1.1</json-simple.version>
|
||||
<aws-lambda-java-events.version>3.11.0</aws-lambda-java-events.version>
|
||||
<aws-lambda-java-core.version>1.2.1</aws-lambda-java-core.version>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -46,7 +46,7 @@
|
|||
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||
<jackson.version>2.16.0</jackson.version>
|
||||
<gson.version>2.10</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -63,7 +63,7 @@ public class VectorAPIExamples {
|
|||
public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) {
|
||||
float[] finalResult = new float[arr1.length];
|
||||
for (int i = 0; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
@ -77,13 +77,13 @@ public class VectorAPIExamples {
|
|||
var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i);
|
||||
var vc = va.mul(va)
|
||||
.add(vb.mul(vb))
|
||||
.neg();
|
||||
.sqrt();
|
||||
vc.intoArray(finalResult, i);
|
||||
}
|
||||
|
||||
// tail cleanup
|
||||
for (; i < arr1.length; i++) {
|
||||
finalResult[i] = (arr1[i] * arr1[i] + arr2[i] * arr2[i]) * -1.0f;
|
||||
finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]);
|
||||
}
|
||||
return finalResult;
|
||||
}
|
||||
|
|
|
@ -28,7 +28,7 @@ public class VectorAPIUnitTest {
|
|||
public void whenTwoValuesProvided_thenComputeScalarNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.scalarNormOfTwoArrays(arr1, arr2));
|
||||
}
|
||||
|
||||
|
@ -36,7 +36,7 @@ public class VectorAPIUnitTest {
|
|||
public void whenTwoValuesProvided_thenComputeVectorNorm() {
|
||||
float[] arr1 = { 1, 2.3f };
|
||||
float[] arr2 = { 1.3f, 2.0f };
|
||||
float[] result = { -2.6899998f, -9.29f };
|
||||
float[] result = { 1.6401219f, 3.047950f };
|
||||
Assertions.assertArrayEquals(result, vector.vectorNormalForm(arr1, arr2));
|
||||
}
|
||||
|
||||
|
|
|
@ -3,3 +3,4 @@
|
|||
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)
|
||||
- [Unnamed Classes and Instance Main Methods in Java 21](https://www.baeldung.com/java-21-unnamed-class-instance-main)
|
||||
- [Unnamed Patterns and Variables in Java 21](https://www.baeldung.com/java-unnamed-patterns-variables)
|
||||
- [JFR View Command in Java 21](https://www.baeldung.com/java-flight-recorder-view)
|
||||
|
|
|
@ -11,4 +11,6 @@
|
|||
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
||||
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
|
||||
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
|
||||
- [Check if Two Date Ranges Overlap](https://www.baeldung.com/java-check-two-date-ranges-overlap)
|
||||
- [Difference between ZoneOffset.UTC and ZoneId.of(“UTC”)](https://www.baeldung.com/java-zoneoffset-utc-zoneid-of)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about arrays conversion in Java
|
|||
- [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array)
|
||||
- [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array)
|
||||
- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char)
|
||||
- [Convert byte[] to Byte[] and Vice Versa in Java](https://www.baeldung.com/java-byte-array-wrapper-primitive-type-convert)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -7,10 +7,6 @@
|
|||
<name>core-java-arrays-guides</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
|
@ -34,7 +30,10 @@
|
|||
<version>${system-stubs.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.movezerototheend;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
public class MoveZeroesToTheEndOfAnArrayUnitTest {
|
||||
private static final int[] EXPECTED = new int[] { 42, 2, 3, 4, 0, 0 };
|
||||
|
||||
@Test
|
||||
void whenCreatingANewArrayAndCopyingValues_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int[] result = new int[array.length];
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
result[idx++] = n;
|
||||
}
|
||||
}
|
||||
assertArrayEquals(EXPECTED, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenMovingZeroInTheOriginalArray_thenGetTheExpectedResult() {
|
||||
int[] array = new int[] { 42, 2, 0, 3, 4, 0 };
|
||||
int idx = 0;
|
||||
for (int n : array) {
|
||||
if (n != 0) {
|
||||
array[idx++] = n;
|
||||
}
|
||||
}
|
||||
while (idx < array.length) {
|
||||
array[idx++] = 0;
|
||||
}
|
||||
assertArrayEquals(EXPECTED, array);
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
|
|
|
@ -13,4 +13,5 @@
|
|||
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
|
||||
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
|
||||
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
|
||||
- [PriorityQueue iterator() Method in Java](https://www.baeldung.com/java-priorityqueue-iterator)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
||||
|
|
|
@ -5,18 +5,6 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-5</artifactId>
|
||||
<name>core-java-collections-5</name>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>9</source>
|
||||
<target>9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
@ -61,6 +49,19 @@
|
|||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>9</source>
|
||||
<target>9</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.version>5.9.2</junit.version>
|
||||
<roaringbitmap.version>0.9.38</roaringbitmap.version>
|
||||
|
|
|
@ -55,7 +55,6 @@
|
|||
<version>${org.json.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
|
|
@ -3,3 +3,4 @@
|
|||
- [Removing the Last Node in a Linked List](https://www.baeldung.com/java-linked-list-remove-last-element)
|
||||
- [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item)
|
||||
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
|
||||
- [Reset ListIterator to First Element of the List in Java](https://www.baeldung.com/java-reset-listiterator)
|
||||
|
|
|
@ -27,7 +27,7 @@
|
|||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.9</version>
|
||||
<version>2.10.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json</groupId>
|
||||
|
|
|
@ -41,7 +41,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -2,3 +2,4 @@
|
|||
### Relevant Articles:
|
||||
- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization)
|
||||
- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture)
|
||||
- [CountDownLatch vs. Semaphore](https://www.baeldung.com/java-countdownlatch-vs-semaphore)
|
||||
|
|
|
@ -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.");
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -8,3 +8,4 @@
|
|||
- [System.console() vs. System.out](https://www.baeldung.com/java-system-console-vs-system-out)
|
||||
- [How to Log to the Console in Color](https://www.baeldung.com/java-log-console-in-color)
|
||||
- [Create Table Using ASCII in a Console in Java](https://www.baeldung.com/java-console-ascii-make-table)
|
||||
- [Printing Message on Console without Using main() Method in Java](https://www.baeldung.com/java-no-main-print-message-console)
|
||||
|
|
|
@ -2,4 +2,5 @@
|
|||
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)
|
||||
|
|
|
@ -0,0 +1,65 @@
|
|||
package com.baeldung.datetounixtimestamp;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DateToUnixTimeStampUnitTest {
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingInstantClass_thenConvertToUnixTimeStamp() {
|
||||
Instant givenDate = Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getEpochSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingLocalDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
LocalDateTime givenDate = LocalDateTime.of(2023, 10, 19, 22, 45);
|
||||
|
||||
assertEquals(1697755500L, givenDate.toEpochSecond(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingDateClass_thenConvertToUnixTimeStamp() throws ParseException {
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
Date givenDate = dateFormat.parse("2023-10-15 22:00:00");
|
||||
|
||||
assertEquals(1697407200L, givenDate.getTime() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingCalendarClass_thenConvertToUnixTimeStamp() {
|
||||
Calendar calendar = new GregorianCalendar(2023, Calendar.OCTOBER, 17);
|
||||
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
assertEquals(1697500800L, calendar.getTimeInMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeInstantClass_thenConvertToUnixTimeStamp() {
|
||||
org.joda.time.Instant givenDate = org.joda.time.Instant.parse("2020-09-08T12:16:40Z");
|
||||
|
||||
assertEquals(1599567400L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDate_whenUsingJodaTimeDateTimeClass_thenConvertToUnixTimeStamp() {
|
||||
DateTime givenDate = new DateTime("2020-09-09T12:16:40Z");
|
||||
|
||||
assertEquals(1599653800L, givenDate.getMillis() / 1000);
|
||||
}
|
||||
|
||||
}
|
|
@ -3,4 +3,5 @@
|
|||
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)
|
||||
- [Convert String Date to XMLGregorianCalendar in Java](https://www.baeldung.com/java-string-date-xmlgregoriancalendar-conversion)
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.stringdatetoxmlgregoriancalendar;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
|
||||
public class StringDateToXMLGregorianCalendarConverter {
|
||||
public static XMLGregorianCalendar usingDatatypeFactoryForDate(String dateAsString) throws DatatypeConfigurationException {
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateAsString);
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingLocalDate(String dateAsString) throws DatatypeConfigurationException {
|
||||
LocalDate localDate = LocalDate.parse(dateAsString);
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString());
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingSimpleDateFormat(String dateTimeAsString) throws DatatypeConfigurationException, ParseException {
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||||
Date date = simpleDateFormat.parse(dateTimeAsString);
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(simpleDateFormat.format(date));
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingGregorianCalendar(String dateTimeAsString) throws DatatypeConfigurationException, ParseException {
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateTimeAsString));
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
|
||||
}
|
||||
|
||||
public static XMLGregorianCalendar usingJodaTime(String dateTimeAsString) throws DatatypeConfigurationException {
|
||||
DateTime dateTime = DateTime.parse(dateTimeAsString, DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"));
|
||||
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTime.toGregorianCalendar());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.stringdatetoxmlgregoriancalendar;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StringDateToXMLGregorianCalendarConverterUnitTest {
|
||||
private static final String dateAsString = "2014-04-24";
|
||||
private static final String dateTimeAsString = "2014-04-24T15:45:30";
|
||||
|
||||
@Test
|
||||
void givenStringDate_whenUsingDatatypeFactory_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingDatatypeFactoryForDate(dateAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingApacheCommonsLang3_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingLocalDate(dateAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingSimpleDateFormat_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException, ParseException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingSimpleDateFormat(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingGregorianCalendar_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException, ParseException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingGregorianCalendar(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringDateTime_whenUsingJodaTime_thenConvertToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = StringDateToXMLGregorianCalendarConverter.usingJodaTime(dateTimeAsString);
|
||||
assertEquals(24,xmlGregorianCalendar.getDay());
|
||||
assertEquals(4,xmlGregorianCalendar.getMonth());
|
||||
assertEquals(2014,xmlGregorianCalendar.getYear());
|
||||
assertEquals(15,xmlGregorianCalendar.getHour());
|
||||
assertEquals(45,xmlGregorianCalendar.getMinute());
|
||||
assertEquals(30,xmlGregorianCalendar.getSecond());
|
||||
}
|
||||
}
|
|
@ -5,3 +5,4 @@ This module contains articles about parsing and formatting Java date and time ob
|
|||
### Relevant Articles:
|
||||
- [Convert String to Instant](https://www.baeldung.com/java-string-to-instant)
|
||||
- [Sort Date Strings in Java](https://www.baeldung.com/java-sort-date-strings)
|
||||
- [Using Current Time as Filename in Java](https://www.baeldung.com/java-current-time-filename)
|
||||
|
|
|
@ -8,5 +8,6 @@ This module contains articles about core Java input and output (IO)
|
|||
- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream)
|
||||
- [How to Write Strings to OutputStream in Java](https://www.baeldung.com/java-write-string-outputstream)
|
||||
- [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several)
|
||||
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
Hello, world!
|
|
@ -0,0 +1,85 @@
|
|||
package com.baeldung.readwritethread;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
|
||||
public class ReadWriteBlockingQueue {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
|
||||
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
|
||||
String readFileName = "src/main/resources/read_file.txt";
|
||||
String writeFileName = "src/main/resources/write_file.txt";
|
||||
|
||||
Thread producerThread = new Thread(new FileProducer(queue, readFileName));
|
||||
Thread consumerThread1 = new Thread(new FileConsumer(queue, writeFileName));
|
||||
|
||||
producerThread.start();
|
||||
Thread.sleep(100); // Give producer a head start
|
||||
consumerThread1.start();
|
||||
try {
|
||||
producerThread.join();
|
||||
consumerThread1.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
class FileProducer implements Runnable {
|
||||
|
||||
private final BlockingQueue<String> queue;
|
||||
private final String inputFileName;
|
||||
|
||||
public FileProducer(BlockingQueue<String> queue, String inputFileName) {
|
||||
this.queue = queue;
|
||||
this.inputFileName = inputFileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
queue.offer(line);
|
||||
System.out.println("Producer added line: " + line);
|
||||
System.out.println("Queue size: " + queue.size());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FileConsumer implements Runnable {
|
||||
|
||||
private final BlockingQueue<String> queue;
|
||||
private final String outputFileName;
|
||||
|
||||
public FileConsumer(BlockingQueue queue, String outputFileName) {
|
||||
this.queue = queue;
|
||||
this.outputFileName = outputFileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {
|
||||
String line;
|
||||
while ((line = queue.poll()) != null) {
|
||||
writer.write(line);
|
||||
writer.newLine();
|
||||
System.out.println(Thread.currentThread()
|
||||
.getId() + " - Consumer processed line: " + line);
|
||||
System.out.println("Queue size: " + queue.size());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.readwritethread;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ReadWriteThread {
|
||||
|
||||
public static void readFile(String filePath) {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
System.out.println(line);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public static void writeFile(String filePath, String content) {
|
||||
Thread thread = new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try (FileWriter fileWriter = new FileWriter(filePath)) {
|
||||
fileWriter.write("Hello, world!");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
thread.start();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String file = "src/main/resources/text.txt";
|
||||
|
||||
writeFile(file, "Hello, world!");
|
||||
|
||||
readFile(file);
|
||||
|
||||
// Sleep for a while to allow the threads to complete
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
Hello,
|
||||
Baeldung!
|
||||
Nice to meet you!
|
||||
My name is
|
||||
Wynn.
|
|
@ -0,0 +1 @@
|
|||
Hello, world!
|
|
@ -0,0 +1,5 @@
|
|||
Hello,
|
||||
Baeldung!
|
||||
Nice to meet you!
|
||||
My name is
|
||||
Wynn.
|
|
@ -82,6 +82,7 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-io-apis-2</finalName>
|
||||
<resources>
|
||||
|
@ -91,6 +92,7 @@
|
|||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter-version>5.9.3</junit-jupiter-version>
|
||||
</properties>
|
||||
|
|
|
@ -51,9 +51,10 @@ public class ReadInputCharByCharUnitTest {
|
|||
System.setIn(inputStream);
|
||||
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
char[] result = scanner.next().toCharArray();
|
||||
|
||||
assertArrayEquals("TestInput".toCharArray(), result);
|
||||
if (scanner.hasNext()) {
|
||||
char[] result = scanner.next().toCharArray();
|
||||
assertArrayEquals("TestInput".toCharArray(), result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -3,14 +3,14 @@
|
|||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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>
|
||||
<artifactId>core-java-lang-6</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>core-java-lang-6</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct -->
|
||||
<dependency>
|
||||
|
|
|
@ -14,4 +14,7 @@
|
|||
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
|
||||
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
|
||||
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)
|
||||
- [Validate if a String Is a Valid Geo Coordinate](https://www.baeldung.com/java-geo-coordinates-validation)
|
||||
- [Rotate a Vertex Around a Certain Point in Java](https://www.baeldung.com/java-rotate-vertex-around-point)
|
||||
- [Calculating the Power of Any Number in Java Without Using Math pow() Method](https://www.baeldung.com/java-calculating-the-power-without-math-pow)
|
||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
|
||||
|
|
|
@ -5,6 +5,14 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-lang-math</artifactId>
|
||||
<name>core-java-lang-math</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
@ -13,13 +21,6 @@
|
|||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-lang-math</finalName>
|
||||
|
|
|
@ -32,7 +32,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.2</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.objectmutability;
|
||||
|
||||
public final class ImmutablePerson {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public ImmutablePerson(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.objectmutability;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
public class ImmutableObjectExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImmutableString_whenConcatString_thenNotSameAndCorrectValues() {
|
||||
String originalString = "Hello";
|
||||
String modifiedString = originalString.concat(" World");
|
||||
|
||||
assertNotSame(originalString, modifiedString);
|
||||
|
||||
assertEquals("Hello", originalString);
|
||||
assertEquals("Hello World", modifiedString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableInteger_whenAddInteger_thenNotSameAndCorrectValue() {
|
||||
Integer immutableInt = 42;
|
||||
Integer modifiedInt = immutableInt + 8;
|
||||
|
||||
assertNotSame(immutableInt, modifiedInt);
|
||||
|
||||
assertEquals(42, (int) immutableInt);
|
||||
assertEquals(50, (int) modifiedInt);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.objectmutability;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ImmutablePersonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenImmutablePerson_whenAccessFields_thenCorrectValues() {
|
||||
ImmutablePerson person = new ImmutablePerson("John", 30);
|
||||
|
||||
assertEquals("John", person.getName());
|
||||
assertEquals(30, person.getAge());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.objectmutability;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class MutableObjectExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMutableString_whenAppendElement_thenCorrectValue() {
|
||||
StringBuilder mutableString = new StringBuilder("Hello");
|
||||
mutableString.append(" World");
|
||||
|
||||
assertEquals("Hello World", mutableString.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMutableList_whenAddElement_thenCorrectSize() {
|
||||
List<String> mutableList = new ArrayList<>();
|
||||
mutableList.add("Java");
|
||||
|
||||
assertEquals(1, mutableList.size());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.infixpostfix;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
public class InfixToPostFixExpressionConversion {
|
||||
|
||||
private int getPrecedenceScore(char ch) {
|
||||
switch (ch) {
|
||||
case '^':
|
||||
return 3;
|
||||
|
||||
case '*':
|
||||
case '/':
|
||||
return 2;
|
||||
|
||||
case '+':
|
||||
case '-':
|
||||
return 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private boolean isOperand(char ch) {
|
||||
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
|
||||
}
|
||||
|
||||
private char associativity(char ch) {
|
||||
if (ch == '^')
|
||||
return 'R';
|
||||
return 'L';
|
||||
}
|
||||
|
||||
public String infixToPostfix(String infix) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
Stack<Character> stack = new Stack<>();
|
||||
|
||||
for (int i = 0; i < infix.length(); i++) {
|
||||
char ch = infix.charAt(i);
|
||||
|
||||
if (isOperand(ch)) {
|
||||
result.append(ch);
|
||||
} else if (ch == '(') {
|
||||
stack.push(ch);
|
||||
} else if (ch == ')') {
|
||||
while (!stack.isEmpty() && stack.peek() != '(') {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
stack.pop();
|
||||
} else {
|
||||
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
stack.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
result.append(stack.pop());
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
|
||||
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.infixpostfix;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
|
||||
public class InfixToPostfixExpressionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSimpleOp_whenNoParenthesis_thenProduceValidPostfix() {
|
||||
String infix = "a+b*c-d";
|
||||
String postfix = "abc*+d-";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleOp_whenWithParenthesis_thenProduceValidPostfix() {
|
||||
String infix = "(a+b)*(c-d)";
|
||||
String postfix = "ab+cd-*";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexOp_whenInputIsInfix_thenProduceValidPostfix() {
|
||||
String infix = "a^b*(c^d-e)^(f+g*h)-i";
|
||||
String postfix = "ab^cd^e-fgh*+^*i-";
|
||||
|
||||
InfixToPostFixExpressionConversion obj = new InfixToPostFixExpressionConversion();
|
||||
|
||||
Assertions.assertEquals(postfix, obj.infixToPostfix(infix));
|
||||
}
|
||||
}
|
|
@ -5,3 +5,4 @@
|
|||
- [Download a Webpage in Java](https://www.baeldung.com/java-download-webpage)
|
||||
- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)
|
||||
- [Understanding the java.net.SocketException Broken Pipe Error](https://www.baeldung.com/java-socketexception-broken-pipe-error)
|
||||
- [Normalize a URL in Java](https://www.baeldung.com/java-url-normalization)
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -31,6 +31,7 @@
|
|||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-numbers-6</finalName>
|
||||
<resources>
|
||||
|
@ -44,4 +45,5 @@
|
|||
<properties>
|
||||
<commons-codec>1.16.0</commons-codec>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,3 +1,5 @@
|
|||
## Relevant Articles
|
||||
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)
|
||||
- [Print a Double Value Without Scientific Notation in Java](https://www.baeldung.com/java-print-double-number-no-scientific-notation)
|
||||
- [Check if a Float Value is Equivalent to an Integer Value in Java](https://www.baeldung.com/java-float-integer-equal)
|
||||
- [Generating Unique Positive Long Using SecureRandom in Java](https://www.baeldung.com/java-securerandom-generate-positive-long)
|
||||
|
|
|
@ -25,6 +25,7 @@
|
|||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-numbers-7</finalName>
|
||||
<resources>
|
||||
|
@ -34,4 +35,5 @@
|
|||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.securerandompositivelong;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class SecureRandomPositiveLongUnitTest {
|
||||
|
||||
@Test
|
||||
void whenGenerateRandomPositiveLong_thenGetPositiveValue() {
|
||||
SecureRandom secureRandom = new SecureRandom();
|
||||
long randomPositiveLong = Math.abs(secureRandom.nextLong());
|
||||
|
||||
assertThat(randomPositiveLong).isNotNegative();
|
||||
}
|
||||
}
|
|
@ -15,7 +15,7 @@
|
|||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<groupId>org.hibernate.orm</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.core.version}</version>
|
||||
</dependency>
|
||||
|
@ -53,7 +53,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
|
||||
<hibernate.core.version>6.4.2.Final</hibernate.core.version>
|
||||
<json-path.version>5.3.2</json-path.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@ import java.util.Map;
|
|||
import java.util.Optional;
|
||||
|
||||
public class HandleOptionalTypeExample {
|
||||
static Map<String, User> usersByName = new HashMap();
|
||||
static Map<String, User> usersByName = new HashMap<>();
|
||||
static {
|
||||
User user1 = new User();
|
||||
user1.setUserId(1l);
|
||||
|
|
|
@ -2,9 +2,9 @@ package com.baeldung.optionalreturntype;
|
|||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.Persistence;
|
||||
|
||||
public class PersistOptionalTypeExample {
|
||||
static String persistenceUnit = "com.baeldung.optionalreturntype";
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.Persistence;
|
||||
|
||||
public class PersistOptionalTypeExample2 {
|
||||
static String persistenceUnit = "com.baeldung.optionalreturntype";
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package com.baeldung.optionalreturntype;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.EntityManagerFactory;
|
||||
import jakarta.persistence.Persistence;
|
||||
|
||||
public class PersistUserExample {
|
||||
static String persistenceUnit = "com.baeldung.optionalreturntype";
|
||||
|
|
|
@ -2,8 +2,8 @@ package com.baeldung.optionalreturntype;
|
|||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class User implements Serializable {
|
||||
|
|
|
@ -3,9 +3,9 @@ package com.baeldung.optionalreturntype;
|
|||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class UserOptional implements Serializable {
|
||||
|
|
|
@ -3,8 +3,8 @@ package com.baeldung.optionalreturntype;
|
|||
import java.io.Serializable;
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class UserOptionalField implements Serializable {
|
||||
|
|
|
@ -6,3 +6,5 @@ This module contains articles about performance of Java applications
|
|||
- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
|
||||
- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)
|
||||
- [Differences Between Heap Dump, Thread Dump and Core Dump](https://www.baeldung.com/java-heap-thread-core-dumps)
|
||||
- [Shutting Down on OutOfMemoryError in Java](https://www.baeldung.com/java-shutting-down-outofmemoryerror)
|
||||
|
||||
|
|
|
@ -2,14 +2,15 @@
|
|||
<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>
|
||||
<artifactId>core-java-records</artifactId>
|
||||
|
||||
<parent>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>core-java-records</artifactId>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Is Java Reflection Bad Practice?](https://www.baeldung.com/java-reflection-benefits-drawbacks)
|
||||
- [Instantiate an Inner Class With Reflection in Java](https://www.baeldung.com/java-reflection-instantiate-inner-class)
|
||||
|
|
|
@ -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 {
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -7,4 +7,5 @@ This module contains articles about core Java Security
|
|||
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
|
||||
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
|
||||
- [Using a Custom TrustStore in Java](https://www.baeldung.com/java-custom-truststore)
|
||||
- [Enable Java SSL Debug Logging](https://www.baeldung.com/java-ssl-debug-logging)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -5,3 +5,4 @@ This module contains articles about string-related algorithms.
|
|||
### Relevant Articles:
|
||||
- [Rotating a Java String By n Characters](https://www.baeldung.com/java-rotate-string-by-n-characters)
|
||||
- [Remove Characters From a String That Are in the Other String](https://www.baeldung.com/java-strings-character-difference)
|
||||
- [Run-Length Encoding and Decoding in Java](https://www.baeldung.com/java-rle-compression)
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
}
|
|
@ -12,6 +12,7 @@
|
|||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
|
|
@ -12,3 +12,6 @@
|
|||
- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character)
|
||||
- [Comparing One String With Multiple Values in One Expression in Java](https://www.baeldung.com/java-compare-string-multiple-values-one-expression)
|
||||
- [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)
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
|
||||
### Relevant Articles:
|
|
@ -0,0 +1,72 @@
|
|||
<?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">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-string-operations-8</artifactId>
|
||||
<name>core-java-string-operations-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${apache.commons.lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-text</artifactId>
|
||||
<version>${commons-text.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>4.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-core</artifactId>
|
||||
<version>4.9.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
|
||||
<commons-text.version>1.10.0</commons-text.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.emailandphonemasking;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class EmailAndPhoneMaskingUnitTest {
|
||||
|
||||
|
||||
String phoneNumber = "+12344567890";
|
||||
String expectedMaskedPhoneNumber = "+*******7890";
|
||||
String email = "testemailaddress@example.com";
|
||||
String expectedMaskedEmail = "te**************@example.com";
|
||||
|
||||
@Test
|
||||
public void givenEmailAddress_whenUsingStringManipulation_thenMaskEmail() {
|
||||
int atIndex = email.indexOf('@');
|
||||
String repeatedString = IntStream.range(0, atIndex - 2).mapToObj(i -> "*").collect(Collectors.joining());
|
||||
String maskedPart = email.substring(0, atIndex - repeatedString.length()) + repeatedString;
|
||||
String maskedEmail = maskedPart + email.substring(atIndex);
|
||||
assertEquals(expectedMaskedEmail, maskedEmail);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmailAddress_whenUsingRegex_thenMaskEmail() {
|
||||
int atIndex = email.indexOf('@');
|
||||
String regex = "(.{2})(.*)(@.*)";
|
||||
String repeatedAsterisks = "*".repeat(atIndex - 2);
|
||||
String maskedEmail = email.replaceAll(regex, "$1" + repeatedAsterisks + "$3");
|
||||
assertEquals(expectedMaskedEmail, maskedEmail);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenUsingStringManipulation_thenMaskPhone() {
|
||||
String maskedPhoneNumber = phoneNumber.replaceAll("\\d(?=\\d{4})", "*");
|
||||
assertEquals(expectedMaskedPhoneNumber, maskedPhoneNumber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPhoneNumber_whenUsingRegex_thenMaskPhone() {
|
||||
int lastDigitsIndex = phoneNumber.length() - 5;
|
||||
String regex = "(\\+)(\\d+)(\\d{4})";
|
||||
String repeatedAsterisks = "*".repeat(Math.max(0, lastDigitsIndex));
|
||||
String maskedPhoneNumber = phoneNumber.replaceAll(regex, "$1" + repeatedAsterisks + "$3");
|
||||
assertEquals(expectedMaskedPhoneNumber, maskedPhoneNumber);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
<?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">
|
||||
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>
|
||||
<artifactId>core-java-swing</artifactId>
|
||||
<name>core-java-swing</name>
|
||||
|
@ -12,6 +12,7 @@
|
|||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>20</maven.compiler.source>
|
||||
<maven.compiler.target>20</maven.compiler.target>
|
||||
|
|
|
@ -7,3 +7,4 @@
|
|||
- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
|
||||
- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
|
||||
- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation)
|
||||
- [Storing UUID as Base64 String in Java](https://www.baeldung.com/java-store-uuid-base64-string)
|
||||
|
|
|
@ -29,6 +29,16 @@
|
|||
<artifactId>tsid-creator</artifactId>
|
||||
<version>5.2.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.16.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.14.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.uuid;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.decodeBase64;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.lang3.Conversion;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class DecodeUUIDStringFromBase64UnitTest {
|
||||
private final UUID originalUUID = UUID.fromString("cc5f93f7-8cf1-4a51-83c6-e740313a0c6c");
|
||||
|
||||
@Test
|
||||
public void givenEncodedString_whenDecodingUsingBase64Decoder_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] decodedBytes = Base64.getDecoder()
|
||||
.decode(expectedEncodedString);
|
||||
UUID uuid = convertToUUID(decodedBytes);
|
||||
assertEquals(originalUUID, uuid);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncodedString_whenDecodingUsingByteBufferAndBase64UrlDecoder_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "zF-T94zxSlGDxudAMToMbA";
|
||||
byte[] decodedBytes = Base64.getUrlDecoder()
|
||||
.decode(expectedEncodedString);
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(decodedBytes);
|
||||
long mostSignificantBits = byteBuffer.getLong();
|
||||
long leastSignificantBits = byteBuffer.getLong();
|
||||
UUID uuid = new UUID(mostSignificantBits, leastSignificantBits);
|
||||
assertEquals(originalUUID, uuid);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncodedString_whenDecodingUsingApacheUtils_thenGiveExpectedUUID() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] decodedBytes = decodeBase64(expectedEncodedString);
|
||||
UUID uuid = Conversion.byteArrayToUuid(decodedBytes, 0);
|
||||
assertEquals(originalUUID, uuid);
|
||||
}
|
||||
|
||||
private UUID convertToUUID(byte[] src) {
|
||||
long mostSignificantBits = convertBytesToLong(src, 0);
|
||||
long leastSignificantBits = convertBytesToLong(src, 8);
|
||||
|
||||
return new UUID(mostSignificantBits, leastSignificantBits);
|
||||
}
|
||||
|
||||
private long convertBytesToLong(byte[] uuidBytes, int start) {
|
||||
long result = 0;
|
||||
|
||||
for(int i = 0; i < 8; i++) {
|
||||
int shift = i * 8;
|
||||
long bits = (255L & (long)uuidBytes[i + start]) << shift;
|
||||
long mask = 255L << shift;
|
||||
result = result & ~mask | bits;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.uuid;
|
||||
|
||||
import static org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.lang3.Conversion;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class EncodeUUIDToBase64StringUnitTest {
|
||||
private final UUID originalUUID = UUID.fromString("cc5f93f7-8cf1-4a51-83c6-e740313a0c6c");
|
||||
|
||||
@Test
|
||||
public void givenUUID_whenEncodingUsingBase64Encoder_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] uuidBytes = convertToByteArray(originalUUID);
|
||||
String encodedUUID = Base64.getEncoder().withoutPadding()
|
||||
.encodeToString(uuidBytes);
|
||||
assertEquals(expectedEncodedString, encodedUUID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUUID_whenEncodingUsingByteBufferAndBase64UrlEncoder_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "zF-T94zxSlGDxudAMToMbA";
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
|
||||
byteBuffer.putLong(originalUUID.getMostSignificantBits());
|
||||
byteBuffer.putLong(originalUUID.getLeastSignificantBits());
|
||||
String encodedUUID = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(byteBuffer.array());
|
||||
assertEquals(expectedEncodedString, encodedUUID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUUID_whenEncodingUsingApacheUtils_thenGiveExpectedEncodedString() {
|
||||
String expectedEncodedString = "UUrxjPeTX8xsDDoxQOfGgw";
|
||||
byte[] bytes = Conversion.uuidToByteArray(originalUUID, new byte[16], 0, 16);
|
||||
String encodedUUID = encodeBase64URLSafeString(bytes);
|
||||
assertEquals(expectedEncodedString, encodedUUID);
|
||||
}
|
||||
|
||||
private byte[] convertToByteArray(UUID uuid) {
|
||||
byte[] result = new byte[16];
|
||||
|
||||
long mostSignificantBits = uuid.getMostSignificantBits();
|
||||
fillByteArray(0, 8, result, mostSignificantBits);
|
||||
|
||||
long leastSignificantBits = uuid.getLeastSignificantBits();
|
||||
fillByteArray(8, 16, result, leastSignificantBits);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void fillByteArray(int start, int end, byte[] result, long bits) {
|
||||
for (int i = start; i < end; i++) {
|
||||
int shift = i * 8;
|
||||
result[i] = (byte) ((int) (255L & bits >> shift));
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue