Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2ae8f45bc2
|
@ -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")
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -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();
|
||||
|
@ -37,16 +37,14 @@ public class UsersListMappingUnitTest {
|
|||
typeMap.addMappings(mapper -> mapper.using(new UsersListConverter())
|
||||
.map(UserList::getUsers, UserListDTO::setUsernames));
|
||||
|
||||
users = new ArrayList();
|
||||
users = new ArrayList<>();
|
||||
users.add(new User("b100", "user1", "user1@baeldung.com", "111-222", "USER"));
|
||||
users.add(new User("b101", "user2", "user2@baeldung.com", "111-333", "USER"));
|
||||
users.add(new User("b102", "user3", "user3@baeldung.com", "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")))
|
||||
assertThat(userDtoList, Matchers.<UserDTO> hasItem(Matchers.both(hasProperty("userId", equalTo("b100")))
|
||||
.and(hasProperty("email", equalTo("user1@baeldung.com")))
|
||||
.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)
|
|
@ -6,6 +6,10 @@
|
|||
<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");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -5,7 +5,7 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-conditionals</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-compiler</name>
|
||||
<name>core-java-conditionals</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -54,7 +54,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<hirondelle-date4j.version>RELEASE</hirondelle-date4j.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
|
|
@ -47,7 +47,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<hirondelle-date4j.version>1.5.1</hirondelle-date4j.version>
|
||||
<prettytime.version>3.2.7.Final</prettytime.version>
|
||||
<time4j-base.version>5.9</time4j-base.version>
|
||||
|
|
|
@ -11,4 +11,6 @@ This module contains articles about date operations in Java.
|
|||
- [Getting Yesterday’s Date in Java](https://www.baeldung.com/java-find-yesterdays-date)
|
||||
- [How to Get the Start and End Dates of a Year Using Java](https://www.baeldung.com/java-date-year-start-end)
|
||||
- [Convert Between Java LocalDate and Epoch](https://www.baeldung.com/java-localdate-epoch)
|
||||
- [Get First Date of Current Month in Java](https://www.baeldung.com/java-current-month-start-date)
|
||||
- [Time Conversions Using TimeUnit](https://www.baeldung.com/java-timeunit-conversion)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
|
||||
|
|
|
@ -0,0 +1,105 @@
|
|||
package com.baeldung.timeunitconversions;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class TimeUnitConversionsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
void givenSeconds_whenConvertToMinutes_thenCorrect() {
|
||||
int input = 60;
|
||||
|
||||
long minutes = TimeUnit.MINUTES.convert(input, TimeUnit.SECONDS);
|
||||
|
||||
assertThat(minutes).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMinutes_whenConvertToSeconds_thenCorrect() {
|
||||
int input = 1;
|
||||
|
||||
long seconds = TimeUnit.SECONDS.convert(input, TimeUnit.MINUTES);
|
||||
|
||||
assertThat(seconds).isEqualTo(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSeconds_whenToMinutes_thenCorrect() {
|
||||
int input = 60;
|
||||
|
||||
long minutes = TimeUnit.SECONDS.toMinutes(input);
|
||||
|
||||
assertThat(minutes).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenMinutes_whenToSeconds_thenCorrect() {
|
||||
int input = 1;
|
||||
|
||||
long seconds = TimeUnit.MINUTES.toSeconds(input);
|
||||
|
||||
assertThat(seconds).isEqualTo(60);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNegativeInput_whenToMinutes_thenCorrect() {
|
||||
int input = -60;
|
||||
|
||||
long minutes = TimeUnit.SECONDS.toMinutes(input);
|
||||
assertThat(minutes).isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonTotalInput_whenToMinutes_thenCorrectTotalResultWithDecimalTruncate() {
|
||||
long positiveUnder = TimeUnit.SECONDS.toMinutes(59);
|
||||
long positiveAbove = TimeUnit.SECONDS.toMinutes(61);
|
||||
|
||||
assertThat(positiveUnder).isEqualTo(0);
|
||||
assertThat(positiveAbove).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonTotalNegativeInput_whenToMinutes_thenCorrectTotalResultWithDecimalTruncate() {
|
||||
long negativeUnder = TimeUnit.SECONDS.toMinutes(-59);
|
||||
long negativeAbove = TimeUnit.SECONDS.toMinutes(-61);
|
||||
|
||||
assertThat(negativeUnder).isEqualTo(0);
|
||||
assertThat(negativeAbove).isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenOverflowInput_whenToMillis_thenTruncatedToLimit() {
|
||||
long maxMillis = TimeUnit.DAYS.toMillis(Long.MAX_VALUE);
|
||||
long minMillis = TimeUnit.DAYS.toMillis(Long.MIN_VALUE);
|
||||
|
||||
assertThat(maxMillis).isEqualTo(Long.MAX_VALUE);
|
||||
assertThat(minMillis).isEqualTo(Long.MIN_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenExtractFineTimeUnits_thenCorrect() {
|
||||
long inputSeconds = 3672;
|
||||
|
||||
long hours = TimeUnit.SECONDS.toHours(inputSeconds);
|
||||
|
||||
long secondsRemainingAfterHours = inputSeconds - TimeUnit.HOURS.toSeconds(hours);
|
||||
long minutes = TimeUnit.SECONDS.toMinutes(secondsRemainingAfterHours);
|
||||
|
||||
long seconds = secondsRemainingAfterHours - TimeUnit.MINUTES.toSeconds(minutes);
|
||||
|
||||
|
||||
assertThat(hours).isEqualTo(1);
|
||||
assertThat(minutes).isEqualTo(1);
|
||||
assertThat(seconds).isEqualTo(12);
|
||||
|
||||
assertThat(inputSeconds).isEqualTo(
|
||||
(hours * 60 * 60) +
|
||||
(minutes * 60) +
|
||||
(seconds)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -54,7 +54,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
|
|
|
@ -64,7 +64,7 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-validator.version>1.6</commons-validator.version>
|
||||
<commons-validator.version>1.7</commons-validator.version>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
<hirondelle-date4j.version>RELEASE</hirondelle-date4j.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
|
|
|
@ -6,6 +6,7 @@ import java.time.Instant;
|
|||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.UnsupportedTemporalTypeException;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.junit.Test;
|
||||
|
@ -17,7 +18,7 @@ public class FormatInstantUnitTest {
|
|||
@Test
|
||||
public void givenInstant_whenUsingDateTimeFormatter_thenFormat() {
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
.withZone(TimeZone.getTimeZone("UTC").toZoneId());
|
||||
|
||||
Instant instant = Instant.parse("2022-02-15T18:35:24.00Z");
|
||||
String formattedInstant = formatter.format(instant);
|
||||
|
|
|
@ -4,3 +4,4 @@
|
|||
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [Code Snippets in Java API Documentation](https://www.baeldung.com/java-doc-code-snippets)
|
||||
- [How to Document Generic Type Parameters in Javadoc](https://www.baeldung.com/java-javadoc-generic-type-parameters)
|
||||
|
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.filetofrombytearray;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileToByteArrayUnitTest {
|
||||
|
||||
private static final String FILE_NAME = "src" + File.separator + "test" + File.separator + "resources" + File.separator + "sample.txt";
|
||||
private final byte[] expectedByteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
|
||||
|
||||
@Test
|
||||
void givenFile_whenUsingFileInputStreamClass_thenConvert() throws IOException {
|
||||
File myFile = new File(FILE_NAME);
|
||||
byte[] byteArray = new byte[(int) myFile.length()];
|
||||
try (FileInputStream inputStream = new FileInputStream(myFile)) {
|
||||
inputStream.read(byteArray);
|
||||
}
|
||||
|
||||
assertArrayEquals(expectedByteArray, byteArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFile_whenUsingNioApiFilesClass_thenConvert() throws IOException {
|
||||
byte[] byteArray = Files.readAllBytes(Paths.get(FILE_NAME));
|
||||
|
||||
assertArrayEquals(expectedByteArray, byteArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFile_whenUsingApacheCommonsIOUtilsClass_thenConvert() throws IOException {
|
||||
File myFile = new File(FILE_NAME);
|
||||
byte[] byteArray = new byte[(int) myFile.length()];
|
||||
try (FileInputStream inputStream = new FileInputStream(myFile)) {
|
||||
byteArray = IOUtils.toByteArray(inputStream);
|
||||
}
|
||||
|
||||
assertArrayEquals(expectedByteArray, byteArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFile_whenUsingApacheCommonsFileUtilsClass_thenConvert() throws IOException {
|
||||
byte[] byteArray = FileUtils.readFileToByteArray(new File(FILE_NAME));
|
||||
|
||||
assertArrayEquals(expectedByteArray, byteArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenFile_whenUsingGuavaFilesClass_thenConvert() throws IOException {
|
||||
byte[] byteArray = com.google.common.io.Files.toByteArray(new File(FILE_NAME));
|
||||
|
||||
assertArrayEquals(expectedByteArray, byteArray);
|
||||
}
|
||||
|
||||
}
|
|
@ -4,3 +4,4 @@
|
|||
- [Java Naming and Directory Interface Overview](https://www.baeldung.com/jndi)
|
||||
- [LDAP Authentication Using Pure Java](https://www.baeldung.com/java-ldap-auth)
|
||||
- [Testing LDAP Connections With Java](https://www.baeldung.com/java-test-ldap-connections)
|
||||
- [JNDI – What Is java:comp/env?](https://www.baeldung.com/java-jndi-comp-env)
|
||||
|
|
|
@ -29,7 +29,6 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.5.1</version>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
|
@ -50,7 +49,7 @@
|
|||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<mapstruct.version>1.5.5.Final</mapstruct.version>
|
||||
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -4,9 +4,7 @@ public class InterruptThread extends Thread {
|
|||
@Override
|
||||
public void run() {
|
||||
while (!isInterrupted()) {
|
||||
if (isInterrupted()) {
|
||||
break;
|
||||
}
|
||||
// business logic
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,13 +1,12 @@
|
|||
package com.baeldung.genericnumberscomparator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.entry;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
|
@ -25,6 +24,7 @@ class GenericNumbersComparatorUnitTest {
|
|||
assertEquals(0, compareDouble(5, 5.0));
|
||||
}
|
||||
|
||||
// we create a method that compares Integer, but this could also be done for other types e.g. Double, BigInteger
|
||||
public int compareTo(Integer int1, Integer int2) {
|
||||
return int1.compareTo(int2);
|
||||
}
|
||||
|
@ -34,11 +34,10 @@ class GenericNumbersComparatorUnitTest {
|
|||
assertEquals(-1, compareTo(5, 7));
|
||||
}
|
||||
|
||||
Map<Class<? extends Number>, BiFunction<Number, Number, Integer>> comparisonMap = new HashMap<>();
|
||||
// for this example, we create a function that compares Integer, but this could also be done for other types e.g. Double, BigInteger
|
||||
Map<Class<? extends Number>, BiFunction<Number, Number, Integer>> comparisonMap = Map.ofEntries(entry(Integer.class, (num1, num2) -> ((Integer) num1).compareTo((Integer) num2)));
|
||||
|
||||
public int compareUsingMap(Number num1, Number num2) {
|
||||
comparisonMap.put(Integer.class, (a, b) -> ((Integer) num1).compareTo((Integer) num2));
|
||||
|
||||
return comparisonMap.get(num1.getClass())
|
||||
.apply(num1, num2);
|
||||
}
|
||||
|
@ -70,24 +69,6 @@ class GenericNumbersComparatorUnitTest {
|
|||
assertEquals(-1, compareUsingReflection(5, 7));
|
||||
}
|
||||
|
||||
interface NumberComparatorFactory {
|
||||
Comparator<Number> getComparator();
|
||||
}
|
||||
|
||||
class IntegerComparatorFactory implements NumberComparatorFactory {
|
||||
@Override
|
||||
public Comparator<Number> getComparator() {
|
||||
return (num1, num2) -> ((Integer) num1).compareTo((Integer) num2);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenUseComparatorFactory_thenWillExecuteComparison() {
|
||||
NumberComparatorFactory factory = new IntegerComparatorFactory();
|
||||
Comparator<Number> comparator = factory.getComparator();
|
||||
assertEquals(-1, comparator.compare(5, 7));
|
||||
}
|
||||
|
||||
Function<Number, Double> toDouble = Number::doubleValue;
|
||||
BiPredicate<Number, Number> isEqual = (num1, num2) -> toDouble.apply(num1)
|
||||
.equals(toDouble.apply(num2));
|
||||
|
@ -97,20 +78,7 @@ class GenericNumbersComparatorUnitTest {
|
|||
assertEquals(true, isEqual.test(5, 5.0));
|
||||
}
|
||||
|
||||
private Number someNumber = 5;
|
||||
private Number anotherNumber = 5.0;
|
||||
|
||||
Optional<Number> optNum1 = Optional.ofNullable(someNumber);
|
||||
Optional<Number> optNum2 = Optional.ofNullable(anotherNumber);
|
||||
int comparisonResult = optNum1.flatMap(n1 -> optNum2.map(n2 -> Double.compare(n1.doubleValue(), n2.doubleValue())))
|
||||
.orElse(0);
|
||||
|
||||
@Test
|
||||
void givenNumbers_whenUseComparisonResult_thenWillExecuteComparison() {
|
||||
assertEquals(0, comparisonResult);
|
||||
}
|
||||
|
||||
private boolean someCondition = true;
|
||||
private boolean someCondition;
|
||||
Function<Number, ?> dynamicFunction = someCondition ? Number::doubleValue : Number::intValue;
|
||||
Comparator<Number> dynamicComparator = (num1, num2) -> ((Comparable) dynamicFunction.apply(num1)).compareTo(dynamicFunction.apply(num2));
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.floatdoubleconversions;
|
|||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FloatDoubleConversionsTest {
|
||||
public class FloatDoubleConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenDoubleType_thenFloatTypeSuccess(){
|
|
@ -47,14 +47,14 @@
|
|||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<version>${json-path.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<json-path.version>5.3.2</json-path.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -8,88 +8,88 @@ import java.util.Optional;
|
|||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
// Uncomment code when code base is compatible with Java 9
|
||||
//public class Java9OptionalUnitTest {
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
|
||||
// //given
|
||||
// Optional<String> value = Optional.of("a");
|
||||
//
|
||||
// //when
|
||||
// List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
//
|
||||
// //then
|
||||
// assertThat(collect).hasSameElementsAs(List.of("A"));
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
|
||||
// //given
|
||||
// Optional<String> value = Optional.empty();
|
||||
//
|
||||
// //when
|
||||
// List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
//
|
||||
// //then
|
||||
// assertThat(collect).isEmpty();
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
|
||||
// //given
|
||||
// Optional<String> value = Optional.of("properValue");
|
||||
// AtomicInteger successCounter = new AtomicInteger(0);
|
||||
// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
//
|
||||
// //when
|
||||
// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
//
|
||||
// //then
|
||||
// assertThat(successCounter.get()).isEqualTo(1);
|
||||
// assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
|
||||
// //given
|
||||
// Optional<String> value = Optional.empty();
|
||||
// AtomicInteger successCounter = new AtomicInteger(0);
|
||||
// AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
//
|
||||
// //when
|
||||
// value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
//
|
||||
// //then
|
||||
// assertThat(successCounter.get()).isEqualTo(0);
|
||||
// assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
|
||||
// //given
|
||||
// String expected = "properValue";
|
||||
// Optional<String> value = Optional.of(expected);
|
||||
// Optional<String> defaultValue = Optional.of("default");
|
||||
//
|
||||
// //when
|
||||
// Optional<String> result = value.or(() -> defaultValue);
|
||||
//
|
||||
// //then
|
||||
// assertThat(result.get()).isEqualTo(expected);
|
||||
// }
|
||||
//
|
||||
// @Test
|
||||
// public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
|
||||
// //given
|
||||
// String defaultString = "default";
|
||||
// Optional<String> value = Optional.empty();
|
||||
// Optional<String> defaultValue = Optional.of(defaultString);
|
||||
//
|
||||
// //when
|
||||
// Optional<String> result = value.or(() -> defaultValue);
|
||||
//
|
||||
// //then
|
||||
// assertThat(result.get()).isEqualTo(defaultString);
|
||||
// }
|
||||
//}
|
||||
|
||||
public class Java9OptionalUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
|
||||
//given
|
||||
Optional<String> value = Optional.of("a");
|
||||
|
||||
//when
|
||||
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertThat(collect).hasSameElementsAs(List.of("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
|
||||
//given
|
||||
Optional<String> value = Optional.empty();
|
||||
|
||||
//when
|
||||
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertThat(collect).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
|
||||
//given
|
||||
Optional<String> value = Optional.of("properValue");
|
||||
AtomicInteger successCounter = new AtomicInteger(0);
|
||||
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
|
||||
//when
|
||||
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
|
||||
//then
|
||||
assertThat(successCounter.get()).isEqualTo(1);
|
||||
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
|
||||
//given
|
||||
Optional<String> value = Optional.empty();
|
||||
AtomicInteger successCounter = new AtomicInteger(0);
|
||||
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
|
||||
|
||||
//when
|
||||
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
|
||||
|
||||
//then
|
||||
assertThat(successCounter.get()).isEqualTo(0);
|
||||
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
|
||||
//given
|
||||
String expected = "properValue";
|
||||
Optional<String> value = Optional.of(expected);
|
||||
Optional<String> defaultValue = Optional.of("default");
|
||||
|
||||
//when
|
||||
Optional<String> result = value.or(() -> defaultValue);
|
||||
|
||||
//then
|
||||
assertThat(result.get()).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
|
||||
//given
|
||||
String defaultString = "default";
|
||||
Optional<String> value = Optional.empty();
|
||||
Optional<String> defaultValue = Optional.of(defaultString);
|
||||
|
||||
//when
|
||||
Optional<String> result = value.or(() -> defaultValue);
|
||||
|
||||
//then
|
||||
assertThat(result.get()).isEqualTo(defaultString);
|
||||
}
|
||||
}
|
|
@ -3,8 +3,8 @@
|
|||
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-os</artifactId>
|
||||
<name>core-java-os</name>
|
||||
<artifactId>core-java-os-2</artifactId>
|
||||
<name>core-java-os-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant Articles
|
||||
- [Overriding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)
|
||||
- [Optional as a Record Parameter in Java](https://www.baeldung.com/java-record-optional-param)
|
||||
|
|
|
@ -5,3 +5,5 @@
|
|||
- [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops)
|
||||
- [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream)
|
||||
- [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams)
|
||||
- [Modifying Objects Within Stream While Iterating](https://www.baeldung.com/java-stream-modify-objects-during-iteration)
|
||||
- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap)
|
||||
|
|
|
@ -4,6 +4,7 @@ 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;
|
||||
|
@ -18,6 +19,10 @@ public class User {
|
|||
return age;
|
||||
}
|
||||
|
||||
public Rating getRating() {
|
||||
return rating;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung.streams.collectors;
|
|||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
|
@ -23,62 +24,72 @@ public class Java8CollectorsUnitTest {
|
|||
private final List<String> listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb");
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toList());
|
||||
public void whenCollectingToList_shouldCollectToList() {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(toList());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToUnmodifiableList_shouldCollectToUnmodifiableList() {
|
||||
final List<String> result = givenList.stream().collect(toUnmodifiableList());
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(toUnmodifiableList());
|
||||
|
||||
assertThatThrownBy(() -> result.add("foo"))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
assertThatThrownBy(() -> result.add("foo")).isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
public void whenCollectingToSet_shouldCollectToSet() {
|
||||
final Set<String> result = givenList.stream()
|
||||
.collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToUnmodifiableSet_shouldCollectToUnmodifiableSet() {
|
||||
final Set<String> result = givenList.stream().collect(toUnmodifiableSet());
|
||||
final Set<String> result = givenList.stream()
|
||||
.collect(toUnmodifiableSet());
|
||||
|
||||
assertThatThrownBy(() -> result.add("foo"))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
assertThatThrownBy(() -> result.add("foo")).isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
|
||||
final Set<String> result = listWithDuplicates.stream().collect(toSet());
|
||||
final Set<String> result = listWithDuplicates.stream()
|
||||
.collect(toSet());
|
||||
|
||||
assertThat(result).hasSize(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||
assertThat(result).containsAll(givenList)
|
||||
.isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||
givenList.stream()
|
||||
.collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||
public void whenCollectingToMap_shouldCollectToMap() {
|
||||
final Map<String, Integer> result = givenList.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -86,63 +97,68 @@ public class Java8CollectorsUnitTest {
|
|||
final Map<String, Integer> result = givenList.stream()
|
||||
.collect(toUnmodifiableMap(Function.identity(), String::length));
|
||||
|
||||
assertThatThrownBy(() -> result.put("foo", 3))
|
||||
.isInstanceOf(UnsupportedOperationException.class);
|
||||
assertThatThrownBy(() -> result.put("foo", 3)).isInstanceOf(UnsupportedOperationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
|
||||
final Map<String, Integer> result = listWithDuplicates.stream().collect(
|
||||
toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(item, identicalItem) -> item
|
||||
)
|
||||
);
|
||||
final Map<String, Integer> result = listWithDuplicates.stream()
|
||||
.collect(toMap(Function.identity(), String::length, (item, identicalItem) -> item));
|
||||
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1);
|
||||
assertThat(result).containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("c", 1)
|
||||
.containsEntry("d", 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception {
|
||||
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() {
|
||||
assertThatThrownBy(() -> {
|
||||
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
|
||||
listWithDuplicates.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
}).isInstanceOf(IllegalStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
public void whenCollectingAndThen_shouldCollect() {
|
||||
final List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||
assertThat(result).containsAll(givenList)
|
||||
.isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList.stream().collect(joining());
|
||||
public void whenJoining_shouldJoin() {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining());
|
||||
|
||||
assertThat(result).isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" "));
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining(" "));
|
||||
|
||||
assertThat(result).isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() {
|
||||
final String result = givenList.stream()
|
||||
.collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||
public void whenPartitioningBy_shouldPartition() {
|
||||
final Map<Boolean, List<String>> result = givenList.stream()
|
||||
.collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||
assertThat(result).containsKeys(true, false)
|
||||
.satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
|
@ -150,15 +166,17 @@ public class Java8CollectorsUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList.stream().collect(counting());
|
||||
public void whenCounting_shouldCount() {
|
||||
final Long result = givenList.stream()
|
||||
.collect(counting());
|
||||
|
||||
assertThat(result).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||
public void whenSummarizing_shouldSummarize() {
|
||||
final DoubleSummaryStatistics result = givenList.stream()
|
||||
.collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage()).isEqualTo(2);
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
|
@ -168,38 +186,47 @@ public class Java8CollectorsUnitTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||
public void whenAveraging_shouldAverage() {
|
||||
final Double result = givenList.stream()
|
||||
.collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||
public void whenSumming_shouldSum() {
|
||||
final Double result = givenList.stream()
|
||||
.collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||
public void whenMaxingBy_shouldMaxBy() {
|
||||
final Optional<String> result = givenList.stream()
|
||||
.collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result).isPresent().hasValue("dd");
|
||||
assertThat(result).isPresent()
|
||||
.hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||
public void whenGroupingBy_shouldGroupBy() {
|
||||
final Map<Integer, Set<String>> result = givenList.stream()
|
||||
.collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||
assertThat(result).containsEntry(1, newHashSet("a"))
|
||||
.containsEntry(2, newHashSet("bb", "dd"))
|
||||
.containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||
public void whenCreatingCustomCollector_shouldCollect() {
|
||||
final ImmutableSet<String> result = givenList.stream()
|
||||
.collect(toImmutableSet());
|
||||
|
||||
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||
assertThat(result).isInstanceOf(ImmutableSet.class)
|
||||
.contains("a", "bb", "ccc", "dd");
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,15 +1,18 @@
|
|||
package com.baeldung.streamreduce.tests;
|
||||
package com.baeldung.streams.reduce;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.baeldung.streamreduce.entities.Rating;
|
||||
import com.baeldung.streamreduce.entities.Review;
|
||||
import com.baeldung.streamreduce.entities.User;
|
||||
import com.baeldung.streamreduce.utilities.NumberUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.streams.reduce.entities.Rating;
|
||||
import com.baeldung.streams.reduce.entities.Review;
|
||||
import com.baeldung.streams.reduce.entities.User;
|
||||
import com.baeldung.streams.reduce.utilities.NumberUtils;
|
||||
|
||||
public class StreamReduceManualTest {
|
||||
|
||||
@Test
|
|
@ -7,3 +7,5 @@ This module contains articles about string APIs.
|
|||
- [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty)
|
||||
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
|
||||
- [Java Localization – Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
|
||||
- [Compare StringBuilder Objects in Java](https://www.baeldung.com/java-stringbuilder-objects-comparison)
|
||||
- [Finding the N-th Occurrence of a Substring in a String in Java](https://www.baeldung.com/java-locate-nth-match-substring)
|
||||
|
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.diffstringstringbuffer;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
public class MemoryAddress {
|
||||
public long getMemoryAddress(Object object) {
|
||||
Object[] arrayOfObject = new Object[]{object};
|
||||
Unsafe unsafe = null;
|
||||
try {
|
||||
Field field = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
unsafe = (Unsafe) field.get(null);
|
||||
} catch (NoSuchFieldException | IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
assert unsafe != null;
|
||||
long arrayBaseOffset = unsafe.arrayBaseOffset(Object[].class);
|
||||
int addressSize = unsafe.addressSize();
|
||||
long objectAddress;
|
||||
if (addressSize == 4) {
|
||||
objectAddress = unsafe.getInt(arrayOfObject, arrayBaseOffset);
|
||||
} else {
|
||||
if (addressSize == 8) {
|
||||
objectAddress = unsafe.getLong(arrayOfObject, arrayBaseOffset);
|
||||
} else {
|
||||
throw new Error("Error: Size not supported: " + addressSize);
|
||||
}
|
||||
}
|
||||
return objectAddress;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.diffstringstringbuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StringBufferUnitTest {
|
||||
@Test
|
||||
void whenStringBufferVariableIsReassigned_thenVariableRetainsOriginalMemoryAddress() {
|
||||
MemoryAddress memoryAddress = new MemoryAddress();
|
||||
StringBuffer stringBuffer = new StringBuffer("DownTown");
|
||||
long address1 = memoryAddress.getMemoryAddress(stringBuffer);
|
||||
stringBuffer.insert(0, "Coder");
|
||||
assertEquals(stringBuffer.toString(), "CoderDownTown");
|
||||
long address2 = memoryAddress.getMemoryAddress(stringBuffer);
|
||||
assertEquals(address1, address2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.diffstringstringbuffer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StringUnitTest {
|
||||
@Test
|
||||
void whenStringVariableIsReassigned_thenVariableGetsNewMemoryAddress() {
|
||||
MemoryAddress memoryAddress = new MemoryAddress();
|
||||
String s1 = "DownTown";
|
||||
long address1 = memoryAddress.getMemoryAddress(s1);
|
||||
s1 = "Coder";
|
||||
long address2 = memoryAddress.getMemoryAddress(s1);
|
||||
assertNotEquals(address1, address2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenStringsAreIncludedInAStringBuffer_thenThoseStringsRemainImmutable() {
|
||||
String s1 = "TopCat";
|
||||
StringBuffer stringBuffer = new StringBuffer("DownTown");
|
||||
stringBuffer.append(s1);
|
||||
stringBuffer.reverse();
|
||||
assertNotEquals(s1, "taCpoT");
|
||||
stringBuffer.delete(0, 3);
|
||||
assertEquals(s1, "TopCat");
|
||||
}
|
||||
}
|
|
@ -14,11 +14,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
<version>${validation-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
|
@ -30,14 +25,9 @@
|
|||
<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>
|
||||
<groupId>org.glassfish.expressly</groupId>
|
||||
<artifactId>expressly</artifactId>
|
||||
<version>${expressly.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
|
@ -95,10 +85,8 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<validation-api.version>2.0.0.Final</validation-api.version>
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<javax.el-api.version>3.0.0</javax.el-api.version>
|
||||
<javax.el.version>2.2.6</javax.el.version>
|
||||
<hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
|
||||
<expressly.version>5.0.0</expressly.version>
|
||||
<commons-codec.version>1.14</commons-codec.version>
|
||||
<spring-core.version>5.3.0</spring-core.version>
|
||||
</properties>
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.emptystrings;
|
||||
|
||||
import javax.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
class SomeClassWithValidations {
|
||||
|
||||
|
|
|
@ -5,10 +5,10 @@ import org.apache.commons.lang3.StringUtils;
|
|||
import org.junit.Test;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
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 java.util.Set;
|
||||
|
||||
import static org.hamcrest.Matchers.iterableWithSize;
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
### Relevant Articles:
|
||||
- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)
|
||||
- [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word)
|
||||
- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters)
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
@rem This bat file starts the consumer and producer (more or less) at the same time
|
||||
cd target\classes
|
||||
rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ProducerApp c:\lixo\sharedmem.bin 65536
|
||||
rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ConsumerApp c:\lixo\sharedmem.bin 65536
|
||||
start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ProducerApp c:\lixo\sharedmem.bin 65536
|
||||
start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ConsumerApp c:\lixo\sharedmem.bin 65536
|
||||
cd ..
|
||||
cd ..
|
|
@ -0,0 +1,10 @@
|
|||
@rem This bat file starts the consumer and producer (more or less) at the same time
|
||||
del target\sharedmem.bin
|
||||
echo "" > target\sharedmem.bin
|
||||
cd target\classes
|
||||
rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ProducerAppWithSpinLock ..\sharedmem.bin 65536
|
||||
rem start java --add-opens java.base/java.nio=ALL-UNNAMED com.baeldung.sharedmem.ConsumerAppWithSpinLock ..\sharedmem.bin 65536
|
||||
start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ProducerAppWithSpinLock ..\sharedmem.bin 65536
|
||||
start %JAVA_HOME%\bin\java com.baeldung.sharedmem.ConsumerAppWithSpinLock ..\sharedmem.bin 65536
|
||||
cd ..
|
||||
cd ..
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.park;
|
||||
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
|
||||
public class ThreadMonitorInfo {
|
||||
private static final Object MONITOR = new Object();
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
final Thread waitingThread = new Thread(() -> {
|
||||
try {
|
||||
synchronized (MONITOR) {
|
||||
MONITOR.wait();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}, "Waiting Thread");
|
||||
|
||||
final Thread parkedThread = new Thread(LockSupport::park, "Parked Thread");
|
||||
|
||||
waitingThread.start();
|
||||
parkedThread.start();
|
||||
|
||||
waitingThread.join();
|
||||
parkedThread.join();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
package com.baeldung.sharedmem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Random;
|
||||
|
||||
public class ConsumerApp {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
digest.digest(new byte[256]);
|
||||
byte[] dummy = digest.digest();
|
||||
int hashLen = dummy.length;
|
||||
|
||||
System.out.println("Starting consumer iterations...");
|
||||
|
||||
long size = Long.parseLong(args[1]);
|
||||
MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen);
|
||||
long start = System.currentTimeMillis();
|
||||
long iterations = 0;
|
||||
int capacity = shm.capacity();
|
||||
|
||||
long matchCount = 0;
|
||||
long mismatchCount = 0;
|
||||
byte[] expectedHash = new byte[hashLen];
|
||||
|
||||
while (System.currentTimeMillis() - start < 30_000) {
|
||||
|
||||
for (int i = 0; i < capacity - hashLen; i++) {
|
||||
byte value = shm.get(i);
|
||||
digest.update(value);
|
||||
}
|
||||
|
||||
byte[] hash = digest.digest();
|
||||
shm.position(capacity-hashLen);
|
||||
shm.get(expectedHash);
|
||||
|
||||
if (Arrays.equals(hash, expectedHash)) {
|
||||
matchCount++;
|
||||
} else {
|
||||
mismatchCount++;
|
||||
}
|
||||
|
||||
iterations++;
|
||||
}
|
||||
|
||||
System.out.printf("%d iterations run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount);
|
||||
System.out.println("Press <enter> to exit");
|
||||
System.console()
|
||||
.readLine();
|
||||
}
|
||||
|
||||
private static MappedByteBuffer createSharedMemory(String path, long size) {
|
||||
|
||||
try (FileChannel fc = (FileChannel) Files.newByteChannel(
|
||||
new File(path).toPath(),
|
||||
EnumSet.of(
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.SPARSE,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.READ))) {
|
||||
return fc.map(FileChannel.MapMode.READ_WRITE, 0, size);
|
||||
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
}
|
||||
|
||||
private static long getBufferAddress(MappedByteBuffer shm) {
|
||||
try {
|
||||
Class<?> cls = shm.getClass();
|
||||
Method maddr = cls.getMethod("address");
|
||||
maddr.setAccessible(true);
|
||||
Long addr = (Long) maddr.invoke(shm);
|
||||
if (addr == null) {
|
||||
throw new RuntimeException("Unable to retrieve buffer's address");
|
||||
}
|
||||
return addr;
|
||||
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,119 @@
|
|||
package com.baeldung.sharedmem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Random;
|
||||
|
||||
public class ConsumerAppWithSpinLock {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
// Small wait to ensure the Producer gets the first round. Otherwise the hash will be invalid
|
||||
Thread.sleep(1000);
|
||||
run(args);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
} finally {
|
||||
System.console()
|
||||
.printf("Press <enter> to continue");
|
||||
System.console()
|
||||
.readLine();
|
||||
}
|
||||
}
|
||||
|
||||
private static void run(String args[]) throws Exception {
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
digest.digest(new byte[256]);
|
||||
byte[] dummy = digest.digest();
|
||||
int hashLen = dummy.length;
|
||||
|
||||
long size = Long.parseLong(args[1]);
|
||||
MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen);
|
||||
long addr = getBufferAddress(shm);
|
||||
|
||||
System.out.printf("Buffer address: 0x%08x\n", addr);
|
||||
|
||||
Random rnd = new Random();
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long iterations = 0;
|
||||
int capacity = shm.capacity();
|
||||
System.out.println("Starting consumer iterations...");
|
||||
|
||||
long matchCount = 0;
|
||||
long mismatchCount = 0;
|
||||
byte[] expectedHash = new byte[hashLen];
|
||||
SpinLock lock = new SpinLock(addr);
|
||||
|
||||
while (System.currentTimeMillis() - start < 30_000) {
|
||||
|
||||
if (!lock.tryLock(5_000)) {
|
||||
throw new RuntimeException("Unable to acquire lock");
|
||||
}
|
||||
|
||||
try {
|
||||
for (int i = 4; i < capacity - hashLen; i++) {
|
||||
byte value = shm.get(i);
|
||||
digest.update(value);
|
||||
}
|
||||
|
||||
byte[] hash = digest.digest();
|
||||
shm.position(capacity-hashLen);
|
||||
shm.get(expectedHash);
|
||||
|
||||
if (Arrays.equals(hash, expectedHash)) {
|
||||
matchCount++;
|
||||
} else {
|
||||
mismatchCount++;
|
||||
}
|
||||
|
||||
iterations++;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.printf("%d iteractions run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount);
|
||||
}
|
||||
|
||||
private static MappedByteBuffer createSharedMemory(String path, long size) {
|
||||
|
||||
try (FileChannel fc = (FileChannel) Files.newByteChannel(
|
||||
new File(path).toPath(),
|
||||
EnumSet.of(
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.SPARSE,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.READ))) {
|
||||
return fc.map(FileChannel.MapMode.READ_WRITE, 0, size);
|
||||
} catch (IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
}
|
||||
|
||||
private static long getBufferAddress(MappedByteBuffer shm) {
|
||||
try {
|
||||
Class<?> cls = shm.getClass();
|
||||
Method maddr = cls.getMethod("address");
|
||||
maddr.setAccessible(true);
|
||||
Long addr = (Long) maddr.invoke(shm);
|
||||
if (addr == null) {
|
||||
throw new RuntimeException("Unable to retrieve buffer's address");
|
||||
}
|
||||
return addr;
|
||||
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.sharedmem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Random;
|
||||
|
||||
public class ProducerApp {
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
digest.digest(new byte[256]);
|
||||
byte[] dummy = digest.digest();
|
||||
int hashLen = dummy.length;
|
||||
|
||||
|
||||
long size = Long.parseLong(args[1]);
|
||||
MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen);
|
||||
|
||||
System.out.println("Starting producer iterations...");
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long iterations = 0;
|
||||
int capacity = shm.capacity();
|
||||
Random rnd = new Random();
|
||||
|
||||
while(System.currentTimeMillis() - start < 30000) {
|
||||
|
||||
for (int i = 0; i < capacity - hashLen; i++) {
|
||||
byte value = (byte) (rnd.nextInt(256) & 0x00ff);
|
||||
digest.update(value);
|
||||
shm.put(i, value);
|
||||
}
|
||||
|
||||
// Write hash at the end
|
||||
byte[] hash = digest.digest();
|
||||
shm.position(capacity - hashLen);
|
||||
shm.put(hash);
|
||||
iterations++;
|
||||
}
|
||||
|
||||
System.out.printf("%d iterations run\n", iterations);
|
||||
System.out.println("Press <enter> to exit");
|
||||
System.console().readLine();
|
||||
|
||||
}
|
||||
|
||||
private static long getBufferAddress(MappedByteBuffer shm) {
|
||||
try {
|
||||
Class<?> cls = shm.getClass();
|
||||
Method maddr = cls.getMethod("address");
|
||||
maddr.setAccessible(true);
|
||||
Long addr = (Long) maddr.invoke(shm);
|
||||
if ( addr == null ) {
|
||||
throw new RuntimeException("Unable to retrieve buffer's address");
|
||||
}
|
||||
return addr;
|
||||
}
|
||||
catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static MappedByteBuffer createSharedMemory(String path, long size) {
|
||||
|
||||
try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(),
|
||||
EnumSet.of(
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.SPARSE,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.READ))) {
|
||||
|
||||
return fc.map(FileChannel.MapMode.READ_WRITE, 0, size);
|
||||
}
|
||||
catch( IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,117 @@
|
|||
package com.baeldung.sharedmem;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.MappedByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Random;
|
||||
|
||||
public class ProducerAppWithSpinLock {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
run(args);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
} finally {
|
||||
System.console()
|
||||
.printf("Press <enter> to continue");
|
||||
System.console()
|
||||
.readLine();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void run(String[] args) throws Exception {
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA1");
|
||||
digest.digest(new byte[256]);
|
||||
byte[] dummy = digest.digest();
|
||||
int hashLen = dummy.length;
|
||||
|
||||
|
||||
long size = Long.parseLong(args[1]);
|
||||
MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen);
|
||||
|
||||
// Cleanup lock area
|
||||
shm.putInt(0,0);
|
||||
|
||||
long addr = getBufferAddress(shm);
|
||||
System.out.printf("Buffer address: 0x%08x\n",addr);
|
||||
Random rnd = new Random();
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
long iterations = 0;
|
||||
int capacity = shm.capacity();
|
||||
System.out.println("Starting producer iterations...");
|
||||
SpinLock lock = new SpinLock(addr);
|
||||
while(System.currentTimeMillis() - start < 30000) {
|
||||
|
||||
if(!lock.tryLock(5000)) {
|
||||
throw new RuntimeException("Unable to acquire lock");
|
||||
}
|
||||
|
||||
try {
|
||||
// Skip the first 4 bytes, as they're used by the lock
|
||||
for (int i = 4; i < capacity - hashLen; i++) {
|
||||
byte value = (byte) (rnd.nextInt(256) & 0x00ff);
|
||||
digest.update(value);
|
||||
shm.put(i, value);
|
||||
}
|
||||
|
||||
// Write hash at the end
|
||||
byte[] hash = digest.digest();
|
||||
shm.position(capacity-hashLen);
|
||||
shm.put(hash);
|
||||
iterations++;
|
||||
}
|
||||
finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.printf("%d iterations run\n", iterations);
|
||||
|
||||
}
|
||||
|
||||
private static long getBufferAddress(MappedByteBuffer shm) {
|
||||
try {
|
||||
Class<?> cls = shm.getClass();
|
||||
Method maddr = cls.getMethod("address");
|
||||
maddr.setAccessible(true);
|
||||
Long addr = (Long) maddr.invoke(shm);
|
||||
if ( addr == null ) {
|
||||
throw new RuntimeException("Unable to retrieve buffer's address");
|
||||
}
|
||||
return addr;
|
||||
}
|
||||
catch( NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static MappedByteBuffer createSharedMemory(String path, long size) {
|
||||
|
||||
try (FileChannel fc = (FileChannel)Files.newByteChannel(new File(path).toPath(),
|
||||
EnumSet.of(
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.SPARSE,
|
||||
StandardOpenOption.WRITE,
|
||||
StandardOpenOption.READ))) {
|
||||
|
||||
return fc.map(FileChannel.MapMode.READ_WRITE, 0, size);
|
||||
|
||||
}
|
||||
catch( IOException ioe) {
|
||||
throw new RuntimeException(ioe);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.sharedmem;
|
||||
|
||||
//import sun.misc.Unsafe;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import sun.misc.Unsafe;
|
||||
|
||||
public class SpinLock {
|
||||
private static final Unsafe unsafe;
|
||||
|
||||
static {
|
||||
try {
|
||||
Field f = Unsafe.class.getDeclaredField("theUnsafe");
|
||||
f.setAccessible(true);
|
||||
unsafe = (Unsafe) f.get(null);
|
||||
}
|
||||
catch(NoSuchFieldException | IllegalAccessException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private final long addr;
|
||||
|
||||
public SpinLock(long addr) {
|
||||
this.addr = addr;
|
||||
}
|
||||
|
||||
public boolean tryLock(long maxWait) {
|
||||
long deadline = System.currentTimeMillis() + maxWait;
|
||||
while(System.currentTimeMillis() < deadline ) {
|
||||
if ( unsafe.compareAndSwapInt(null,addr,0,1)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void unlock() {
|
||||
unsafe.putInt(addr,0);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.park;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PreemptivePermitsBehaviorUnitTest {
|
||||
|
||||
private final Thread parkedThread = new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
LockSupport.unpark(this);
|
||||
LockSupport.park();
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void givenThreadWhenPreemptivePermitShouldNotPark() {
|
||||
assertTimeoutPreemptively(Duration.of(1, ChronoUnit.SECONDS), () -> {
|
||||
parkedThread.start();
|
||||
parkedThread.join();
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.park;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RepeatedPreemptivePermitsBehaviorUnitTest {
|
||||
|
||||
private final Thread parkedThread = new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
LockSupport.unpark(this);
|
||||
LockSupport.unpark(this);
|
||||
LockSupport.park();
|
||||
LockSupport.park();
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void givenThreadWhenRepeatedPreemptivePermitShouldPark() {
|
||||
Callable<Boolean> callable = () -> {
|
||||
parkedThread.start();
|
||||
parkedThread.join();
|
||||
return true;
|
||||
};
|
||||
|
||||
boolean result = false;
|
||||
final Future<Boolean> future = Executors.newSingleThreadExecutor().submit(callable);
|
||||
try {
|
||||
result = future.get(1, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException | ExecutionException | TimeoutException e) {
|
||||
// Expected the thread to be parked
|
||||
}
|
||||
assertFalse(result, "The thread should be parked");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
package com.baeldung.park;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
class ThreadInterruptedBehaviorUnitTest {
|
||||
|
||||
@Test
|
||||
@Timeout(3)
|
||||
void givenParkedThreadWhenInterruptedShouldNotResetInterruptedFlag() throws InterruptedException {
|
||||
final Thread thread = new Thread(LockSupport::park);
|
||||
thread.start();
|
||||
thread.interrupt();
|
||||
assertTrue(thread.isInterrupted(), "The thread should have the interrupted flag");
|
||||
thread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(3)
|
||||
void givenParkedThreadWhenNotInterruptedShouldNotHaveInterruptedFlag() throws InterruptedException {
|
||||
final Thread thread = new Thread(LockSupport::park);
|
||||
thread.start();
|
||||
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
|
||||
LockSupport.unpark(thread);
|
||||
assertFalse(thread.isInterrupted(), "The thread shouldn't have the interrupted flag");
|
||||
thread.join();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(3)
|
||||
void givenWaitingThreadWhenNotInterruptedShouldNotHaveInterruptedFlag() throws InterruptedException {
|
||||
|
||||
final Thread thread = new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
try {
|
||||
this.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// The thread was interrupted
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
thread.start();
|
||||
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
|
||||
thread.interrupt();
|
||||
thread.join();
|
||||
assertFalse(thread.isInterrupted(), "The thread shouldn't have the interrupted flag");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.park;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
|
||||
class TreadMonitorsBehaviorUnitTest {
|
||||
|
||||
@Test
|
||||
@Timeout(3)
|
||||
void giveThreadWhenNotifyWithoutAcquiringMonitorThrowsException() {
|
||||
final Thread thread = new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
synchronized (this) {
|
||||
try {
|
||||
this.wait();
|
||||
} catch (InterruptedException e) {
|
||||
// The thread was interrupted
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
assertThrows(IllegalMonitorStateException.class, () -> {
|
||||
thread.start();
|
||||
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
|
||||
thread.notify();
|
||||
thread.join();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(3)
|
||||
void giveThreadWhenUnparkWithoutAcquiringMonitor() {
|
||||
final Thread thread = new Thread(LockSupport::park);
|
||||
assertTimeoutPreemptively(Duration.of(2, ChronoUnit.SECONDS), () -> {
|
||||
thread.start();
|
||||
LockSupport.unpark(thread);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -21,7 +21,9 @@
|
|||
<!--<module>core-java-8-2</module> -->
|
||||
<!--<module>core-java-8-datetime</module> -->
|
||||
<!--<module>core-java-8-datetime-2</module> -->
|
||||
<!--<module>core-java-collections-conversions-2</module> -->
|
||||
<module>core-java-collections-conversions-2</module>
|
||||
<module>core-java-collections-conversions-3</module>
|
||||
<module>core-java-concurrency-advanced-5</module>
|
||||
<!--<module>core-java-lang</module> -->
|
||||
<!--<module>core-java-lang-math-3</module> -->
|
||||
<!--<module>core-java-security</module> -->
|
||||
|
@ -32,6 +34,7 @@
|
|||
<!-- <module>core-java-modules/core-java-16</module> --> <!-- JAVA-26056 -->
|
||||
<!-- <module>core-java-modules/core-java-17</module> --> <!-- JAVA-26056 -->
|
||||
<!-- <module>core-java-modules/core-java-19</module> --> <!-- JAVA-26056 -->
|
||||
<module>core-java-numbers-conversions</module>
|
||||
<module>core-java-9-improvements</module>
|
||||
<module>core-java-9-streams</module>
|
||||
<module>core-java-9</module>
|
||||
|
@ -195,9 +198,10 @@
|
|||
<module>core-java-records</module>
|
||||
<module>core-java-9-jigsaw</module>
|
||||
<!--<module>core-java-20</module>--> <!--JAVA-25373-->
|
||||
<!--<module>core-java-conditionals</module>--> <!--JAVA-25373-->
|
||||
<module>core-java-collections-set</module>
|
||||
<module>core-java-date-operations-1</module>
|
||||
<!--<module>core-java-datetime-conversion</module>--> <!--JAVA-25433-->
|
||||
<module>core-java-datetime-conversion</module>
|
||||
<module>core-java-httpclient</module>
|
||||
<module>java-native</module>
|
||||
</modules>
|
||||
|
|
|
@ -3,14 +3,11 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>inject-intro</artifactId>
|
||||
<artifactId>avaje</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>avaje-inject-intro</name>
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<avaje.inject.version>9.5</avaje.inject.version>
|
||||
</properties>
|
||||
<name>avaje</name>
|
||||
<description>Avaje Inject Intro</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.avaje</groupId>
|
||||
|
@ -34,4 +31,10 @@
|
|||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
<avaje.inject.version>9.5</avaje.inject.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -18,6 +18,7 @@
|
|||
<module>dagger</module>
|
||||
<module>flyway-cdi-extension</module>
|
||||
<module>guice</module>
|
||||
<module>avaje</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
|
@ -192,7 +192,7 @@
|
|||
<ethereumj-core.version>1.5.0-RELEASE</ethereumj-core.version>
|
||||
<web3j.core.version>3.3.1</web3j.core.version>
|
||||
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
|
||||
<jsonpath.version>2.4.0</jsonpath.version>
|
||||
<jsonpath.version>2.8.0</jsonpath.version>
|
||||
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
|
||||
<compiler.plugin.version>3.1</compiler.plugin.version>
|
||||
</properties>
|
||||
|
|
|
@ -8,7 +8,6 @@
|
|||
<name>google-auto-project</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
|
|
@ -21,7 +21,7 @@
|
|||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<version>${json-path.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
|
@ -59,7 +59,7 @@
|
|||
|
||||
<properties>
|
||||
<h2.version>2.1.214</h2.version>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<json-path.version>5.3.2</json-path.version>
|
||||
<spring-boot.version>2.5.0</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -29,7 +29,7 @@
|
|||
|
||||
<properties>
|
||||
<javax.websocket-api.version>1.1</javax.websocket-api.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -37,7 +37,7 @@
|
|||
<!--</plugin> </plugins> </build> -->
|
||||
|
||||
<properties>
|
||||
<hibernate-validator.ap.version>6.2.0.Final</hibernate-validator.ap.version>
|
||||
<hibernate-validator.ap.version>8.0.1.Final</hibernate-validator.ap.version>
|
||||
<spring.boot.version>3.0.4</spring.boot.version>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -12,3 +12,4 @@ This module contains articles about Jersey.
|
|||
- [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers)
|
||||
- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey)
|
||||
- [@FormDataParam vs. @FormParam in Jersey](https://www.baeldung.com/jersey-formdataparam-vs-formparam)
|
||||
- [Add a List as Query Parameter in Jersey](https://www.baeldung.com/java-jersey-list-query-param)
|
||||
|
|
|
@ -64,8 +64,8 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<joda-time.version>2.12.5</joda-time.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,6 +1,10 @@
|
|||
package com.baeldung.gson.conversion;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.google.gson.*;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
|
@ -11,11 +15,14 @@ public class JsonObjectConversionsUnitTest {
|
|||
// Example 1: Using JsonParser
|
||||
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
|
||||
|
||||
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
|
||||
JsonObject jsonObject = JsonParser.parseString(json)
|
||||
.getAsJsonObject();
|
||||
|
||||
Assert.assertTrue(jsonObject.isJsonObject());
|
||||
Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung"));
|
||||
Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true);
|
||||
assertTrue(jsonObject.isJsonObject());
|
||||
assertEquals("Baeldung", jsonObject.get("name")
|
||||
.getAsString());
|
||||
assertTrue(jsonObject.get("java")
|
||||
.getAsBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -25,9 +32,11 @@ public class JsonObjectConversionsUnitTest {
|
|||
|
||||
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
|
||||
|
||||
Assert.assertTrue(convertedObject.isJsonObject());
|
||||
Assert.assertTrue(convertedObject.get("name").getAsString().equals("Baeldung"));
|
||||
Assert.assertTrue(convertedObject.get("java").getAsBoolean() == true);
|
||||
assertTrue(convertedObject.isJsonObject());
|
||||
assertEquals("Baeldung", convertedObject.get("name")
|
||||
.getAsString());
|
||||
assertTrue(convertedObject.get("java")
|
||||
.getAsBoolean());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -3,8 +3,9 @@ package com.baeldung.gson.deserialization.test;
|
|||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.instanceOf;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.ArrayList;
|
||||
|
@ -68,7 +69,7 @@ public class GsonDeserializationUnitTest {
|
|||
|
||||
final GenericFoo<Integer> targetObject = new Gson().fromJson(json, typeToken);
|
||||
|
||||
assertEquals(targetObject.theValue, new Integer(1));
|
||||
assertEquals(targetObject.theValue, Integer.valueOf(1));
|
||||
}
|
||||
|
||||
// tests - multiple elements
|
||||
|
@ -98,8 +99,7 @@ public class GsonDeserializationUnitTest {
|
|||
@Test
|
||||
public void whenDeserializingJsonIntoElements_thenCorrect() {
|
||||
final String jsonSourceObject = "{\"valueInt\":7,\"valueString\":\"seven\"}";
|
||||
final JsonParser jParser = new JsonParser();
|
||||
final JsonElement jElement = jParser.parse(jsonSourceObject);
|
||||
final JsonElement jElement = JsonParser.parseString(jsonSourceObject);
|
||||
final JsonObject jObject = jElement.getAsJsonObject();
|
||||
final int intValue = jObject.get("valueInt").getAsInt();
|
||||
final String stringValue = jObject.get("valueString").getAsString();
|
||||
|
|
|
@ -16,79 +16,71 @@ public class JsonCompareUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenIdenticalSimpleObjects_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\", \"fullName\": \"Emily Jenkins\",\"age\": 27}}";
|
||||
|
||||
assertTrue(parser.parse(string1)
|
||||
.isJsonObject());
|
||||
assertEquals(parser.parse(string1), parser.parse(string2));
|
||||
assertTrue(JsonParser.parseString(string1).isJsonObject());
|
||||
assertEquals(JsonParser.parseString(string1), JsonParser.parseString(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameObjectsInDifferentOrder_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27 }}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"age\": 27, \"fullName\": \"Emily Jenkins\" }}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
JsonElement json1 = JsonParser.parseString(string1);
|
||||
JsonElement json2 = JsonParser.parseString(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalArrays_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "[10, 20, 30]";
|
||||
String string2 = "[10, 20, 30]";
|
||||
|
||||
assertTrue(parser.parse(string1)
|
||||
assertTrue(JsonParser.parseString(string1)
|
||||
.isJsonArray());
|
||||
assertEquals(parser.parse(string1), parser.parse(string2));
|
||||
assertEquals(JsonParser.parseString(string1), JsonParser.parseString(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArraysInDifferentOrder_whenCompared_thenNotEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "[20, 10, 30]";
|
||||
String string2 = "[10, 20, 30]";
|
||||
|
||||
assertNotEquals(parser.parse(string1), parser.parse(string2));
|
||||
assertNotEquals(JsonParser.parseString(string1), JsonParser.parseString(string2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalNestedObjects_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"fav_product\": \"Coke\", \"last_buy\": \"2012-04-23\"}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"fav_product\": \"Coke\"}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
JsonElement json1 = JsonParser.parseString(string1);
|
||||
JsonElement json2 = JsonParser.parseString(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdenticalNestedObjectsWithArray_whenCompared_thenEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
JsonElement json1 = JsonParser.parseString(string1);
|
||||
JsonElement json2 = JsonParser.parseString(string2);
|
||||
|
||||
assertEquals(json1, json2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() {
|
||||
JsonParser parser = new JsonParser();
|
||||
String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}";
|
||||
String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}";
|
||||
|
||||
JsonElement json1 = parser.parse(string1);
|
||||
JsonElement json2 = parser.parse(string2);
|
||||
JsonElement json1 = JsonParser.parseString(string1);
|
||||
JsonElement json2 = JsonParser.parseString(string2);
|
||||
|
||||
assertNotEquals(json1, json2);
|
||||
}
|
||||
|
|
|
@ -43,8 +43,8 @@ public class PrimitiveValuesUnitTest {
|
|||
gson.toJson(model);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class) public void
|
||||
whenSerializingNaN_thenShouldRaiseAnException() {
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenSerializingNaN_thenShouldRaiseAnException() {
|
||||
FloatExample model = new FloatExample();
|
||||
model.value = Float.NaN;
|
||||
|
||||
|
@ -52,7 +52,8 @@ public class PrimitiveValuesUnitTest {
|
|||
gson.toJson(model);
|
||||
}
|
||||
|
||||
@Test public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() {
|
||||
@Test
|
||||
public void whenDeserializingFromJSON_thenShouldParseTheValueInTheString() {
|
||||
String json = "{\"byteValue\": 17, \"shortValue\": 3, \"intValue\": 3, "
|
||||
+ "\"longValue\": 3, \"floatValue\": 3.5" + ", \"doubleValue\": 3.5"
|
||||
+ ", \"booleanValue\": true, \"charValue\": \"a\"}";
|
||||
|
@ -72,14 +73,16 @@ public class PrimitiveValuesUnitTest {
|
|||
// @formatter:on
|
||||
}
|
||||
|
||||
@Test public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() {
|
||||
@Test
|
||||
public void whenDeserializingHighPrecissionNumberIntoFloat_thenShouldPerformRounding() {
|
||||
String json = "{\"value\": 12.123425589123456}";
|
||||
Gson gson = new Gson();
|
||||
FloatExample model = gson.fromJson(json, FloatExample.class);
|
||||
assertEquals(12.123426f, model.value, 0.000001);
|
||||
}
|
||||
|
||||
@Test public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() {
|
||||
@Test
|
||||
public void whenDeserializingHighPrecissiongNumberIntoDouble_thenShouldPerformRounding() {
|
||||
String json = "{\"value\": 12.123425589123556}";
|
||||
Gson gson = new Gson();
|
||||
DoubleExample model = gson.fromJson(json, DoubleExample.class);
|
||||
|
@ -87,12 +90,12 @@ public class PrimitiveValuesUnitTest {
|
|||
}
|
||||
|
||||
|
||||
@Test public void whenDeserializingValueThatOverflows_thenShouldOverflowSilently() {
|
||||
@Test(expected = JsonSyntaxException.class)
|
||||
public void whenDeserializingValueThatOverflows_thenShouldRaiseAnException() {
|
||||
Gson gson = new Gson();
|
||||
String json = "{\"value\": \"300\"}";
|
||||
ByteExample model = gson.fromJson(json, ByteExample.class);
|
||||
|
||||
assertEquals(44, model.value);
|
||||
}
|
||||
|
||||
@Test public void whenDeserializingRealIntoByte_thenShouldRaiseAnException() {
|
||||
|
|
|
@ -41,8 +41,7 @@ public class GsonSerializeUnitTest {
|
|||
.serializeNulls()
|
||||
.disableHtmlEscaping()
|
||||
.create()
|
||||
.toJson(new JsonParser()
|
||||
.parse("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}"));
|
||||
.toJson(JsonParser.parseString("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}"));
|
||||
Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -38,7 +38,7 @@
|
|||
|
||||
<properties>
|
||||
<jsonb-api.version>1.0</jsonb-api.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<javax.version>1.1.2</javax.version>
|
||||
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>
|
||||
</properties>
|
||||
|
|
|
@ -13,7 +13,6 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- json-path -->
|
||||
<dependency>
|
||||
<groupId>com.jayway.jsonpath</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
|
@ -22,8 +21,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<!-- json-path -->
|
||||
<json-path.version>2.4.0</json-path.version>
|
||||
<json-path.version>2.8.0</json-path.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -68,7 +68,7 @@
|
|||
<networknt.json.schema.version>1.0.72</networknt.json.schema.version>
|
||||
<jsonb-api.version>1.0</jsonb-api.version>
|
||||
<yasson.version>1.0.1</yasson.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<javax.version>1.1.2</javax.version>
|
||||
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>
|
||||
</properties>
|
||||
|
|
|
@ -141,7 +141,7 @@
|
|||
<typesafe-akka.version>2.5.11</typesafe-akka.version>
|
||||
<streamex.version>0.8.1</streamex.version>
|
||||
<docker.version>3.0.14</docker.version>
|
||||
<caffeine.version>2.5.5</caffeine.version>
|
||||
<caffeine.version>3.1.8</caffeine.version>
|
||||
<findbugs.version>3.0.2</findbugs.version>
|
||||
<fugue.version>4.5.1</fugue.version>
|
||||
<jnats.version>1.0</jnats.version>
|
||||
|
|
|
@ -108,7 +108,7 @@
|
|||
<dependency>
|
||||
<groupId>org.agrona</groupId>
|
||||
<artifactId>agrona</artifactId>
|
||||
<version>1.17.1</version>
|
||||
<version>${agrona.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -126,7 +126,7 @@
|
|||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
|
@ -154,14 +154,14 @@
|
|||
<dependency>
|
||||
<groupId>uk.co.real-logic</groupId>
|
||||
<artifactId>sbe-tool</artifactId>
|
||||
<version>1.27.0</version>
|
||||
<version>${sbe-tool.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>3.0.0</version>
|
||||
<version>${build-helper-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add-source</id>
|
||||
|
@ -204,7 +204,11 @@
|
|||
<rcaller.version>3.0</rcaller.version>
|
||||
<rserve.version>1.8.1</rserve.version>
|
||||
<libphonenumber.version>8.12.9</libphonenumber.version>
|
||||
<org.modelmapper.version>2.4.4</org.modelmapper.version>
|
||||
<org.modelmapper.version>3.2.0</org.modelmapper.version>
|
||||
<agrona.version>1.17.1</agrona.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<sbe-tool.version>1.27.0</sbe-tool.version>
|
||||
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -106,7 +106,7 @@
|
|||
<google-sheets.version>v4-rev493-1.21.0</google-sheets.version>
|
||||
<docx4j.version>6.1.2</docx4j.version>
|
||||
<jaxb-runtime.version>2.3.1</jaxb-runtime.version>
|
||||
<gson.version>2.8.7</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<yamlbeans.version>1.15</yamlbeans.version>
|
||||
<apache-thrift.version>0.14.2</apache-thrift.version>
|
||||
<google-protobuf.version>3.17.3</google-protobuf.version>
|
||||
|
|
|
@ -210,7 +210,7 @@
|
|||
<kafka.version>3.3.1</kafka.version>
|
||||
<ignite.version>2.14.0</ignite.version>
|
||||
<ignite-spring-data.version>2.9.1</ignite-spring-data.version>
|
||||
<gson.version>2.9.1</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<cache.version>1.1.1</cache.version>
|
||||
<flink.version>1.5.0</flink.version>
|
||||
<hazelcast.version>5.2.0</hazelcast.version>
|
||||
|
|
|
@ -110,7 +110,7 @@
|
|||
|
||||
<properties>
|
||||
<okhttp.version>4.9.1</okhttp.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<mockwebserver.version>4.9.1</mockwebserver.version>
|
||||
<jetty.httpclient.version>1.0.3</jetty.httpclient.version>
|
||||
<jetty.server.version>9.4.19.v20190610</jetty.server.version>
|
||||
|
|
|
@ -103,7 +103,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<gson.version>2.10.1</gson.version>
|
||||
<httpclient.version>4.5.3</httpclient.version>
|
||||
<com.squareup.okhttp3.version>4.9.1</com.squareup.okhttp3.version>
|
||||
<googleclient.version>1.23.0</googleclient.version>
|
||||
|
|
|
@ -56,7 +56,7 @@
|
|||
<properties>
|
||||
<!-- sftp -->
|
||||
<jsch.version>0.1.55</jsch.version>
|
||||
<sshj.version>0.27.0</sshj.version>
|
||||
<sshj.version>0.37.0</sshj.version>
|
||||
<vfs.version>2.4</vfs.version>
|
||||
<zip4j.version>2.9.0</zip4j.version>
|
||||
<opencsv.version>5.8</opencsv.version>
|
||||
|
|
|
@ -20,14 +20,14 @@ import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
|
|||
|
||||
public class SftpFileTransferLiveTest {
|
||||
|
||||
private String remoteHost = "HOST_NAME_HERE";
|
||||
private String username = "USERNAME_HERE";
|
||||
private String password = "PASSWORD_HERE";
|
||||
private String localFile = "src/main/resources/input.txt";
|
||||
private String remoteFile = "welcome.txt";
|
||||
private String localDir = "src/main/resources/";
|
||||
private String remoteDir = "remote_sftp_test/";
|
||||
private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
|
||||
private final String remoteHost = "HOST_NAME_HERE";
|
||||
private final String username = "USERNAME_HERE";
|
||||
private final String password = "PASSWORD_HERE";
|
||||
private final String localFile = "src/main/resources/input.txt";
|
||||
private final String remoteFile = "welcome.txt";
|
||||
private final String localDir = "src/main/resources/";
|
||||
private final String remoteDir = "remote_sftp_test/";
|
||||
private final String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
|
||||
|
||||
@Test
|
||||
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
|
||||
|
@ -100,6 +100,7 @@ public class SftpFileTransferLiveTest {
|
|||
client.addHostKeyVerifier(new PromiscuousVerifier());
|
||||
client.connect(remoteHost);
|
||||
client.authPassword(username, password);
|
||||
client.useCompression();
|
||||
return client;
|
||||
}
|
||||
|
||||
|
|
|
@ -213,7 +213,7 @@
|
|||
<serenity.version>1.9.9</serenity.version>
|
||||
<serenity.jbehave.version>1.46.0</serenity.jbehave.version>
|
||||
<serenity.jira.version>1.9.0</serenity.jira.version>
|
||||
<serenity.plugin.version>3.6.12</serenity.plugin.version>
|
||||
<serenity.plugin.version>4.0.18</serenity.plugin.version>
|
||||
<jsonassert.version>1.5.0</jsonassert.version>
|
||||
<awaitility.version>3.0.0</awaitility.version>
|
||||
<hoverfly-java.version>0.8.1</hoverfly-java.version>
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue