Merge remote-tracking branch 'upstream/master'
This commit is contained in:
@@ -15,3 +15,5 @@
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
|
||||
@@ -3,5 +3,5 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [String Matching in Groovy](http://www.baeldung.com/)
|
||||
- [Groovy def Keyword]
|
||||
|
||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Maps in Groovy](http://www.baeldung.com/)
|
||||
- [Maps in Groovy](https://www.baeldung.com/groovy-maps)
|
||||
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.IntFunction;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamArrayConversion {
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingFunctionalInterface(Stream<String> stringStream) {
|
||||
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
|
||||
@Override
|
||||
public String[] apply(int value) {
|
||||
return new String[value];
|
||||
}
|
||||
};
|
||||
|
||||
return stringStream.toArray(intFunction);
|
||||
}
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingMethodReference(Stream<String> stringStream) {
|
||||
return stringStream.toArray(String[]::new);
|
||||
}
|
||||
|
||||
public static String[] stringStreamToStringArrayUsingLambda(Stream<String> stringStream) {
|
||||
return stringStream.toArray(value -> new String[value]);
|
||||
}
|
||||
|
||||
public static Integer[] integerStreamToIntegerArray(Stream<Integer> integerStream) {
|
||||
return integerStream.toArray(Integer[]::new);
|
||||
}
|
||||
|
||||
public static int[] intStreamToPrimitiveIntArray(Stream<Integer> integerStream) {
|
||||
return integerStream.mapToInt(i -> i).toArray();
|
||||
}
|
||||
|
||||
public static Stream<String> stringArrayToStreamUsingArraysStream(String[] stringArray) {
|
||||
return Arrays.stream(stringArray);
|
||||
}
|
||||
|
||||
public static Stream<String> stringArrayToStreamUsingStreamOf(String[] stringArray) {
|
||||
return Stream.of(stringArray);
|
||||
}
|
||||
|
||||
public static IntStream primitiveIntArrayToStreamUsingArraysStream(int[] intArray) {
|
||||
return Arrays.stream(intArray);
|
||||
}
|
||||
|
||||
public static Stream<int[]> primitiveIntArrayToStreamUsingStreamOf(int[] intArray) {
|
||||
return Stream.of(intArray);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.array.conversions;
|
||||
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.intStreamToPrimitiveIntArray;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.integerStreamToIntegerArray;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingFunctionalInterface;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingLambda;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingMethodReference;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingArraysStream;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingStreamOf;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingArraysStream;
|
||||
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingStreamOf;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import com.google.common.collect.Iterators;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamArrayConversionUnitTest {
|
||||
|
||||
private String[] stringArray = new String[]{"baeldung", "convert", "to", "string", "array"};
|
||||
private Integer[] integerArray = new Integer[]{1, 2, 3, 4, 5, 6, 7};
|
||||
private int[] intPrimitiveArray = new int[]{1, 2, 3, 4, 5, 6, 7};
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingFunctionalInterface() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingFunctionalInterface(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingMethodReference() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingMethodReference(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringStream_thenConvertToStringArrayUsingLambda() {
|
||||
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
|
||||
assertArrayEquals(stringArray, stringStreamToStringArrayUsingLambda(stringStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerStream_thenConvertToIntegerArray() {
|
||||
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
|
||||
assertArrayEquals(integerArray, integerStreamToIntegerArray(integerStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntStream_thenConvertToIntegerArray() {
|
||||
Stream<Integer> integerStream = IntStream.rangeClosed(1, 7).boxed();
|
||||
assertArrayEquals(intPrimitiveArray, intStreamToPrimitiveIntArray(integerStream));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringArray_whenConvertedTwoWays_thenConvertedStreamsAreEqual() {
|
||||
assertTrue(Iterators
|
||||
.elementsEqual(stringArrayToStreamUsingArraysStream(stringArray).iterator(),
|
||||
stringArrayToStreamUsingStreamOf(stringArray).iterator()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPrimitiveArray_whenConvertedTwoWays_thenConvertedStreamsAreNotEqual() {
|
||||
assertFalse(Iterators.elementsEqual(
|
||||
primitiveIntArrayToStreamUsingArraysStream(intPrimitiveArray).iterator(),
|
||||
primitiveIntArrayToStreamUsingStreamOf(intPrimitiveArray).iterator()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
||||
@@ -7,3 +7,4 @@
|
||||
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
|
||||
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
|
||||
- [Guide to jlink](https://www.baeldung.com/jlink)
|
||||
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ public class OptionalChainingUnitTest {
|
||||
}
|
||||
|
||||
private Optional<String> createOptional(String input) {
|
||||
if (input == null || input == "" || input == "empty") {
|
||||
if (input == null || "".equals(input) || "empty".equals(input)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
@@ -21,5 +21,14 @@
|
||||
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
|
||||
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
|
||||
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
|
||||
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
|
||||
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
|
||||
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
|
||||
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
|
||||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
|
||||
- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
|
||||
|
||||
@@ -8,4 +8,5 @@
|
||||
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
|
||||
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
|
||||
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.exception.numberformat</groupId>
|
||||
<artifactId>core-java-exceptions</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>core-java-exceptions</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package com.baeldung.exception.numberformat;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.text.NumberFormat;
|
||||
import java.text.ParseException;
|
||||
import java.util.Locale;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* A set of examples tested to show cases where NumberFormatException is thrown and not thrown.
|
||||
*/
|
||||
public class NumberFormatExceptionUnitTest {
|
||||
|
||||
Logger LOG = Logger.getLogger(NumberFormatExceptionUnitTest.class.getName());
|
||||
|
||||
/* ---INTEGER FAIL CASES--- */
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenByteConstructor_whenAlphabetAsInput_thenFail() {
|
||||
Byte byteInt = new Byte("one");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenShortConstructor_whenSpaceInInput_thenFail() {
|
||||
Short shortInt = new Short("2 ");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseIntMethod_whenSpaceInInput_thenFail() {
|
||||
Integer aIntPrim = Integer.parseInt("6000 ");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseIntMethod_whenUnderscoreInInput_thenFail() {
|
||||
int bIntPrim = Integer.parseInt("6_000");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenIntegerValueOfMethod_whenCommaInInput_thenFail() {
|
||||
Integer cIntPrim = Integer.valueOf("6,000");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenBigIntegerConstructor_whenDecimalInInput_thenFail() {
|
||||
BigInteger bigInteger = new BigInteger("4.0");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenDecodeMethod_whenAlphabetInInput_thenFail() {
|
||||
Long decodeInteger = Long.decode("64403L");
|
||||
}
|
||||
|
||||
/* ---INTEGER PASS CASES--- */
|
||||
@Test
|
||||
public void givenInvalidNumberInputs_whenOptimized_thenPass() {
|
||||
Byte byteInt = new Byte("1");
|
||||
assertEquals(1, byteInt.intValue());
|
||||
|
||||
Short shortInt = new Short("2 ".trim());
|
||||
assertEquals(2, shortInt.intValue());
|
||||
|
||||
Integer aIntObj = Integer.valueOf("6");
|
||||
assertEquals(6, aIntObj.intValue());
|
||||
|
||||
BigInteger bigInteger = new BigInteger("4");
|
||||
assertEquals(4, bigInteger.intValue());
|
||||
|
||||
int aIntPrim = Integer.parseInt("6000 ".trim());
|
||||
assertEquals(6000, aIntPrim);
|
||||
|
||||
int bIntPrim = Integer.parseInt("6_000".replaceAll("_", ""));
|
||||
assertEquals(6000, bIntPrim);
|
||||
|
||||
int cIntPrim = Integer.parseInt("-6000");
|
||||
assertEquals(-6000, cIntPrim);
|
||||
|
||||
Long decodeInteger = Long.decode("644032334");
|
||||
assertEquals(644032334L, decodeInteger.longValue());
|
||||
}
|
||||
|
||||
/* ---DOUBLE FAIL CASES--- */
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenFloatConstructor_whenAlphabetInInput_thenFail() {
|
||||
Float floatDecimalObj = new Float("one.1");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenDoubleConstructor_whenAlphabetInInput_thenFail() {
|
||||
Double doubleDecimalObj = new Double("two.2");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenBigDecimalConstructor_whenSpecialCharsInInput_thenFail() {
|
||||
BigDecimal bigDecimalObj = new BigDecimal("3_0.3");
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void givenParseDoubleMethod_whenCommaInInput_thenFail() {
|
||||
double aDoublePrim = Double.parseDouble("4000,1");
|
||||
}
|
||||
|
||||
/* ---DOUBLE PASS CASES--- */
|
||||
@Test
|
||||
public void givenDoubleConstructor_whenDecimalInInput_thenPass() {
|
||||
Double doubleDecimalObj = new Double("2.2");
|
||||
assertEquals(2.2, doubleDecimalObj.doubleValue(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDoubleValueOfMethod_whenMinusInInput_thenPass() {
|
||||
Double aDoubleObj = Double.valueOf("-6000");
|
||||
assertEquals(-6000, aDoubleObj.doubleValue(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsDecimalNumber_whenParsedWithNumberFormat_thenPass() throws ParseException {
|
||||
Number parsedNumber = parseNumberWithLocale("4000.1", Locale.US);
|
||||
assertEquals(4000.1, parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
|
||||
assertEquals(4000, parsedNumber.intValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* In most European countries (for example, France), comma is used as decimal in place of period.
|
||||
* @throws ParseException if the input string contains special characters other than comma or decimal.
|
||||
* In this test case, anything after decimal (period) is dropped when a European locale is set.
|
||||
*/
|
||||
@Test
|
||||
public void givenEuDecimalNumberHasComma_whenParsedWithNumberFormat_thenPass() throws ParseException {
|
||||
Number parsedNumber = parseNumberWithLocale("4000,1", Locale.FRANCE);
|
||||
LOG.info("Number parsed is: " + parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber);
|
||||
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
|
||||
assertEquals(4000, parsedNumber.intValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a string into a number retaining all decimals, and symbols valid in a locale.
|
||||
* @param number the input string for a number.
|
||||
* @param locale the locale to consider while parsing a number.
|
||||
* @return the generic number object which can represent multiple number types.
|
||||
* @throws ParseException when input contains invalid characters.
|
||||
*/
|
||||
private Number parseNumberWithLocale(String number, Locale locale) throws ParseException {
|
||||
locale = locale == null ? Locale.getDefault() : locale;
|
||||
NumberFormat numberFormat = NumberFormat.getInstance(locale);
|
||||
return numberFormat.parse(number);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,3 +4,5 @@
|
||||
|
||||
### Relevant Articles:
|
||||
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
|
||||
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
|
||||
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
|
||||
|
||||
@@ -454,7 +454,7 @@
|
||||
<gson.version>2.8.2</gson.version>
|
||||
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<decimal4j.version>1.0.3</decimal4j.version>
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Utility class to find root cause exceptions.
|
||||
*/
|
||||
public class RootCauseFinder {
|
||||
|
||||
private RootCauseFinder() {
|
||||
}
|
||||
|
||||
public static Throwable findCauseUsingPlainJava(Throwable throwable) {
|
||||
Objects.requireNonNull(throwable);
|
||||
Throwable rootCause = throwable;
|
||||
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
|
||||
rootCause = rootCause.getCause();
|
||||
}
|
||||
return rootCause;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the age of a person from a given date.
|
||||
*/
|
||||
static class AgeCalculator {
|
||||
|
||||
private AgeCalculator() {
|
||||
}
|
||||
|
||||
public static int calculateAge(String birthDate) {
|
||||
if (birthDate == null || birthDate.isEmpty()) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
try {
|
||||
return Period
|
||||
.between(parseDate(birthDate), LocalDate.now())
|
||||
.getYears();
|
||||
} catch (DateParseException ex) {
|
||||
throw new CalculationException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDate parseDate(String birthDateAsString) {
|
||||
|
||||
LocalDate birthDate;
|
||||
try {
|
||||
birthDate = LocalDate.parse(birthDateAsString);
|
||||
} catch (DateTimeParseException ex) {
|
||||
throw new InvalidFormatException(birthDateAsString, ex);
|
||||
}
|
||||
|
||||
if (birthDate.isAfter(LocalDate.now())) {
|
||||
throw new DateOutOfRangeException(birthDateAsString);
|
||||
}
|
||||
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static class CalculationException extends RuntimeException {
|
||||
|
||||
CalculationException(DateParseException ex) {
|
||||
super(ex);
|
||||
}
|
||||
}
|
||||
|
||||
static class DateParseException extends RuntimeException {
|
||||
|
||||
DateParseException(String input) {
|
||||
super(input);
|
||||
}
|
||||
|
||||
DateParseException(String input, Throwable thr) {
|
||||
super(input, thr);
|
||||
}
|
||||
}
|
||||
|
||||
static class InvalidFormatException extends DateParseException {
|
||||
|
||||
InvalidFormatException(String input, Throwable thr) {
|
||||
super("Invalid date format: " + input, thr);
|
||||
}
|
||||
}
|
||||
|
||||
static class DateOutOfRangeException extends DateParseException {
|
||||
|
||||
DateOutOfRangeException(String date) {
|
||||
super("Date out of range: " + date);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static com.baeldung.exceptions.RootCauseFinder.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests the {@link RootCauseFinder}.
|
||||
*/
|
||||
public class RootCauseFinderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenBirthDate_whenCalculatingAge_thenAgeReturned() {
|
||||
try {
|
||||
int age = AgeCalculator.calculateAge("1990-01-01");
|
||||
Assertions.assertEquals(1990, LocalDate
|
||||
.now()
|
||||
.minus(age, ChronoUnit.YEARS)
|
||||
.getYear());
|
||||
} catch (CalculationException e) {
|
||||
Assertions.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("010102");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOutOfRangeDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("2020-04-04");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge(null);
|
||||
} catch (Exception ex) {
|
||||
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongFormatDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("010102");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateTimeParseException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOutOfRangeDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("2020-04-04");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateOutOfRangeException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseNotFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge(null);
|
||||
} catch (Exception ex) {
|
||||
assertTrue(ExceptionUtils.getRootCause(ex) instanceof IllegalArgumentException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("010102");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(Throwables.getRootCause(ex) instanceof DateTimeParseException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOutOfRangeDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge("2020-04-04");
|
||||
} catch (CalculationException ex) {
|
||||
assertTrue(Throwables.getRootCause(ex) instanceof DateOutOfRangeException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
|
||||
try {
|
||||
AgeCalculator.calculateAge(null);
|
||||
} catch (Exception ex) {
|
||||
assertTrue(Throwables.getRootCause(ex) instanceof IllegalArgumentException);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
<modules>
|
||||
<module>pre-jpms</module>
|
||||
<module>core-java-exceptions</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -6,4 +6,5 @@
|
||||
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
|
||||
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
|
||||
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
|
||||
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)
|
||||
@@ -7,4 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
|
||||
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
|
||||
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
|
||||
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
## Relevant Articles:
|
||||
- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives)
|
||||
- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.localization;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
public class App {
|
||||
|
||||
/**
|
||||
* Runs all available formatter
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
|
||||
Localization.run(locales);
|
||||
JavaSEFormat.run(locales);
|
||||
ICUFormat.run(locales);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.localization;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import com.ibm.icu.text.MessageFormat;
|
||||
|
||||
public class ICUFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
String format = bundle.getString("label-icu");
|
||||
MessageFormat formatter = new MessageFormat(format, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("ICU formatter");
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.localization;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class JavaSEFormat {
|
||||
|
||||
public static String getLabel(Locale locale, Object[] data) {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
|
||||
final String pattern = bundle.getString("label");
|
||||
final MessageFormat formatter = new MessageFormat(pattern, locale);
|
||||
return formatter.format(data);
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
System.out.println("Java formatter");
|
||||
final Date date = new Date(System.currentTimeMillis());
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.localization;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
public class Localization {
|
||||
|
||||
public static String getLabel(Locale locale) {
|
||||
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
|
||||
return bundle.getString("label");
|
||||
}
|
||||
|
||||
public static void run(List<Locale> locales) {
|
||||
locales.forEach(locale -> System.out.println(getLabel(locale)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.
|
||||
@@ -0,0 +1,2 @@
|
||||
label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoy\u00e9 {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
|
||||
label-icu={0} {2, plural, =0 {ne } other {}}vous a envoy\u00e9 {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.
|
||||
@@ -0,0 +1,2 @@
|
||||
label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
|
||||
label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.
|
||||
@@ -0,0 +1,2 @@
|
||||
label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
|
||||
label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.
|
||||
@@ -0,0 +1 @@
|
||||
label=Alice has sent you a message.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user