Merge branch 'eugenp:master' into master

This commit is contained in:
Ekatereana 2023-11-27 11:15:05 +02:00 committed by GitHub
commit 71c26155d5
15 changed files with 283 additions and 25 deletions

View File

@ -0,0 +1,47 @@
package com.baeldung.array.conversions;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.assertArrayEquals;
public class ByteToCharArrayUnitTest {
public static byte[] byteArray = {65, 66, 67, 68};
public static char[] expected = {'A', 'B', 'C', 'D'};
@Test
public void givenByteArray_WhenUsingStandardCharsets_thenConvertToCharArray() {
char[] charArray = new String(byteArray, StandardCharsets.UTF_8).toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingSUsingStreams_thenConvertToCharArray() throws IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
InputStreamReader reader = new InputStreamReader(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int data;
while ((data = reader.read()) != -1) {
char ch = (char) data;
outputStream.write(ch);
}
char[] charArray = outputStream.toString().toCharArray();
assertArrayEquals(expected, charArray);
}
@Test
public void givenByteArray_WhenUsingCharBuffer_thenConvertToCharArray() {
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer);
char[] charArray = new char[charBuffer.remaining()];
charBuffer.get(charArray);
assertArrayEquals(expected, charArray);
}
}

View File

@ -38,6 +38,16 @@
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.37</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.37</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,68 @@
package com.baeldung.map.incrementmapkey;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class BenchmarkMapMethodsJMH {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkGuavaMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingAtomicMap(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchContainsKeyMap() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingContainsKey(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkComputeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingCompute(getString());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 1, warmups = 1)
public void benchMarkMergeMethod() {
IncrementMapValueWays im = new IncrementMapValueWays();
im.charFrequencyUsingMerge(getString());
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
private String getString() {
return
"Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n"
+ "\n"
+ "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n"
+ "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n"
+ "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n"
+ "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n"
+ "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n"
+ "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n"
+ "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n"
+ "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe.";
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.map;
package com.baeldung.map.incrementmapkey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -9,6 +9,8 @@ import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.map.incrementmapkey.IncrementMapValueWays;
public class IncrementMapValueUnitTest {
@Test

View File

@ -0,0 +1,83 @@
package com.baeldung.uuid;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;
/**
* Methods are called by reflection in the unit test
*/
@SuppressWarnings("unused")
public class UUIDPositiveLongGenerator {
public long getLeastSignificantBits() {
return Math.abs(UUID.randomUUID().getLeastSignificantBits());
}
public long getMostSignificantBits() {
return Math.abs(UUID.randomUUID().getMostSignificantBits());
}
public long combineByteBuffer() {
UUID uuid = UUID.randomUUID();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
bb.rewind();
return Math.abs(bb.getLong());
}
public long combineBitwise() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineDirect() {
UUID uniqueUUID = UUID.randomUUID();
long mostSignificantBits = uniqueUUID.getMostSignificantBits();
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1));
}
public long combinePermutation() {
UUID uuid = UUID.randomUUID();
long mostSigBits = uuid.getMostSignificantBits();
long leastSigBits = uuid.getLeastSignificantBits();
byte[] uuidBytes = new byte[16];
for (int i = 0; i < 8; i++) {
uuidBytes[i] = (byte) (mostSigBits >>> (8 * (7 - i)));
uuidBytes[i + 8] = (byte) (leastSigBits >>> (8 * (7 - i)));
}
long result = 0;
for (byte b : uuidBytes) {
result = (result << 8) | (b & 0xFF);
}
return Math.abs(result);
}
public long combineWithSecureRandom() {
UUID uniqueUUID = UUID.randomUUID();
SecureRandom secureRandom = new SecureRandom();
long randomBits = secureRandom.nextLong();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ randomBits;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
public long combineWithNanoTime() {
UUID uniqueUUID = UUID.randomUUID();
long nanoTime = System.nanoTime();
long mostSignificantBits = uniqueUUID.getMostSignificantBits() ^ nanoTime;
long leastSignificantBits = uniqueUUID.getLeastSignificantBits();
return Math.abs((mostSignificantBits << 32) | (leastSignificantBits & 0xFFFFFFFFL));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.uuid;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class UUIDPositiveLongGeneratorUnitTest {
private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator();
private final Set<Long> uniqueValues = new HashSet<>();
@Test
void whenForeachMethods_thenRetryWhileNotUnique() throws Exception {
for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) {
long uniqueValue;
do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue));
assertThat(uniqueValue).isPositive();
}
}
@Test
void whenGivenLongValue_thenCheckUniqueness() {
long uniqueValue = generateUniqueLong();
assertThat(uniqueValue).isPositive();
}
private long generateUniqueLong() {
long uniqueValue;
do uniqueValue = uuidLongGenerator.combineBitwise(); while (!isUnique(uniqueValue));
return uniqueValue;
}
private boolean isUnique(long value) {
// Implement uniqueness checking logic, for example, by checking in the database
return uniqueValues.add(value);
}
}

View File

@ -2,8 +2,7 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -35,6 +35,11 @@
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -58,7 +63,8 @@
</build>
<properties>
<jinq.version>1.8.29</jinq.version>
<jinq.version>2.0.1</jinq.version>
<hibernate-core.version>6.4.0.Final</hibernate-core.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.spring.jinq.config;
import javax.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManagerFactory;
import org.jinq.jpa.JinqJPAStreamProvider;
import org.springframework.beans.factory.annotation.Autowired;

View File

@ -1,19 +1,23 @@
package com.baeldung.spring.jinq.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Entity(name = "CAR")
public class Car {
@Id
private String model;
private String description;
private int year;
private String engine;
@ManyToOne
@JoinColumn(name = "name")
private Manufacturer manufacturer;
@Id
public String getModel() {
return model;
}
@ -46,8 +50,6 @@ public class Car {
this.engine = engine;
}
@OneToOne
@JoinColumn(name = "name")
public Manufacturer getManufacturer() {
return manufacturer;
}

View File

@ -2,18 +2,19 @@ package com.baeldung.spring.jinq.entities;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity(name = "MANUFACTURER")
public class Manufacturer {
@Id
private String name;
private String city;
@OneToMany(mappedBy = "model")
private List<Car> cars;
@Id
public String getName() {
return name;
}
@ -30,7 +31,6 @@ public class Manufacturer {
this.city = city;
}
@OneToMany(mappedBy = "model")
public List<Car> getCars() {
return cars;
}
@ -38,5 +38,4 @@ public class Manufacturer {
public void setCars(List<Car> cars) {
this.cars = cars;
}
}

View File

@ -1,7 +1,7 @@
package com.baeldung.spring.jinq.repositories;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.jinq.jpa.JPAJinqStream;
import org.jinq.jpa.JinqJPAStreamProvider;

View File

@ -4,7 +4,6 @@ import com.baeldung.spring.jinq.JinqApplication;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.baeldung.spring.jinq.JinqApplication;
@SpringBootTest(classes = JinqApplication.class)
public class SpringContextTest {