Merge remote-tracking branch 'upstream/master'

This commit is contained in:
mcasari
2023-11-13 23:39:46 +01:00
314 changed files with 3606 additions and 1447 deletions
+1 -19
View File
@@ -82,26 +82,11 @@
<artifactId>geronimo-jta_1.0.1B_spec</artifactId>
<version>${geronimo.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
</dependencies>
<properties>
@@ -113,10 +98,7 @@
<derby.version>10.8.1.2</derby.version>
<jta.version>1.1</jta.version>
<geronimo.version>1.0</geronimo.version>
<validation-api.version>2.0.1.Final</validation-api.version>
<hibernate-validator.version>6.1.2.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.4</javax.el.version>
<hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
</properties>
</project>
@@ -3,10 +3,10 @@ package com.baeldung.atomikos.spring.jpa;
import java.util.Set;
import java.util.UUID;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@@ -3,7 +3,7 @@ package com.baeldung.atomikos.spring.jpa.order;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import jakarta.validation.constraints.Max;
@Entity
@Table(name = "ORDERS")
+1 -1
View File
@@ -79,7 +79,7 @@
</build>
<properties>
<gson.version>2.8.0</gson.version>
<gson.version>2.10.1</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version>
<maven-plugins-version>3.1.1</maven-plugins-version>
</properties>
+1 -1
View File
@@ -73,7 +73,7 @@
</build>
<properties>
<gson.version>2.8.0</gson.version>
<gson.version>2.10.1</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
@@ -6,4 +6,5 @@
- [How Many Days Are There in a Particular Month of a Given Year?](https://www.baeldung.com/days-particular-month-given-year)
- [Difference Between Instant and LocalDateTime](https://www.baeldung.com/java-instant-vs-localdatetime)
- [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins)
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -55,7 +55,7 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<joda-time.version>2.10</joda-time.version>
<joda-time.version>2.12.5</joda-time.version>
</properties>
</project>
@@ -7,7 +7,7 @@ import java.util.List;
public class SimpleParseDate {
public Date parseDate(String dateString, List<String> formatStrings) {
public static Date parseDate(String dateString, List<String> formatStrings) {
for (String formatString : formatStrings) {
try {
return new SimpleDateFormat(formatString).parse(dateString);
@@ -1,43 +1,41 @@
package com.baeldung.parsingDates;
import com.baeldung.parsingDates.SimpleDateTimeFormat;
import com.baeldung.parsingDates.SimpleDateTimeFormater;
import com.baeldung.parsingDates.SimpleDateUtils;
import com.baeldung.parsingDates.SimpleParseDate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
import org.joda.time.LocalDate;
import org.junit.jupiter.api.Test;
public class SimpleParseDateUnitTest {
class SimpleParseDateUnitTest {
@Test
public void whenInvalidInput_thenGettingUnexpectedResult() {
SimpleParseDate simpleParseDate = new SimpleParseDate();
void whenInvalidInput_thenGettingUnexpectedResult() {
String date = "2022-40-40";
assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString());
assertEquals("Sat May 10 00:00:00 UTC 2025", SimpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd"))
.toString());
}
@Test
public void whenInvalidDate_thenAssertThrows() {
SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater();
assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04"));
assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04"));
void whenInvalidDate_thenAssertThrows() {
assertEquals(java.time.LocalDate.parse("2022-12-04"), SimpleDateTimeFormater.parseDate("2022-12-04"));
assertThrows(DateTimeParseException.class, () -> SimpleDateTimeFormater.parseDate("2022-13-04"));
}
@Test
public void whenDateIsCorrect_thenParseCorrect() {
SimpleDateUtils simpleDateUtils = new SimpleDateUtils();
assertNull(simpleDateUtils.parseDate("53/10/2014"));
assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString());
void whenDateIsCorrect_thenParseCorrect() {
assertNull(SimpleDateUtils.parseDate("53/10/2014"));
assertEquals("Wed Sep 10 00:00:00 UTC 2014", SimpleDateUtils.parseDate("10/09/2014")
.toString());
}
@Test
public void whenDateIsCorrect_thenResultCorrect() {
SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat();
assertNull(simpleDateTimeFormat.parseDate("53/10/2014"));
assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10"));
void whenDateIsCorrect_thenResultCorrect() {
assertNull(SimpleDateTimeFormat.parseDate("53/10/2014"));
assertEquals(LocalDate.parse("2014-10-10"), SimpleDateTimeFormat.parseDate("2014-10-10"));
}
}
@@ -56,7 +56,7 @@
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<joda-time.version>2.10</joda-time.version>
<joda-time.version>2.12.5</joda-time.version>
</properties>
</project>
@@ -1,62 +0,0 @@
package com.baeldung.streamreduce.application;
import com.baeldung.streamreduce.entities.User;
import com.baeldung.streamreduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result1 = numbers.stream().reduce(0, (a, b) -> a + b);
System.out.println(result1);
int result2 = numbers.stream().reduce(0, Integer::sum);
System.out.println(result2);
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result3 = letters.stream().reduce("", (a, b) -> a + b);
System.out.println(result3);
String result4 = letters.stream().reduce("", String::concat);
System.out.println(result4);
String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
System.out.println(result5);
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result6);
String result7 = letters.parallelStream().reduce("", String::concat);
System.out.println(result7);
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
System.out.println(result8);
List<User> userList = new ArrayList<>();
for (int i = 0; i <= 1000000; i++) {
userList.add(new User("John" + i, i));
}
long t1 = System.currentTimeMillis();
int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long t2 = System.currentTimeMillis();
System.out.println(result9);
System.out.println("Sequential stream time: " + (t2 - t1) + "ms");
long t3 = System.currentTimeMillis();
int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
long t4 = System.currentTimeMillis();
System.out.println(result10);
System.out.println("Parallel stream time: " + (t4 - t3) + "ms");
int result11 = NumberUtils.divideListElements(numbers, 1);
System.out.println(result11);
int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0);
System.out.println(result12);
}
}
@@ -1,39 +0,0 @@
package com.baeldung.streamreduce.entities;
import java.util.ArrayList;
import java.util.List;
public class Rating {
double points;
List<Review> reviews = new ArrayList<>();
public Rating() {}
public void add(Review review) {
reviews.add(review);
computeRating();
}
private double computeRating() {
double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum);
this.points = totalPoints / reviews.size();
return this.points;
}
public static Rating average(Rating r1, Rating r2) {
Rating combined = new Rating();
combined.reviews = new ArrayList<>(r1.reviews);
combined.reviews.addAll(r2.reviews);
combined.computeRating();
return combined;
}
public double getPoints() {
return points;
}
public List<Review> getReviews() {
return reviews;
}
}
@@ -1,28 +0,0 @@
package com.baeldung.streamreduce.entities;
public class Review {
int points;
String review;
public Review(int points, String review) {
this.points = points;
this.review = review;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}
@@ -1,30 +0,0 @@
package com.baeldung.streamreduce.entities;
public class User {
private final String name;
private final int age;
private final Rating rating = new Rating();
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Rating getRating() {
return rating;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';
}
}
@@ -1,52 +0,0 @@
package com.baeldung.streamreduce.utilities;
import java.util.List;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class NumberUtils {
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
public static int divideListElements(List<Integer> values, Integer divider) {
return values.stream()
.reduce(0, (a, b) -> {
try {
return a / divider + b / divider;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return 0;
});
}
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
}
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
}
private static int divide(int value, int factor) {
int result = 0;
try {
result = value / factor;
} catch (ArithmeticException e) {
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
}
return result;
}
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
try {
return function.apply(a, b);
}
catch(Exception e) {
LOGGER.log(Level.INFO, "Exception occurred!");
}
return 0;
}
}
@@ -8,4 +8,5 @@
- [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods)
- [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration)
- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue)
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -0,0 +1,51 @@
package com.baeldung.toarraymethod;
import org.junit.Test;
import java.util.HashSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ConvertingHashSetToArrayUnitTest {
@Test
public void givenStringHashSet_whenConvertedToArray_thenArrayContainsStringElements() {
HashSet<String> stringSet = new HashSet<>();
stringSet.add("Apple");
stringSet.add("Banana");
stringSet.add("Cherry");
// Convert the HashSet of Strings to an array of Strings
String[] stringArray = stringSet.toArray(new String[0]);
// Test that the array is of the correct length
assertEquals(3, stringArray.length);
for (String str : stringArray) {
assertTrue(stringSet.contains(str));
}
}
@Test
public void givenIntegerHashSet_whenConvertedToArray_thenArrayContainsIntegerElements() {
HashSet<Integer> integerSet = new HashSet<>();
integerSet.add(5);
integerSet.add(10);
integerSet.add(15);
// Convert the HashSet of Integers to an array of Integers
Integer[] integerArray = integerSet.toArray(new Integer[0]);
// Test that the array is of the correct length
assertEquals(3, integerArray.length);
for (Integer num : integerArray) {
assertTrue(integerSet.contains(num));
}
assertTrue(integerSet.contains(5));
assertTrue(integerSet.contains(10));
assertTrue(integerSet.contains(15));
}
}
@@ -44,6 +44,6 @@
<properties>
<vavr.version>0.10.3</vavr.version>
<java.version>11</java.version>
<modelmapper.version>3.1.1</modelmapper.version>
<modelmapper.version>3.2.0</modelmapper.version>
</properties>
</project>
@@ -1,8 +1,9 @@
package com.baeldung.modelmapper;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeMap;
import org.modelmapper.TypeToken;
@@ -10,11 +11,10 @@ import org.modelmapper.TypeToken;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;
/**
* This class has test methods of mapping Integer to Character list,
@@ -22,12 +22,12 @@ import static org.junit.Assert.assertThat;
*
* @author Sasa Milenkovic
*/
public class UsersListMappingUnitTest {
class UsersListMappingUnitTest {
private ModelMapper modelMapper;
private List<User> users;
@Before
@BeforeEach
public void init() {
modelMapper = new ModelMapper();
@@ -35,18 +35,16 @@ public class UsersListMappingUnitTest {
TypeMap<UserList, UserListDTO> typeMap = modelMapper.createTypeMap(UserList.class, UserListDTO.class);
typeMap.addMappings(mapper -> mapper.using(new UsersListConverter())
.map(UserList::getUsers, UserListDTO::setUsernames));
.map(UserList::getUsers, UserListDTO::setUsernames));
users = new ArrayList();
users = new ArrayList<>();
users.add(new User("b100", "user1", "[email protected]", "111-222", "USER"));
users.add(new User("b101", "user2", "[email protected]", "111-333", "USER"));
users.add(new User("b102", "user3", "[email protected]", "111-444", "ADMIN"));
}
@Test
public void whenInteger_thenMapToCharacter() {
void whenInteger_thenMapToCharacter() {
List<Integer> integers = new ArrayList<Integer>();
integers.add(1);
@@ -57,36 +55,27 @@ public class UsersListMappingUnitTest {
}.getType());
assertThat(characters, hasItems('1', '2', '3'));
}
@Test
public void givenUsersList_whenUseGenericType_thenMapToUserDTO() {
void givenUsersList_whenUseGenericType_thenMapToUserDTO() {
// Mapping lists using custom (generic) type mapping
List<UserDTO> userDtoList = MapperUtil.mapList(users, UserDTO.class);
assertThat(userDtoList, Matchers.<UserDTO>hasItem(
Matchers.both(hasProperty("userId", equalTo("b100")))
.and(hasProperty("email", equalTo("user1@baeldung.com")))
.and(hasProperty("username", equalTo("user1")))));
assertThat(userDtoList, Matchers.<UserDTO> hasItem(Matchers.both(hasProperty("userId", equalTo("b100")))
.and(hasProperty("email", equalTo("[email protected]")))
.and(hasProperty("username", equalTo("user1")))));
}
@Test
public void givenUsersList_whenUseConverter_thenMapToUsernames() {
void givenUsersList_whenUseConverter_thenMapToUsernames() {
// Mapping lists using property mapping and converter
UserList userList = new UserList();
userList.setUsers(users);
UserListDTO dtos = new UserListDTO();
modelMapper.map(userList, dtos);
assertThat(dtos.getUsernames(), hasItems("user1", "user2", "user3"));
}
}
@@ -1,3 +1,7 @@
## Relevant Articles
## Relevant Articles:
- [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent)
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/how-to-write-and-read-a-file-with-a-java-hashmap/)
- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv)
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
@@ -1,11 +1,15 @@
<?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-collections-maps-7</artifactId>
<name>core-java-collections-maps-7</name>
<packaging>jar</packaging>
<properties>
<gson.version>2.10.1</gson.version>
<csv.version>1.5</csv.version>
</properties>
<parent>
<artifactId>core-java-modules</artifactId>
@@ -13,72 +17,24 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.36</version>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.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.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
<version>${csv.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@@ -92,5 +48,4 @@
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,51 @@
package com.baeldung.map.readandwritefile;
import java.io.Serializable;
import java.util.Objects;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private String lastName;
/** Default constructor for JSON serialization */
public Student() {
}
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Student student = (Student) o;
return Objects.equals(firstName, student.firstName) && Objects.equals(lastName, student.lastName);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
@@ -0,0 +1,135 @@
package com.baeldung.map.readandwritefile;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.After;
import org.junit.Test;
import org.junit.Before;
public class ReadAndWriteFileWithHashMapUnitTest {
private static final Map<Integer, Student> STUDENT_DATA = new HashMap<>();
static {
STUDENT_DATA.put(1234, new Student("Henry", "Winter"));
STUDENT_DATA.put(5678, new Student("Richard", "Papen"));
}
private File file;
@Before
public void createFile() throws IOException {
file = File.createTempFile("student", ".data");
}
@After
public void deleteFile() {
file.delete();
}
@Test
public void givenHashMap_whenWrittenAsPropertiesFile_thenReloadedMapIsIdentical() throws IOException {
// Given a map containing student data
Map<String, String> studentData = new HashMap<>();
studentData.put("student.firstName", "Henry");
studentData.put("student.lastName", "Winter");
// When converting to a Properties object and writing to a file
Properties props = new Properties();
props.putAll(studentData);
try (OutputStream output = Files.newOutputStream(file.toPath())) {
props.store(output, null);
}
// Then the map resulting from loading the Properties file is identical
Properties propsFromFile = new Properties();
try (InputStream input = Files.newInputStream(file.toPath())) {
propsFromFile.load(input);
}
Map<String, String> studentDataFromProps = propsFromFile.stringPropertyNames()
.stream()
.collect(Collectors.toMap(key -> key, props::getProperty));
assertThat(studentDataFromProps).isEqualTo(studentData);
}
@Test
public void givenHashMap_whenSerializedToFile_thenDeserializedMapIsIdentical() throws IOException, ClassNotFoundException {
// Given a map containing student data (STUDENT_DATA)
// When serializing the map to a file
try (FileOutputStream fileOutput = new FileOutputStream(file); ObjectOutputStream objectStream = new ObjectOutputStream(fileOutput)) {
objectStream.writeObject(STUDENT_DATA);
}
// Then read the file back into a map and check the contents
Map<Integer, Student> studentsFromFile;
try (FileInputStream fileReader = new FileInputStream(file); ObjectInputStream objectStream = new ObjectInputStream(fileReader)) {
studentsFromFile = (HashMap<Integer, Student>) objectStream.readObject();
}
assertThat(studentsFromFile).isEqualTo(STUDENT_DATA);
}
@Test
public void givenHashMap_whenSerializedToFileWithJackson_thenDeserializedMapIsIdentical() throws IOException {
// Given a map containing student data (STUDENT_DATA)
// When converting to JSON with Jackson and writing to a file
ObjectMapper mapper = new ObjectMapper();
try (FileOutputStream fileOutput = new FileOutputStream(file)) {
mapper.writeValue(fileOutput, STUDENT_DATA);
}
// Then deserialize the file back into a map and check that it's identical
Map<Integer, Student> mapFromFile;
try (FileInputStream fileInput = new FileInputStream(file)) {
// Create a TypeReference so we can deserialize the parameterized type
TypeReference<HashMap<Integer, Student>> mapType = new TypeReference<HashMap<Integer, Student>>() {
};
mapFromFile = mapper.readValue(fileInput, mapType);
}
assertThat(mapFromFile).isEqualTo(STUDENT_DATA);
}
@Test
public void givenHashMap_whenSerializedToFileWithGson_thenDeserializedMapIsIdentical() throws IOException {
// Given a map containing student data (STUDENT_DATA)
// When converting to JSON using Gson and writing to a file
Gson gson = new Gson();
try (FileWriter writer = new FileWriter(file)) {
gson.toJson(STUDENT_DATA, writer);
}
// Then deserialize the file back into a map and check that it's identical
Map<Integer, Student> studentsFromFile;
try (FileReader reader = new FileReader(file)) {
Type mapType = new TypeToken<HashMap<Integer, Student>>() {
}.getType();
studentsFromFile = gson.fromJson(reader, mapType);
}
assertThat(studentsFromFile).isEqualTo(STUDENT_DATA);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.concurrent.synchronizestatic.atomicinteger;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Synchronizing static variable with AtomicInteger.
*/
public class Employee {
private static final AtomicInteger count = new AtomicInteger(0);
int id;
String name;
String title;
public Employee(int id, String name, String title) {
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static void incrementCount() {
count.incrementAndGet();
}
public static int getCount() {
return count.get();
}
}
@@ -0,0 +1,27 @@
package com.baeldung.concurrent.synchronizestatic.none;
/**
* No synchronization.
*/
public class Employee {
static int count;
int id;
String name;
String title;
public Employee(int id, String name, String title) {
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static void incrementCount() {
System.out.println("Count = " + ++count);
}
public static Integer getCount() {
return count;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.concurrent.synchronizestatic.reentrantlock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Synchronizing static variable with a Reenatrant Lock.
*/
public class Employee {
private static final ReentrantLock lock = new ReentrantLock();
static int count;
int id;
String name;
String title;
public Employee(int id, String name, String title) {
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static void incrementCount() {
lock.lock();
try {
System.out.println("Count = " + ++count);
}
finally {
lock.unlock();
}
}
public static int getCount() {
lock.lock();
try {
return count;
}
finally {
lock.unlock();
}
}
}
@@ -0,0 +1,33 @@
package com.baeldung.concurrent.synchronizestatic.synchronizedblock;
/**
* Synchronizing static variable with a synchronized block.
*/
public class Employee {
private static final Object lock = new Object();
static int count;
int id;
String name;
String title;
public Employee(int id, String name, String title) {
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static void incrementCount() {
synchronized(lock) {
System.out.println("Count = " + ++count);
}
}
public static int getCount() {
synchronized(lock) {
return count;
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.concurrent.synchronizestatic.synchronizedclass;
/**
* Synchronizing static variable with a synchronized block.
*/
public class Employee
{
static int count;
int id;
String name;
String title;
public Employee(int id, String name, String title) {
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static void incrementCount() {
synchronized(Employee.class) {
System.out.println("Count = " + ++count);
}
}
public static int getCount() {
synchronized(Employee.class) {
return count;
}
}
}
@@ -0,0 +1,27 @@
package com.baeldung.concurrent.synchronizestatic.synchronizedmethod;
/**
* Synchronizing static variable with a synchronized method.
*/
public class Employee {
static int count;
int id;
String name;
String title;
public Employee(int id, String name, String title)
{
incrementCount();
this.id = id;
this.name = name;
this.title = title;
}
private static synchronized void incrementCount() {
System.out.println("Count = " + ++count);
}
public static synchronized int getCount() {
return count;
}
}
@@ -0,0 +1,90 @@
package com.baeldung.concurrent.synchronizestatic;
import org.junit.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* The tests in this class show the output of creating multiple
* types of Employee classes in the <code>synchronizedstatic</code>
* package. When not synchronized the out will not be sequential;
* when it is synchronized the output will be in sequential.
*/
public class SychronizeStaticDataUnitTest {
private final Executor pool = Executors.newFixedThreadPool(4);
private final int numberToTest = 100;
@Test
public void whenNotSynchronized_thenDataOutOfOrder() {
System.out.println("No synchronization");
for(int i = 0; i < numberToTest; i++) {
int finalI = i;
pool.execute(() -> {
new com.baeldung.concurrent.synchronizestatic.none.Employee(finalI, "John", "Smith");
});
}
}
@Test
public void whenSynchronizedMethod_thenDataInOrder() {
System.out.println("Synchronization with synchronized method");
for(int i = 0; i < numberToTest; i++) {
int finalI = i;
pool.execute(() -> {
new com.baeldung.concurrent.synchronizestatic.synchronizedmethod.Employee(finalI, "John", "Smith");
});
}
}
@Test
public void whenSynchronizedClass_thenDataInOrder() {
System.out.println("Synchronization with synchronized block on class");
for(int i = 0; i < numberToTest; i++) {
int finalI = i;
pool.execute(() -> {
new com.baeldung.concurrent.synchronizestatic.synchronizedclass.Employee(finalI, "John", "Smith");
});
}
}
@Test
public void whenSynchronizedBlock_thenDataInOrder() {
System.out.println("Synchronization with synchronized block on a private object");
for(int i = 0; i < numberToTest; i++) {
int finalI = i;
pool.execute(() -> {
new com.baeldung.concurrent.synchronizestatic.synchronizedblock.Employee(finalI, "John", "Smith");
});
}
}
@Test
public void whenAtomicInteger_thenDataInOrder() {
// Not straight forward to test this because we cannot log/print
// and increment values in a synchronized fashion like other
// tests
}
@Test
public void whenReentrantLock_thenDataInOrder() {
System.out.println("Synchronization with ReentrantLock");
for(int i = 0; i < numberToTest; i++) {
int finalI = i;
pool.execute(() -> {
new com.baeldung.concurrent.synchronizestatic.reentrantlock.Employee(finalI, "John", "Smith");
});
}
}
}

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