Merge branch 'master' into JAVA-5223

This commit is contained in:
freelansam
2021-05-17 22:37:02 +05:30
committed by GitHub
130 changed files with 4012 additions and 106 deletions
+6
View File
@@ -50,6 +50,11 @@
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
@@ -73,6 +78,7 @@
<junit.jupiter.version>5.7.0</junit.jupiter.version>
<assertj.version>3.17.2</assertj.version>
<mockserver.version>5.11.1</mockserver.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>
@@ -0,0 +1,48 @@
package com.baeldung.version;
import org.apache.commons.lang3.SystemUtils;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class VersionUnitTest {
@Test
public void givenJava_whenUsingRuntime_thenGetVersion() {
String expectedVersion = "11";
Runtime.Version runtimeVersion = Runtime.version();
String version = String.valueOf(runtimeVersion.version().get(0));
Assertions.assertThat(version).isEqualTo(expectedVersion);
}
@Test
@Disabled("Only valid for Java 8 and lower")
public void givenJava_whenUsingCommonsLang_thenGetVersion() {
int expectedVersion = 8;
String[] versionElements = SystemUtils.JAVA_SPECIFICATION_VERSION.split("\\.");
int discard = Integer.parseInt(versionElements[0]);
int version;
if (discard == 1) {
version = Integer.parseInt(versionElements[1]);
} else {
version = discard;
}
Assertions.assertThat(version).isEqualTo(expectedVersion);
}
@Test
@Disabled("Only valid for Java 8 and lower")
public void givenJava_whenUsingSystemProp_thenGetVersion() {
int expectedVersion = 8;
String[] versionElements = System.getProperty("java.version").split("\\.");
int discard = Integer.parseInt(versionElements[0]);
int version;
if (discard == 1) {
version = Integer.parseInt(versionElements[1]);
} else {
version = discard;
}
Assertions.assertThat(version).isEqualTo(expectedVersion);
}
}
@@ -45,4 +45,4 @@
<providermodule.version>1.0</providermodule.version>
</properties>
</project>
</project>
@@ -0,0 +1,91 @@
package com.baeldung.hash;
import java.util.Objects;
public class Player {
private String firstName;
private String lastName;
private String position;
public Player() {
}
public Player(String firstName, String lastName, String position) {
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, position);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Player other = (Player) obj;
if (firstName == null) {
if (other.firstName != null) {
return false;
}
} else if (!firstName.equals(other.firstName)) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
} else if (!lastName.equals(other.lastName)) {
return false;
}
if (position == null) {
if (other.position != null) {
return false;
}
} else if (!position.equals(other.position)) {
return false;
}
return true;
}
}
@@ -0,0 +1,67 @@
package com.baeldung.hash;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Objects;
import org.junit.Test;
public class HashCodeUnitTest {
@Test
public void whenCallingObjectsHashCodeOnIndenticalObjects_thenSameHashCodeReturned() {
String stringOne = "test";
String stringTwo = "test";
int hashCode1 = Objects.hashCode(stringOne);
int hashCode2 = Objects.hashCode(stringTwo);
assertEquals(hashCode1, hashCode2);
}
@Test
public void whenCallingObjectsHashCodeOnNullObject_thenZeroReturned() {
String nullString = null;
int hashCode = Objects.hashCode(nullString);
assertEquals(0, hashCode);
}
@Test
public void whenCallingObjectHashCodeOnIndenticalObjects_thenSameHashCodeReturned() {
Double valueOne = Double.valueOf(1.0012);
Double valueTwo = Double.valueOf(1.0012);
int hashCode1 = valueOne.hashCode();
int hashCode2 = valueTwo.hashCode();
assertEquals(hashCode1, hashCode2);
}
@Test(expected = NullPointerException.class)
public void whenCallingObjectHashCodeOnNullObject_theNullPointerExceptionThrown() {
Double value = null;
value.hashCode();
}
@Test
public void whenCallingObjectsHashOnStrings_thenSameHashCodeReturned() {
String strOne = "one";
String strTwo = "two";
String strOne2 = "one";
String strTwo2 = "two";
int hashCode1 = Objects.hash(strOne, strTwo);
int hashCode2 = Objects.hash(strOne2, strTwo2);
assertEquals(hashCode1, hashCode2);
}
@Test
public void whenCallingObjectsHashOnSingleString_thenDifferentHashcodeFromObjectsHashCodeCallReturned() {
String testString = "test string";
int hashCode1 = Objects.hash(testString);
int hashCode2 = Objects.hashCode(testString);
assertNotEquals(hashCode1, hashCode2);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.hash;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class PlayerUnitTest {
@Test
public void whenCallingHashCodeOnIdenticalValue_thenSameHashCodeReturned() {
Player player = new Player("Eduardo", "Rodriguez", "Pitcher");
Player indenticalPlayer = new Player("Eduardo", "Rodriguez", "Pitcher");
int hashCode1 = player.hashCode();
int hashCode2 = player.hashCode();
int hashCode3 = indenticalPlayer.hashCode();
assertEquals(hashCode1, hashCode2);
assertEquals(hashCode1, hashCode3);
}
@Test
public void whenCallingHashCodeAndArraysHashCode_thenSameHashCodeReturned() {
Player player = new Player("Bobby", "Dalbec", "First Base");
int hashcode1 = player.hashCode();
String[] playerInfo = { "Bobby", "Dalbec", "First Base" };
int hashcode2 = Arrays.hashCode(playerInfo);
assertEquals(hashcode1, hashcode2);
}
}
@@ -0,0 +1,42 @@
package com.baeldung.interfacevsabstractclass;
public class Car extends Vehicle {
public Car(String vechicleName) {
super(vechicleName);
}
public Car(String vechicleName, String vehicleModel) {
super(vechicleName, vehicleModel);
}
public Car(String vechicleName, String vehicleModel, Long makeYear) {
super(vechicleName, vehicleModel, makeYear);
}
@Override
protected void start() {
// code implementation details on starting a car.
}
@Override
protected void stop() {
// code implementation details on stopping a car.
}
@Override
protected void drive() {
// code implementation details on start driving a car.
}
@Override
protected void changeGear() {
// code implementation details on changing the car gear.
}
@Override
protected void reverse() {
// code implementation details on reverse driving a car.
}
}
@@ -0,0 +1,12 @@
package com.baeldung.interfacevsabstractclass;
import java.io.File;
public class ImageSender implements Sender {
@Override
public void send(File fileToBeSent) {
// image sending implementation code.
}
}
@@ -0,0 +1,8 @@
package com.baeldung.interfacevsabstractclass;
import java.io.File;
public interface Sender {
void send(File fileToBeSent);
}
@@ -0,0 +1,57 @@
package com.baeldung.interfacevsabstractclass;
public abstract class Vehicle {
private String vehicleName;
private String vehicleModel;
private Long makeYear;
public Vehicle(String vehicleName) {
this.vehicleName = vehicleName;
}
public Vehicle(String vehicleName, String vehicleModel) {
this(vehicleName);
this.vehicleModel = vehicleModel;
}
public Vehicle(String vechicleName, String vehicleModel, Long makeYear) {
this(vechicleName, vehicleModel);
this.makeYear = makeYear;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getVehicleModel() {
return vehicleModel;
}
public void setVehicleModel(String vehicleModel) {
this.vehicleModel = vehicleModel;
}
public Long getMakeYear() {
return makeYear;
}
public void setMakeYear(Long makeYear) {
this.makeYear = makeYear;
}
protected abstract void start();
protected abstract void stop();
protected abstract void drive();
protected abstract void changeGear();
protected abstract void reverse();
}
@@ -0,0 +1,12 @@
package com.baeldung.interfacevsabstractclass;
import java.io.File;
public class VideoSender implements Sender {
@Override
public void send(File fileToBeSent) {
// video sending implementation code
}
}
@@ -0,0 +1,23 @@
package com.baeldung.interfacevsabstractclass;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.baeldung.interfacevsabstractclass.ImageSender;
import com.baeldung.interfacevsabstractclass.Sender;
import java.io.File;
class SenderUnitTest {
public final static String IMAGE_FILE_PATH = "/sample_image_file_path/photo.jpg";
@Test
void givenImageUploaded_whenButtonClicked_thenSendImage() {
File imageFile = new File(IMAGE_FILE_PATH);
Sender sender = new ImageSender();
sender.send(imageFile);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.interfacevsabstractclass;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.baeldung.interfacevsabstractclass.Car;
import com.baeldung.interfacevsabstractclass.Vehicle;
class VehicleUnitTest {
@Test
void givenVehicle_whenNeedToDrive_thenStart() {
Vehicle car = new Car("BMW");
car.start();
car.drive();
car.changeGear();
car.stop();
}
}
@@ -17,9 +17,9 @@ import static org.junit.Assert.assertTrue;
public class FileDownloadIntegrationTest {
static String FILE_URL = "http://ovh.net/files/1Mio.dat";
static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson+by+Baeldung.pdf";
static String FILE_NAME = "file.dat";
static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116";
static String FILE_MD5_HASH = "c959feb066b37f5c4f0e0f45bbbb4f86";
@Test
public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException {
@@ -27,6 +27,17 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
<scope>test</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
@@ -44,11 +55,30 @@
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<lombok.version>1.18.20</lombok.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<jmh.version>1.29</jmh.version>
</properties>
</project>
@@ -0,0 +1,9 @@
package com.baeldung.streams.parallel;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.streams.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class DifferentSourceSplitting {
private static final List<Integer> arrayListOfNumbers = new ArrayList<>();
private static final List<Integer> linkedListOfNumbers = new LinkedList<>();
static {
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
arrayListOfNumbers.add(i);
linkedListOfNumbers.add(i);
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void differentSourceArrayListSequential() {
arrayListOfNumbers.stream().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void differentSourceArrayListParallel() {
arrayListOfNumbers.parallelStream().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void differentSourceLinkedListSequential() {
linkedListOfNumbers.stream().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void differentSourceLinkedListParallel() {
linkedListOfNumbers.parallelStream().reduce(0, Integer::sum);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.streams.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class MemoryLocalityCosts {
private static final int[] intArray = new int[1_000_000];
private static final Integer[] integerArray = new Integer[1_000_000];
static {
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
intArray[i-1] = i;
integerArray[i-1] = i;
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntArraySequential() {
Arrays.stream(intArray).reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntArrayParallel() {
Arrays.stream(intArray).parallel().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntegerArraySequential() {
Arrays.stream(integerArray).reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void localityIntegerArrayParallel() {
Arrays.stream(integerArray).parallel().reduce(0, Integer::sum);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.streams.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class MergingCosts {
private static final List<Integer> arrayListOfNumbers = new ArrayList<>();
static {
IntStream.rangeClosed(1, 1_000_000).forEach(i -> {
arrayListOfNumbers.add(i);
});
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void mergingCostsSumSequential() {
arrayListOfNumbers.stream().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void mergingCostsSumParallel() {
arrayListOfNumbers.stream().parallel().reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void mergingCostsGroupingSequential() {
arrayListOfNumbers.stream().collect(Collectors.toSet());
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void mergingCostsGroupingParallel() {
arrayListOfNumbers.stream().parallel().collect(Collectors.toSet());
}
}
@@ -0,0 +1,15 @@
package com.baeldung.streams.parallel;
import java.util.Arrays;
import java.util.List;
public class ParallelStream {
public static void main(String[] args) {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
listOfNumbers.parallelStream().forEach(number ->
System.out.println(number + " " + Thread.currentThread().getName())
);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.streams.parallel;
import java.util.Arrays;
import java.util.List;
public class SequentialStream {
public static void main(String[] args) {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
listOfNumbers.stream().forEach(number ->
System.out.println(number + " " + Thread.currentThread().getName())
);
}
}
@@ -0,0 +1,27 @@
package com.baeldung.streams.parallel;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
public class SplittingCosts {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void sourceSplittingIntStreamSequential() {
IntStream.rangeClosed(1, 100).reduce(0, Integer::sum);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void sourceSplittingIntStreamParallel() {
IntStream.rangeClosed(1, 100).parallel().reduce(0, Integer::sum);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.streams.parallel;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import static org.assertj.core.api.Assertions.assertThat;
class ForkJoinUnitTest {
@Test
void givenSequentialStreamOfNumbers_whenReducingSumWithIdentityFive_thenResultIsCorrect() {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
int sum = listOfNumbers.stream().reduce(5, Integer::sum);
assertThat(sum).isEqualTo(15);
}
@Test
void givenParallelStreamOfNumbers_whenReducingSumWithIdentityFive_thenResultIsNotCorrect() {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum);
assertThat(sum).isNotEqualTo(15);
}
@Test
void givenParallelStreamOfNumbers_whenReducingSumWithIdentityZero_thenResultIsCorrect() {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
int sum = listOfNumbers.parallelStream().reduce(0, Integer::sum) + 5;
assertThat(sum).isEqualTo(15);
}
@Test
public void givenParallelStreamOfNumbers_whenUsingCustomThreadPool_thenResultIsCorrect()
throws InterruptedException, ExecutionException {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
ForkJoinPool customThreadPool = new ForkJoinPool(4);
int sum = customThreadPool.submit(
() -> listOfNumbers.parallelStream().reduce(0, Integer::sum)).get();
customThreadPool.shutdown();
assertThat(sum).isEqualTo(10);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.splitkeepdelimiters;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import com.google.common.base.Splitter;
public class SplitAndKeepDelimitersUnitTest {
private final String positivelookAheadRegex = "((?=@))";
private final String positivelookBehindRegex = "((?<=@))";
private final String positivelookAroundRegex = "((?=@)|(?<=@))";
private final String positiveLookAroundMultiDelimiterRegex = "((?=:|#|@)|(?<=:|#|@))";
private String text = "Hello@World@This@Is@A@Java@Program";
private String textMixed = "@HelloWorld@This:Is@A#Java#Program";
private String textMixed2 = "pg@no;10@hello;world@this;is@a#10words;Java#Program";
@Test
public void givenString_splitAndKeepDelimiters_using_javaLangString() {
assertThat(text.split(positivelookAheadRegex)).containsExactly("Hello", "@World", "@This", "@Is", "@A", "@Java", "@Program");
assertThat(text.split(positivelookBehindRegex)).containsExactly("Hello@", "World@", "This@", "Is@", "A@", "Java@", "Program");
assertThat(text.split(positivelookAroundRegex)).containsExactly("Hello", "@", "World", "@", "This", "@", "Is", "@", "A", "@", "Java", "@", "Program");
assertThat(textMixed.split(positiveLookAroundMultiDelimiterRegex)).containsExactly("@", "HelloWorld", "@", "This", ":", "Is", "@", "A", "#", "Java", "#", "Program");
}
@Test
public void givenString_splitAndKeepDelimiters_using_ApacheCommonsLang3StringUtils() {
assertThat(StringUtils.splitByCharacterType(textMixed2)).containsExactly("pg", "@", "no", ";", "10", "@", "hello", ";", "world", "@", "this", ";", "is", "@", "a", "#", "10", "words", ";", "J", "ava", "#", "P", "rogram");
}
@Test
public void givenString_splitAndKeepDelimiters_using_GuavaSplitter() {
assertThat(Splitter.onPattern(positivelookAroundRegex)
.splitToList(text)).containsExactly("Hello", "@", "World", "@", "This", "@", "Is", "@", "A", "@", "Java", "@", "Program");
assertThat(Splitter.on(Pattern.compile(positivelookAroundRegex))
.splitToList(text)).containsExactly("Hello", "@", "World", "@", "This", "@", "Is", "@", "A", "@", "Java", "@", "Program");
assertThat(Splitter.onPattern(positiveLookAroundMultiDelimiterRegex)
.splitToList(textMixed)).containsExactly("@", "HelloWorld", "@", "This", ":", "Is", "@", "A", "#", "Java", "#", "Program");
assertThat(Splitter.on(Pattern.compile(positiveLookAroundMultiDelimiterRegex))
.splitToList(textMixed)).containsExactly("@", "HelloWorld", "@", "This", ":", "Is", "@", "A", "#", "Java", "#", "Program");
}
}
@@ -1,18 +1,17 @@
package com.baeldung.javaxval.bigdecimal;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import com.baeldung.javaxval.LocaleAwareUnitTest;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class InvoiceUnitTest extends LocaleAwareUnitTest {
private static Validator validator;
@@ -24,41 +23,67 @@ public class InvoiceUnitTest extends LocaleAwareUnitTest {
}
@Test
public void whenPriceIntegerDigitLessThanThreeWithDecimalValue_thenShouldGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased");
public void whenLessThanThreeIntegerDigits_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("10.21"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations.size()).isEqualTo(1);
violations.forEach(action -> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
assertThat(violations).isEmpty();
}
@Test
public void whenPriceIntegerDigitLessThanThreeWithIntegerValue_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal(10), "Book purchased");
public void whenThreeIntegerDigits_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("102.21"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations.size()).isEqualTo(0);
assertThat(violations).isEmpty();
}
@Test
public void whenPriceIntegerDigitGreaterThanThree_thenShouldGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased");
public void whenMoreThanThreeIntegerDigits_thenShouldGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("1021.21"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations.size()).isEqualTo(1);
violations.forEach(action -> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)"));
assertThat(violations).hasSize(1);
assertThat(violations)
.extracting("message")
.containsOnly("numeric value out of bounds (<3 digits>.<2 digits> expected)");
}
@Test
public void whenLessThanTwoFractionDigits_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("99.9"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations).isEmpty();
}
@Test
public void whenTwoFractionDigits_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("99.99"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations).isEmpty();
}
@Test
public void whenMoreThanTwoFractionDigits_thenShouldGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal("99.999"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations).hasSize(1);
assertThat(violations)
.extracting("message")
.containsOnly("numeric value out of bounds (<3 digits>.<2 digits> expected)");
}
@Test
public void whenPriceIsZero_thenShouldGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased");
Invoice invoice = new Invoice(new BigDecimal("0.00"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations.size()).isEqualTo(1);
violations.forEach(action -> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0"));
assertThat(violations).hasSize(1);
assertThat(violations)
.extracting("message")
.containsOnly("must be greater than 0.0");
}
@Test
public void whenPriceIsGreaterThanZero_thenShouldNotGiveConstraintViolations() {
Invoice invoice = new Invoice(new BigDecimal(100.50), "Book purchased");
Invoice invoice = new Invoice(new BigDecimal("100.50"), "Book purchased");
Set<ConstraintViolation<Invoice>> violations = validator.validate(invoice);
assertThat(violations.size()).isEqualTo(0);
assertThat(violations).isEmpty();
}
}
+1
View File
@@ -16,3 +16,4 @@ If you get a valid response, then you're good to go.
- [Paging and Async Calls with the Kubernetes API](https://www.baeldung.com/java-kubernetes-paging-async)
- [Using Watch with the Kubernetes API](https://www.baeldung.com/java-kubernetes-watch)
- [Using Namespaces and Selectors With the Kubernetes Java API](https://www.baeldung.com/java-kubernetes-namespaces-selectors)
@@ -0,0 +1,58 @@
apiVersion: v1
kind: Namespace
metadata:
name: ns1
---
apiVersion: v1
kind: Namespace
metadata:
name: ns2
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpd
namespace: ns1
labels:
app: httpd
version: "1"
spec:
replicas: 3
selector:
matchLabels:
app: httpd
template:
metadata:
labels:
app: httpd
spec:
containers:
- name: main
image: httpd:alpine
ports:
- containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpd
namespace: ns2
labels:
app: httpd
version: "2"
foo: bar
spec:
replicas: 3
selector:
matchLabels:
app: httpd
template:
metadata:
labels:
app: httpd
spec:
containers:
- name: main
image: httpd:alpine
ports:
- containerPort: 80
@@ -0,0 +1,68 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.Config;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* @author Philippe
*
*/
public class ListPodsWithFieldSelectors {
private static final Logger log = LoggerFactory.getLogger(ListPodsWithFieldSelectors.class);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient newClient = client.getHttpClient()
.newBuilder()
.addInterceptor(interceptor)
.readTimeout(0, TimeUnit.SECONDS)
.build();
client.setHttpClient(newClient);
CoreV1Api api = new CoreV1Api(client);
String fs = createSelector(args);
V1PodList items = api.listPodForAllNamespaces(null, null, fs, null, null, null, null, null, 10, false);
items.getItems()
.stream()
.map((pod) -> pod.getMetadata().getName() )
.forEach((name) -> System.out.println("name=" + name));
}
private static String createSelector(String[] args) {
StringBuilder b = new StringBuilder();
for( int i = 0 ; i < args.length; i++ ) {
if( b.length() > 0 ) {
b.append(',');
}
b.append(args[i]);
}
return b.toString();
}
}
@@ -0,0 +1,68 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.Config;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* @author Philippe
*
*/
public class ListPodsWithLabelSelectors {
private static final Logger log = LoggerFactory.getLogger(ListPodsWithLabelSelectors.class);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient newClient = client.getHttpClient()
.newBuilder()
.addInterceptor(interceptor)
.readTimeout(0, TimeUnit.SECONDS)
.build();
client.setHttpClient(newClient);
CoreV1Api api = new CoreV1Api(client);
String selector = createSelector(args);
V1PodList items = api.listPodForAllNamespaces(null, null, null, selector, null, null, null, null, 10, false);
items.getItems()
.stream()
.map((pod) -> pod.getMetadata().getName() )
.forEach((name) -> System.out.println("name=" + name));
}
private static String createSelector(String[] args) {
StringBuilder b = new StringBuilder();
for( int i = 0 ; i < args.length; i++ ) {
if( b.length() > 0 ) {
b.append(',');
}
b.append(args[i]);
}
return b.toString();
}
}
@@ -0,0 +1,52 @@
/**
*
*/
package com.baeldung.kubernetes.intro;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.Config;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* @author Philippe
*
*/
public class ListPodsWithNamespaces {
private static final Logger log = LoggerFactory.getLogger(ListPodsWithNamespaces.class);
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ApiClient client = Config.defaultClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message));
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient newClient = client.getHttpClient()
.newBuilder()
.addInterceptor(interceptor)
.readTimeout(0, TimeUnit.SECONDS)
.build();
client.setHttpClient(newClient);
CoreV1Api api = new CoreV1Api(client);
String namespace = "ns1";
V1PodList items = api.listNamespacedPod(namespace,null, null, null, null, null, null, null, null, 10, false);
items.getItems()
.stream()
.map((pod) -> pod.getMetadata().getName() )
.forEach((name) -> System.out.println("name=" + name));
}
}

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