Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-9467
This commit is contained in:
commit
510fe26236
|
@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv
|
||||||
**/dist
|
**/dist
|
||||||
**/tmp
|
**/tmp
|
||||||
**/out-tsc
|
**/out-tsc
|
||||||
|
**/nbproject/
|
||||||
|
**/nb-configuration.xml
|
|
@ -21,3 +21,8 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
|
||||||
Building the project
|
Building the project
|
||||||
====================
|
====================
|
||||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||||
|
|
||||||
|
|
||||||
|
Building a single module
|
||||||
|
====================
|
||||||
|
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
|
||||||
|
|
|
@ -28,3 +28,6 @@
|
||||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||||
|
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||||
|
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||||
|
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||||
|
|
|
@ -17,6 +17,11 @@
|
||||||
<artifactId>commons-math3</artifactId>
|
<artifactId>commons-math3</artifactId>
|
||||||
<version>${commons-math3.version}</version>
|
<version>${commons-math3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
|
@ -85,6 +90,7 @@
|
||||||
<io.jenetics.version>3.7.0</io.jenetics.version>
|
<io.jenetics.version>3.7.0</io.jenetics.version>
|
||||||
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
|
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
|
||||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
|
<commons-codec.version>1.11</commons-codec.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,110 @@
|
||||||
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.DecoderException;
|
||||||
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
|
||||||
|
import com.google.common.io.BaseEncoding;
|
||||||
|
|
||||||
|
public class HexStringConverter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a byte Array from String of hexadecimal digits using Character conversion
|
||||||
|
* @param hexString - Hexadecimal digits as String
|
||||||
|
* @return Desired byte Array
|
||||||
|
*/
|
||||||
|
public byte[] decodeHexString(String hexString) {
|
||||||
|
if (hexString.length() % 2 == 1) {
|
||||||
|
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
|
||||||
|
}
|
||||||
|
byte[] bytes = new byte[hexString.length() / 2];
|
||||||
|
|
||||||
|
for (int i = 0; i < hexString.length(); i += 2) {
|
||||||
|
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a String of hexadecimal digits from a byte Array using Character conversion
|
||||||
|
* @param byteArray - The byte Array
|
||||||
|
* @return Desired String of hexadecimal digits in lower case
|
||||||
|
*/
|
||||||
|
public String encodeHexString(byte[] byteArray) {
|
||||||
|
StringBuffer hexStringBuffer = new StringBuffer();
|
||||||
|
for (int i = 0; i < byteArray.length; i++) {
|
||||||
|
hexStringBuffer.append(byteToHex(byteArray[i]));
|
||||||
|
}
|
||||||
|
return hexStringBuffer.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String byteToHex(byte num) {
|
||||||
|
char[] hexDigits = new char[2];
|
||||||
|
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
|
||||||
|
hexDigits[1] = Character.forDigit((num & 0xF), 16);
|
||||||
|
return new String(hexDigits);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte hexToByte(String hexString) {
|
||||||
|
int firstDigit = toDigit(hexString.charAt(0));
|
||||||
|
int secondDigit = toDigit(hexString.charAt(1));
|
||||||
|
return (byte) ((firstDigit << 4) + secondDigit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int toDigit(char hexChar) {
|
||||||
|
int digit = Character.digit(hexChar, 16);
|
||||||
|
if(digit == -1) {
|
||||||
|
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
|
||||||
|
}
|
||||||
|
return digit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingBigIntegerToString(byte[] bytes) {
|
||||||
|
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||||
|
return bigInteger.toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
|
||||||
|
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||||
|
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingBigInteger(String hexString) {
|
||||||
|
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
|
||||||
|
if (byteArray[0] == 0) {
|
||||||
|
byte[] output = new byte[byteArray.length - 1];
|
||||||
|
System.arraycopy(byteArray, 1, output, 0, output.length);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
return byteArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingDataTypeConverter(byte[] bytes) {
|
||||||
|
return DatatypeConverter.printHexBinary(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingDataTypeConverter(String hexString) {
|
||||||
|
return DatatypeConverter.parseHexBinary(hexString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
|
||||||
|
return Hex.encodeHexString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
|
||||||
|
return Hex.decodeHex(hexString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingGuava(byte[] bytes) {
|
||||||
|
return BaseEncoding.base16()
|
||||||
|
.encode(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingGuava(String hexString) {
|
||||||
|
return BaseEncoding.base16()
|
||||||
|
.decode(hexString.toUpperCase());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,127 @@
|
||||||
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.DecoderException;
|
||||||
|
import org.hamcrest.text.IsEqualIgnoringCase;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.conversion.HexStringConverter;
|
||||||
|
|
||||||
|
public class ByteArrayConverterUnitTest {
|
||||||
|
|
||||||
|
private HexStringConverter hexStringConverter;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
hexStringConverter = new HexStringConverter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
if(hexString.charAt(0) == '0') {
|
||||||
|
hexString = hexString.substring(1);
|
||||||
|
}
|
||||||
|
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeHexString(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeHexString(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=IllegalArgumentException.class)
|
||||||
|
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
|
||||||
|
hexStringConverter.hexToByte("fg");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingGuava() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingGuava(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingGuava() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getSampleHexString() {
|
||||||
|
return "0af50c0e2d10";
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] getSampleBytes() {
|
||||||
|
return new byte[] { 10, -11, 12, 14, 45, 16 };
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -9,4 +9,4 @@
|
||||||
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
|
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
|
||||||
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
|
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
|
||||||
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
|
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
|
||||||
|
- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java)
|
||||||
|
|
|
@ -1,46 +0,0 @@
|
||||||
package com.baeldung.internationalization;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.ZoneId;
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
import java.time.format.FormatStyle;
|
|
||||||
import java.util.Locale;
|
|
||||||
import java.util.TimeZone;
|
|
||||||
|
|
||||||
public class DateTimeFormatterUnitTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
|
|
||||||
Locale.setDefault(Locale.US);
|
|
||||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
|
||||||
String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
|
|
||||||
|
|
||||||
DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
|
|
||||||
DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
|
|
||||||
DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
|
|
||||||
|
|
||||||
Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
|
|
||||||
Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
|
|
||||||
Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
|
|
||||||
Locale.setDefault(Locale.US);
|
|
||||||
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
|
||||||
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
|
||||||
|
|
||||||
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
|
||||||
DateTimeFormatter frLocalizedFormatter =
|
|
||||||
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
|
||||||
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
|
||||||
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
|
||||||
|
|
||||||
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
|
||||||
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -26,3 +26,4 @@
|
||||||
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
|
||||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
||||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||||
|
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||||
|
|
|
@ -52,3 +52,6 @@
|
||||||
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
|
||||||
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
|
- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
|
||||||
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
|
||||||
|
- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
|
||||||
|
- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
|
||||||
|
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<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">
|
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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>core-java-collections</artifactId>
|
<artifactId>core-java-collections</artifactId>
|
||||||
<version>0.1.0-SNAPSHOT</version>
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
@ -68,15 +67,14 @@
|
||||||
<artifactId>commons-exec</artifactId>
|
<artifactId>commons-exec</artifactId>
|
||||||
<version>1.3</version>
|
<version>1.3</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>one.util</groupId>
|
<groupId>one.util</groupId>
|
||||||
<artifactId>streamex</artifactId>
|
<artifactId>streamex</artifactId>
|
||||||
<version>0.6.5</version>
|
<version>0.6.5</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
<openjdk.jmh.version>1.19</openjdk.jmh.version>
|
||||||
<junit.platform.version>1.2.0</junit.platform.version>
|
<junit.platform.version>1.2.0</junit.platform.version>
|
||||||
|
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.convertcollectiontoarraylist;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This POJO is the element type of our collection. It has a deepCopy() method.
|
||||||
|
*
|
||||||
|
* @author chris
|
||||||
|
*/
|
||||||
|
public class Foo {
|
||||||
|
|
||||||
|
private int id;
|
||||||
|
private String name;
|
||||||
|
private Foo parent;
|
||||||
|
|
||||||
|
public Foo() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Foo(int id, String name, Foo parent) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.parent = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Foo getParent() {
|
||||||
|
return parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setParent(Foo parent) {
|
||||||
|
this.parent = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Foo deepCopy() {
|
||||||
|
return new Foo(
|
||||||
|
this.id, this.name, this.parent != null ? this.parent.deepCopy() : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.enumset;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.EnumSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class EnumSets {
|
||||||
|
|
||||||
|
public enum Color {
|
||||||
|
RED, YELLOW, GREEN, BLUE, BLACK, WHITE
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
EnumSet<Color> allColors = EnumSet.allOf(Color.class);
|
||||||
|
System.out.println(allColors);
|
||||||
|
|
||||||
|
EnumSet<Color> noColors = EnumSet.noneOf(Color.class);
|
||||||
|
System.out.println(noColors);
|
||||||
|
|
||||||
|
EnumSet<Color> blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE);
|
||||||
|
System.out.println(blackAndWhite);
|
||||||
|
|
||||||
|
EnumSet<Color> noBlackOrWhite = EnumSet.complementOf(blackAndWhite);
|
||||||
|
System.out.println(noBlackOrWhite);
|
||||||
|
|
||||||
|
EnumSet<Color> range = EnumSet.range(Color.YELLOW, Color.BLUE);
|
||||||
|
System.out.println(range);
|
||||||
|
|
||||||
|
EnumSet<Color> blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE));
|
||||||
|
System.out.println(blackAndWhiteCopy);
|
||||||
|
|
||||||
|
List<Color> colorsList = new ArrayList<>();
|
||||||
|
colorsList.add(Color.RED);
|
||||||
|
EnumSet<Color> listCopy = EnumSet.copyOf(colorsList);
|
||||||
|
System.out.println(listCopy);
|
||||||
|
|
||||||
|
EnumSet<Color> set = EnumSet.noneOf(Color.class);
|
||||||
|
set.add(Color.RED);
|
||||||
|
set.add(Color.YELLOW);
|
||||||
|
set.contains(Color.RED);
|
||||||
|
set.forEach(System.out::println);
|
||||||
|
set.remove(Color.RED);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.synchronizedcollections.application;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
private static final Logger LOGGER = Logger.getLogger(Application.class.getName());
|
||||||
|
|
||||||
|
public static void main(String[] args) throws InterruptedException {
|
||||||
|
List<Integer> syncCollection = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||||
|
synchronized (syncCollection) {
|
||||||
|
syncCollection.forEach((e) -> {LOGGER.info(e.toString());});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,148 @@
|
||||||
|
package com.baeldung.convertcollectiontoarraylist;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import static java.util.stream.Collectors.toCollection;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author chris
|
||||||
|
*/
|
||||||
|
public class FooUnitTest {
|
||||||
|
private static Collection<Foo> srcCollection = new HashSet<>();
|
||||||
|
|
||||||
|
public FooUnitTest() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpClass() {
|
||||||
|
int i = 0;
|
||||||
|
Foo john = new Foo(i++, "John", null);
|
||||||
|
Foo mary = new Foo(i++, "Mary", null);
|
||||||
|
Foo sam = new Foo(i++, "Sam", john);
|
||||||
|
Foo alice = new Foo(i++, "Alice", john);
|
||||||
|
Foo buffy = new Foo(i++, "Buffy", sam);
|
||||||
|
srcCollection.add(john);
|
||||||
|
srcCollection.add(mary);
|
||||||
|
srcCollection.add(sam);
|
||||||
|
srcCollection.add(alice);
|
||||||
|
srcCollection.add(buffy);
|
||||||
|
|
||||||
|
// make sure the collection isn't sorted accidentally
|
||||||
|
assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section 3. Using the ArrayList Constructor
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingConstructor_thenVerifyShallowCopy() {
|
||||||
|
ArrayList<Foo> newList = new ArrayList<>(srcCollection);
|
||||||
|
verifyShallowCopy(srcCollection, newList);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section 4. Using the Streams API
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingStream_thenVerifyShallowCopy() {
|
||||||
|
ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new));
|
||||||
|
|
||||||
|
verifyShallowCopy(srcCollection, newList);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section 5. Deep Copy
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
|
||||||
|
ArrayList<Foo> newList = srcCollection.stream()
|
||||||
|
.map(foo -> foo.deepCopy())
|
||||||
|
.collect(toCollection(ArrayList::new));
|
||||||
|
|
||||||
|
verifyDeepCopy(srcCollection, newList);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Section 6. Controlling the List Order
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingSortedStream_thenVerifySortOrder() {
|
||||||
|
ArrayList<Foo> newList = srcCollection.stream()
|
||||||
|
.sorted(Comparator.comparing(Foo::getName))
|
||||||
|
.collect(toCollection(ArrayList::new));
|
||||||
|
|
||||||
|
assertTrue("ArrayList is not sorted by name", isSorted(newList));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the contents of the two collections are the same
|
||||||
|
* @param a
|
||||||
|
* @param b
|
||||||
|
*/
|
||||||
|
private void verifyShallowCopy(Collection a, Collection b) {
|
||||||
|
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||||
|
Iterator<Foo> iterA = a.iterator();
|
||||||
|
Iterator<Foo> iterB = b.iterator();
|
||||||
|
while (iterA.hasNext()) {
|
||||||
|
// use '==' to test instance identity
|
||||||
|
assertTrue("Foo instances differ!", iterA.next() == iterB.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the contents of the two collections are the same
|
||||||
|
* @param a
|
||||||
|
* @param b
|
||||||
|
*/
|
||||||
|
private void verifyDeepCopy(Collection a, Collection b) {
|
||||||
|
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||||
|
Iterator<Foo> iterA = a.iterator();
|
||||||
|
Iterator<Foo> iterB = b.iterator();
|
||||||
|
while (iterA.hasNext()) {
|
||||||
|
Foo nextA = iterA.next();
|
||||||
|
Foo nextB = iterB.next();
|
||||||
|
// should not be same instance
|
||||||
|
assertFalse("Foo instances are the same!", nextA == nextB);
|
||||||
|
// but should have same content
|
||||||
|
assertFalse("Foo instances have different content!", fooDiff(nextA, nextB));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return true if the contents of a and b differ. Test parent recursively
|
||||||
|
* @param a
|
||||||
|
* @param b
|
||||||
|
* @return False if the two items are the same
|
||||||
|
*/
|
||||||
|
private boolean fooDiff(Foo a, Foo b) {
|
||||||
|
if (a != null && b != null) {
|
||||||
|
return a.getId() != b.getId()
|
||||||
|
|| !a.getName().equals(b.getName())
|
||||||
|
|| fooDiff(a.getParent(), b.getParent());
|
||||||
|
}
|
||||||
|
return !(a == null && b == null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param c collection of Foo
|
||||||
|
* @return true if the collection is sorted by name
|
||||||
|
*/
|
||||||
|
private static boolean isSorted(Collection<Foo> c) {
|
||||||
|
String prevName = null;
|
||||||
|
for (Foo foo : c) {
|
||||||
|
if (prevName == null || foo.getName().compareTo(prevName) > 0) {
|
||||||
|
prevName = foo.getName();
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,89 @@
|
||||||
|
package com.baeldung.findItems;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class FindItemsBasedOnOtherStreamUnitTest {
|
||||||
|
|
||||||
|
private List<Employee> employeeList = new ArrayList<Employee>();
|
||||||
|
|
||||||
|
private List<Department> departmentList = new ArrayList<Department>();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
|
||||||
|
Integer expectedId = 1002;
|
||||||
|
|
||||||
|
populate(employeeList, departmentList);
|
||||||
|
|
||||||
|
List<Employee> filteredList = employeeList.stream()
|
||||||
|
.filter(empl -> departmentList.stream()
|
||||||
|
.anyMatch(dept -> dept.getDepartment()
|
||||||
|
.equals("sales") && empl.getEmployeeId()
|
||||||
|
.equals(dept.getEmployeeId())))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(expectedId, filteredList.get(0)
|
||||||
|
.getEmployeeId());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void populate(List<Employee> EmplList, List<Department> deptList) {
|
||||||
|
Employee employee1 = new Employee(1001, "empl1");
|
||||||
|
Employee employee2 = new Employee(1002, "empl2");
|
||||||
|
Employee employee3 = new Employee(1003, "empl3");
|
||||||
|
|
||||||
|
Collections.addAll(EmplList, employee1, employee2, employee3);
|
||||||
|
|
||||||
|
Department department1 = new Department(1002, "sales");
|
||||||
|
Department department2 = new Department(1003, "marketing");
|
||||||
|
Department department3 = new Department(1004, "sales");
|
||||||
|
|
||||||
|
Collections.addAll(deptList, department1, department2, department3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Employee {
|
||||||
|
private Integer employeeId;
|
||||||
|
private String employeeName;
|
||||||
|
|
||||||
|
Employee(Integer employeeId, String employeeName) {
|
||||||
|
super();
|
||||||
|
this.employeeId = employeeId;
|
||||||
|
this.employeeName = employeeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer getEmployeeId() {
|
||||||
|
return employeeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmployeeName() {
|
||||||
|
return employeeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
class Department {
|
||||||
|
private Integer employeeId;
|
||||||
|
private String department;
|
||||||
|
|
||||||
|
Department(Integer employeeId, String department) {
|
||||||
|
super();
|
||||||
|
this.employeeId = employeeId;
|
||||||
|
this.department = department;
|
||||||
|
}
|
||||||
|
|
||||||
|
Integer getEmployeeId() {
|
||||||
|
return employeeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
String getDepartment() {
|
||||||
|
return department;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,44 +0,0 @@
|
||||||
package com.baeldung.java.map;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import org.apache.commons.collections4.MultiMap;
|
|
||||||
import org.apache.commons.collections4.MultiMapUtils;
|
|
||||||
import org.apache.commons.collections4.MultiValuedMap;
|
|
||||||
import org.apache.commons.collections4.map.MultiValueMap;
|
|
||||||
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
|
||||||
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.google.common.collect.ArrayListMultimap;
|
|
||||||
import com.google.common.collect.LinkedHashMultimap;
|
|
||||||
import com.google.common.collect.Multimap;
|
|
||||||
import com.google.common.collect.TreeMultimap;
|
|
||||||
|
|
||||||
|
|
||||||
public class KeyCheckTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
|
||||||
Map<String, String> map = Collections.singletonMap("key", "value");
|
|
||||||
|
|
||||||
assertTrue(map.containsKey("key"));
|
|
||||||
assertFalse(map.containsKey("missing"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenKeyHasNullValue_thenGetStillWorks() {
|
|
||||||
Map<String, String> map = Collections.singletonMap("nothing", null);
|
|
||||||
|
|
||||||
assertTrue(map.containsKey("nothing"));
|
|
||||||
assertNull(map.get("nothing"));
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.java.map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class KeyCheckUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
||||||
|
Map<String, String> map = Collections.singletonMap("key", "value");
|
||||||
|
|
||||||
|
assertTrue(map.containsKey("key"));
|
||||||
|
assertFalse(map.containsKey("missing"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenKeyHasNullValue_thenGetStillWorks() {
|
||||||
|
Map<String, String> map = Collections.singletonMap("nothing", null);
|
||||||
|
|
||||||
|
assertTrue(map.containsKey("nothing"));
|
||||||
|
assertNull(map.get("nothing"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SynchronizedCollectionUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedCollection_whenTwoThreadsAddElements_thenCorrectCollectionSize() throws InterruptedException {
|
||||||
|
Collection<Integer> syncCollection = Collections.synchronizedCollection(new ArrayList<>());
|
||||||
|
|
||||||
|
Runnable listOperations = () -> {
|
||||||
|
syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||||
|
};
|
||||||
|
Thread thread1 = new Thread(listOperations);
|
||||||
|
Thread thread2 = new Thread(listOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncCollection.size()).isEqualTo(12);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,51 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class SynchronizedListUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedList_whenTwoThreadsAddElements_thenCorrectListSize() throws InterruptedException {
|
||||||
|
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
|
||||||
|
Runnable listOperations = () -> {
|
||||||
|
syncList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
|
||||||
|
};
|
||||||
|
Thread thread1 = new Thread(listOperations);
|
||||||
|
Thread thread2 = new Thread(listOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncList.size()).isEqualTo(12);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringList_whenTwoThreadsIterateOnSynchronizedList_thenCorrectResult() throws InterruptedException {
|
||||||
|
List<String> syncCollection = Collections.synchronizedList(Arrays.asList("a", "b", "c"));
|
||||||
|
List<String> uppercasedCollection = new ArrayList<>();
|
||||||
|
|
||||||
|
Runnable listOperations = () -> {
|
||||||
|
synchronized (syncCollection) {
|
||||||
|
syncCollection.forEach((e) -> {
|
||||||
|
uppercasedCollection.add(e.toUpperCase());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Thread thread1 = new Thread(listOperations);
|
||||||
|
Thread thread2 = new Thread(listOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(uppercasedCollection.get(0)).isEqualTo("A");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class SynchronizedMapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedMap_whenTwoThreadsAddElements_thenCorrectMapSize() throws InterruptedException {
|
||||||
|
Map<Integer, String> syncMap = Collections.synchronizedMap(new HashMap<>());
|
||||||
|
|
||||||
|
Runnable mapOperations = () -> {
|
||||||
|
syncMap.put(1, "one");
|
||||||
|
syncMap.put(2, "two");
|
||||||
|
syncMap.put(3, "three");
|
||||||
|
|
||||||
|
};
|
||||||
|
Thread thread1 = new Thread(mapOperations);
|
||||||
|
Thread thread2 = new Thread(mapOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncMap.size()).isEqualTo(3);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class SynchronizedSetUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedSet_whenTwoThreadsAddElements_thenCorrectSetSize() throws InterruptedException {
|
||||||
|
Set<Integer> syncSet = Collections.synchronizedSet(new HashSet<>());
|
||||||
|
|
||||||
|
Runnable setOperations = () -> {syncSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
|
||||||
|
Thread thread1 = new Thread(setOperations);
|
||||||
|
Thread thread2 = new Thread(setOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncSet.size()).isEqualTo(6);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SynchronizedSortedMapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedSorteMap_whenTwoThreadsAddElements_thenCorrectSortedMapSize() throws InterruptedException {
|
||||||
|
Map<Integer, String> syncSortedMap = Collections.synchronizedSortedMap(new TreeMap<>());
|
||||||
|
|
||||||
|
Runnable sortedMapOperations = () -> {
|
||||||
|
syncSortedMap.put(1, "One");
|
||||||
|
syncSortedMap.put(2, "Two");
|
||||||
|
syncSortedMap.put(3, "Three");
|
||||||
|
};
|
||||||
|
Thread thread1 = new Thread(sortedMapOperations);
|
||||||
|
Thread thread2 = new Thread(sortedMapOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncSortedMap.size()).isEqualTo(3);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.synchronizedcollections.test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class SynchronizedSortedSetUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSynchronizedSortedSet_whenTwoThreadsAddElements_thenCorrectSortedSetSize() throws InterruptedException {
|
||||||
|
SortedSet<Integer> syncSortedSet = Collections.synchronizedSortedSet(new TreeSet<>());
|
||||||
|
|
||||||
|
Runnable sortedSetOperations = () -> {syncSortedSet.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));};
|
||||||
|
sortedSetOperations.run();
|
||||||
|
sortedSetOperations.run();
|
||||||
|
Thread thread1 = new Thread(sortedSetOperations);
|
||||||
|
Thread thread2 = new Thread(sortedSetOperations);
|
||||||
|
thread1.start();
|
||||||
|
thread2.start();
|
||||||
|
thread1.join();
|
||||||
|
thread2.join();
|
||||||
|
|
||||||
|
assertThat(syncSortedSet.size()).isEqualTo(6);
|
||||||
|
}
|
||||||
|
}
|
|
@ -29,3 +29,4 @@
|
||||||
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
|
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
|
||||||
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
|
||||||
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
|
||||||
|
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
|
||||||
|
|
|
@ -185,4 +185,24 @@ public class CompletableFutureLongRunningUnitTest {
|
||||||
assertEquals("Hello World", future.get());
|
assertEquals("Hello World", future.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException {
|
||||||
|
CompletableFuture<Integer> finalResult = compute().thenApply(s -> s + 1);
|
||||||
|
assertTrue(finalResult.get() == 11);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException {
|
||||||
|
CompletableFuture<Integer> finalResult = compute().thenCompose(this::computeAnother);
|
||||||
|
assertTrue(finalResult.get() == 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<Integer> compute(){
|
||||||
|
return CompletableFuture.supplyAsync(() -> 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
public CompletableFuture<Integer> computeAnother(Integer i){
|
||||||
|
return CompletableFuture.supplyAsync(() -> 10 + i);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
Test1
|
|
@ -0,0 +1 @@
|
||||||
|
Test2
|
|
@ -8,7 +8,7 @@ import java.io.IOException;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class OutputStreamExamplesTest {
|
public class OutputStreamExamplesUnitTest {
|
||||||
|
|
||||||
StringBuilder filePath = new StringBuilder();
|
StringBuilder filePath = new StringBuilder();
|
||||||
|
|
|
@ -150,3 +150,9 @@
|
||||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||||
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
|
||||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||||
|
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
|
||||||
|
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
|
||||||
|
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||||
|
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
|
||||||
|
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
|
||||||
|
- [Java Switch Statement](https://www.baeldung.com/java-switch)
|
||||||
|
|
|
@ -0,0 +1,159 @@
|
||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class ArrayReferenceGuide {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
declaration();
|
||||||
|
|
||||||
|
initialization();
|
||||||
|
|
||||||
|
access();
|
||||||
|
|
||||||
|
iterating();
|
||||||
|
|
||||||
|
varargs();
|
||||||
|
|
||||||
|
transformIntoList();
|
||||||
|
|
||||||
|
transformIntoStream();
|
||||||
|
|
||||||
|
sort();
|
||||||
|
|
||||||
|
search();
|
||||||
|
|
||||||
|
merge();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void declaration() {
|
||||||
|
int[] anArray;
|
||||||
|
int anotherArray[];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void initialization() {
|
||||||
|
int[] anArray = new int[10];
|
||||||
|
anArray[0] = 10;
|
||||||
|
anArray[5] = 4;
|
||||||
|
|
||||||
|
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void access() {
|
||||||
|
int[] anArray = new int[10];
|
||||||
|
anArray[0] = 10;
|
||||||
|
anArray[5] = 4;
|
||||||
|
|
||||||
|
System.out.println(anArray[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void iterating() {
|
||||||
|
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||||
|
for (int i = 0; i < anArray.length; i++) {
|
||||||
|
System.out.println(anArray[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int element : anArray) {
|
||||||
|
System.out.println(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void varargs() {
|
||||||
|
String[] groceries = new String[] {"Milk", "Tomato", "Chips"};
|
||||||
|
varargMethod(groceries);
|
||||||
|
varargMethod("Milk", "Tomato", "Chips");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void varargMethod(String... varargs) {
|
||||||
|
for (String element : varargs) {
|
||||||
|
System.out.println(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void transformIntoList() {
|
||||||
|
Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
|
||||||
|
|
||||||
|
// Naïve implementation
|
||||||
|
List<Integer> aList = new ArrayList<>(); // We create an empty list
|
||||||
|
for (int element : anArray) {
|
||||||
|
// We iterate over array's elements and add them to the list
|
||||||
|
aList.add(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pretty implementation
|
||||||
|
aList = Arrays.asList(anArray);
|
||||||
|
|
||||||
|
// Drawbacks
|
||||||
|
try {
|
||||||
|
aList.remove(0);
|
||||||
|
} catch (UnsupportedOperationException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
aList.add(6);
|
||||||
|
} catch (UnsupportedOperationException e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] anotherArray = new int[] {1, 2, 3, 4, 5};
|
||||||
|
// List<Integer> anotherList = Arrays.asList(anotherArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void transformIntoStream() {
|
||||||
|
int[] anArray = new int[] {1, 2, 3, 4, 5};
|
||||||
|
IntStream aStream = Arrays.stream(anArray);
|
||||||
|
|
||||||
|
Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5};
|
||||||
|
Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void sort() {
|
||||||
|
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||||
|
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}
|
||||||
|
|
||||||
|
Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
|
||||||
|
Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
|
||||||
|
|
||||||
|
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
|
||||||
|
Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void search() {
|
||||||
|
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||||
|
for (int i = 0; i < anArray.length; i++) {
|
||||||
|
if (anArray[i] == 4) {
|
||||||
|
System.out.println("Found at index " + i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Arrays.sort(anArray);
|
||||||
|
int index = Arrays.binarySearch(anArray, 4);
|
||||||
|
System.out.println("Found at index " + index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void merge() {
|
||||||
|
int[] anArray = new int[] {5, 2, 1, 4, 8};
|
||||||
|
int[] anotherArray = new int[] {10, 4, 9, 11, 2};
|
||||||
|
|
||||||
|
int[] resultArray = new int[anArray.length + anotherArray.length];
|
||||||
|
for (int i = 0; i < resultArray.length; i++) {
|
||||||
|
resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]);
|
||||||
|
}
|
||||||
|
for (int element : resultArray) {
|
||||||
|
System.out.println(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]));
|
||||||
|
for (int element : resultArray) {
|
||||||
|
System.out.println(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,11 +1,14 @@
|
||||||
package com.baeldung.classloader;
|
package com.baeldung.classloader;
|
||||||
|
|
||||||
import java.io.*;
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
public class CustomClassLoader extends ClassLoader {
|
public class CustomClassLoader extends ClassLoader {
|
||||||
|
|
||||||
|
@Override
|
||||||
public Class getClass(String name) throws ClassNotFoundException {
|
public Class findClass(String name) throws ClassNotFoundException {
|
||||||
byte[] b = loadClassFromFile(name);
|
byte[] b = loadClassFromFile(name);
|
||||||
return defineClass(name, b, 0, b.length);
|
return defineClass(name, b, 0, b.length);
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,136 @@
|
||||||
|
package com.baeldung.heapsort;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Heap<E extends Comparable<E>> {
|
||||||
|
|
||||||
|
private List<E> elements = new ArrayList<>();
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) {
|
||||||
|
Heap<E> heap = of(elements);
|
||||||
|
|
||||||
|
List<E> result = new ArrayList<>();
|
||||||
|
|
||||||
|
while (!heap.isEmpty()) {
|
||||||
|
result.add(heap.pop());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> Heap<E> of(E... elements) {
|
||||||
|
return of(Arrays.asList(elements));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
|
||||||
|
Heap<E> result = new Heap<>();
|
||||||
|
for (E element : elements) {
|
||||||
|
result.add(element);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(E e) {
|
||||||
|
elements.add(e);
|
||||||
|
int elementIndex = elements.size() - 1;
|
||||||
|
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
|
||||||
|
int parentIndex = parentIndex(elementIndex);
|
||||||
|
swap(elementIndex, parentIndex);
|
||||||
|
elementIndex = parentIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public E pop() {
|
||||||
|
if (isEmpty()) {
|
||||||
|
throw new IllegalStateException("You cannot pop from an empty heap");
|
||||||
|
}
|
||||||
|
|
||||||
|
E result = elementAt(0);
|
||||||
|
|
||||||
|
int lasElementIndex = elements.size() - 1;
|
||||||
|
swap(0, lasElementIndex);
|
||||||
|
elements.remove(lasElementIndex);
|
||||||
|
|
||||||
|
int elementIndex = 0;
|
||||||
|
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
|
||||||
|
int smallerChildIndex = smallerChildIndex(elementIndex);
|
||||||
|
swap(elementIndex, smallerChildIndex);
|
||||||
|
elementIndex = smallerChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return elements.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isRoot(int index) {
|
||||||
|
return index == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int smallerChildIndex(int index) {
|
||||||
|
int leftChildIndex = leftChildIndex(index);
|
||||||
|
int rightChildIndex = rightChildIndex(index);
|
||||||
|
|
||||||
|
if (!isValidIndex(rightChildIndex)) {
|
||||||
|
return leftChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
|
||||||
|
return leftChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rightChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isLeaf(int index) {
|
||||||
|
return !isValidIndex(leftChildIndex(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrectParent(int index) {
|
||||||
|
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrectChild(int index) {
|
||||||
|
return isCorrect(parentIndex(index), index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrect(int parentIndex, int childIndex) {
|
||||||
|
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isValidIndex(int index) {
|
||||||
|
return index < elements.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void swap(int index1, int index2) {
|
||||||
|
E element1 = elementAt(index1);
|
||||||
|
E element2 = elementAt(index2);
|
||||||
|
elements.set(index1, element2);
|
||||||
|
elements.set(index2, element1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private E elementAt(int index) {
|
||||||
|
return elements.get(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int parentIndex(int index) {
|
||||||
|
return (index - 1) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int leftChildIndex(int index) {
|
||||||
|
return 2 * index + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int rightChildIndex(int index) {
|
||||||
|
return 2 * index + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -11,7 +11,7 @@ public class CustomClassLoaderUnitTest {
|
||||||
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
|
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
|
||||||
|
|
||||||
CustomClassLoader customClassLoader = new CustomClassLoader();
|
CustomClassLoader customClassLoader = new CustomClassLoader();
|
||||||
Class<?> c = customClassLoader.getClass(PrintClassLoader.class.getName());
|
Class<?> c = customClassLoader.findClass(PrintClassLoader.class.getName());
|
||||||
|
|
||||||
Object ob = c.newInstance();
|
Object ob = c.newInstance();
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.baeldung.heapsort;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class HeapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
|
||||||
|
// given
|
||||||
|
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
|
||||||
|
|
||||||
|
// when
|
||||||
|
int head = heap.pop();
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(head).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
|
||||||
|
// given
|
||||||
|
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);
|
||||||
|
|
||||||
|
// when
|
||||||
|
List<Integer> sortedElements = Heap.sort(elements);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.modulo;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Java6Assertions.*;
|
||||||
|
|
||||||
|
public class ModuloUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenIntegerDivision_thenLosesRemainder(){
|
||||||
|
assertThat(11 / 4).isEqualTo(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDoubleDivision_thenKeepsRemainder(){
|
||||||
|
assertThat(11 / 4.0).isEqualTo(2.75);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenModulo_thenReturnsRemainder(){
|
||||||
|
assertThat(11 % 4).isEqualTo(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ArithmeticException.class)
|
||||||
|
public void whenDivisionByZero_thenArithmeticException(){
|
||||||
|
double result = 1 / 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ArithmeticException.class)
|
||||||
|
public void whenModuloByZero_thenArithmeticException(){
|
||||||
|
double result = 1 % 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
|
||||||
|
assertThat(3 % 2).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
|
||||||
|
assertThat(4 % 2).isEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
|
||||||
|
int QUEUE_CAPACITY= 10;
|
||||||
|
int[] circularQueue = new int[QUEUE_CAPACITY];
|
||||||
|
int itemsInserted = 0;
|
||||||
|
for (int value = 0; value < 1000; value++) {
|
||||||
|
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
|
||||||
|
circularQueue[writeIndex] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,11 +1,11 @@
|
||||||
package com.baeldung.nth.root.calculator;
|
package com.baeldung.nth.root.calculator;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
import org.mockito.runners.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
@RunWith(MockitoJUnitRunner.class)
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
public class NthRootCalculatorUnitTest {
|
public class NthRootCalculatorUnitTest {
|
||||||
|
|
|
@ -37,3 +37,5 @@
|
||||||
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
|
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
|
||||||
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
|
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
|
||||||
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
|
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
|
||||||
|
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
|
||||||
|
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.datastructures
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Example of how to use the {@link Node} class.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
val tree = Node(4)
|
||||||
|
val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
|
||||||
|
for (key in keys) {
|
||||||
|
tree.insert(key)
|
||||||
|
}
|
||||||
|
val node = tree.find(4)!!
|
||||||
|
println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
|
||||||
|
println("Delete node with key = 3")
|
||||||
|
node.delete(3)
|
||||||
|
print("Tree content after the node elimination: ")
|
||||||
|
println(tree.visit().joinToString { it.toString() })
|
||||||
|
}
|
|
@ -0,0 +1,167 @@
|
||||||
|
package com.baeldung.datastructures
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An ADT for a binary search tree.
|
||||||
|
* Note that this data type is neither immutable nor thread safe.
|
||||||
|
*/
|
||||||
|
class Node(
|
||||||
|
var key: Int,
|
||||||
|
var left: Node? = null,
|
||||||
|
var right: Node? = null) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a node with given value. If no such node exists, return null.
|
||||||
|
* @param value
|
||||||
|
*/
|
||||||
|
fun find(value: Int): Node? = when {
|
||||||
|
this.key > value -> left?.find(value)
|
||||||
|
this.key < value -> right?.find(value)
|
||||||
|
else -> this
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a given value into the tree.
|
||||||
|
* After insertion, the tree should contain a node with the given value.
|
||||||
|
* If the tree already contains the given value, nothing is performed.
|
||||||
|
* @param value
|
||||||
|
*/
|
||||||
|
fun insert(value: Int) {
|
||||||
|
if (value > this.key) {
|
||||||
|
if (this.right == null) {
|
||||||
|
this.right = Node(value)
|
||||||
|
} else {
|
||||||
|
this.right?.insert(value)
|
||||||
|
}
|
||||||
|
} else if (value < this.key) {
|
||||||
|
if (this.left == null) {
|
||||||
|
this.left = Node(value)
|
||||||
|
} else {
|
||||||
|
this.left?.insert(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
|
||||||
|
* @param value
|
||||||
|
*/
|
||||||
|
fun delete(value: Int) {
|
||||||
|
when {
|
||||||
|
value > key -> scan(value, this.right, this)
|
||||||
|
value < key -> scan(value, this.left, this)
|
||||||
|
else -> removeNode(this, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan the tree in the search of the given value.
|
||||||
|
* @param value
|
||||||
|
* @param node sub-tree that potentially might contain the sought value
|
||||||
|
* @param parent node's parent
|
||||||
|
*/
|
||||||
|
private fun scan(value: Int, node: Node?, parent: Node?) {
|
||||||
|
if (node == null) {
|
||||||
|
System.out.println("value " + value
|
||||||
|
+ " seems not present in the tree.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
value > node.key -> scan(value, node.right, node)
|
||||||
|
value < node.key -> scan(value, node.left, node)
|
||||||
|
value == node.key -> removeNode(node, parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the node.
|
||||||
|
*
|
||||||
|
* Removal process depends on how many children the node has.
|
||||||
|
*
|
||||||
|
* @param node node that is to be removed
|
||||||
|
* @param parent parent of the node to be removed
|
||||||
|
*/
|
||||||
|
private fun removeNode(node: Node, parent: Node?) {
|
||||||
|
node.left?.let { leftChild ->
|
||||||
|
run {
|
||||||
|
node.right?.let {
|
||||||
|
removeTwoChildNode(node)
|
||||||
|
} ?: removeSingleChildNode(node, leftChild)
|
||||||
|
}
|
||||||
|
} ?: run {
|
||||||
|
node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove the node without children.
|
||||||
|
* @param node
|
||||||
|
* @param parent
|
||||||
|
*/
|
||||||
|
private fun removeNoChildNode(node: Node, parent: Node?) {
|
||||||
|
parent?.let { p ->
|
||||||
|
if (node == p.left) {
|
||||||
|
p.left = null
|
||||||
|
} else if (node == p.right) {
|
||||||
|
p.right = null
|
||||||
|
}
|
||||||
|
} ?: throw IllegalStateException(
|
||||||
|
"Can not remove the root node without child nodes")
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a node that has two children.
|
||||||
|
*
|
||||||
|
* The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
|
||||||
|
* node that is to be deleted with that key.
|
||||||
|
*/
|
||||||
|
private fun removeTwoChildNode(node: Node) {
|
||||||
|
val leftChild = node.left!!
|
||||||
|
leftChild.right?.let {
|
||||||
|
val maxParent = findParentOfMaxChild(leftChild)
|
||||||
|
maxParent.right?.let {
|
||||||
|
node.key = it.key
|
||||||
|
maxParent.right = null
|
||||||
|
} ?: throw IllegalStateException("Node with max child must have the right child!")
|
||||||
|
|
||||||
|
} ?: run {
|
||||||
|
node.key = leftChild.key
|
||||||
|
node.left = leftChild.left
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a node whose right child contains the biggest value in the given sub-tree.
|
||||||
|
* Assume that the node n has a non-null right child.
|
||||||
|
*
|
||||||
|
* @param n
|
||||||
|
*/
|
||||||
|
private fun findParentOfMaxChild(n: Node): Node {
|
||||||
|
return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
|
||||||
|
?: throw IllegalArgumentException("Right child must be non-null")
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a parent that has only one child.
|
||||||
|
* Removal is effectively is just coping the data from the child parent to the parent parent.
|
||||||
|
* @param parent Node to be deleted. Assume that it has just one child
|
||||||
|
* @param child Assume it is a child of the parent
|
||||||
|
*/
|
||||||
|
private fun removeSingleChildNode(parent: Node, child: Node) {
|
||||||
|
parent.key = child.key
|
||||||
|
parent.left = child.left
|
||||||
|
parent.right = child.right
|
||||||
|
}
|
||||||
|
|
||||||
|
fun visit(): Array<Int> {
|
||||||
|
val a = left?.visit() ?: emptyArray()
|
||||||
|
val b = right?.visit() ?: emptyArray()
|
||||||
|
return a + arrayOf(key) + b
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.interfaces
|
||||||
|
|
||||||
|
interface BaseInterface {
|
||||||
|
fun someMethod(): String
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FirstChildInterface : BaseInterface {
|
||||||
|
override fun someMethod(): String {
|
||||||
|
return("Hello, from someMethod in FirstChildInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SecondChildInterface : BaseInterface {
|
||||||
|
override fun someMethod(): String {
|
||||||
|
return("Hello, from someMethod in SecondChildInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ChildClass : FirstChildInterface, SecondChildInterface {
|
||||||
|
override fun someMethod(): String {
|
||||||
|
return super<SecondChildInterface>.someMethod()
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.interfaces
|
||||||
|
|
||||||
|
interface MyInterface {
|
||||||
|
fun someMethod(): String
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyClass() : MyInterface {
|
||||||
|
override fun someMethod(): String {
|
||||||
|
return("Hello, World!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.interfaces
|
||||||
|
|
||||||
|
interface FirstInterface {
|
||||||
|
fun someMethod(): String
|
||||||
|
|
||||||
|
fun anotherMethod(): String {
|
||||||
|
return("Hello, from anotherMethod in FirstInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SecondInterface {
|
||||||
|
fun someMethod(): String {
|
||||||
|
return("Hello, from someMethod in SecondInterface")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun anotherMethod(): String {
|
||||||
|
return("Hello, from anotherMethod in SecondInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SomeClass: FirstInterface, SecondInterface {
|
||||||
|
override fun someMethod(): String {
|
||||||
|
return("Hello, from someMethod in SomeClass")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun anotherMethod(): String {
|
||||||
|
return("Hello, from anotherMethod in SomeClass")
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.interfaces
|
||||||
|
|
||||||
|
interface SimpleInterface {
|
||||||
|
val firstProp: String
|
||||||
|
val secondProp: String
|
||||||
|
get() = "Second Property"
|
||||||
|
fun firstMethod(): String
|
||||||
|
fun secondMethod(): String {
|
||||||
|
println("Hello, from: " + secondProp)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SimpleClass: SimpleInterface {
|
||||||
|
override val firstProp: String = "First Property"
|
||||||
|
override val secondProp: String
|
||||||
|
get() = "Second Property, Overridden!"
|
||||||
|
override fun firstMethod(): String {
|
||||||
|
return("Hello, from: " + firstProp)
|
||||||
|
}
|
||||||
|
override fun secondMethod(): String {
|
||||||
|
return("Hello, from: " + secondProp + firstProp)
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,319 @@
|
||||||
|
package com.baeldung.datastructures
|
||||||
|
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class NodeTest {
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for finding the node by value
|
||||||
|
* Partition the tests as follows:
|
||||||
|
* 1. tree depth: 0, 1, > 1
|
||||||
|
* 2. pivot depth location: not present, 0, 1, 2, > 2
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the node by value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. pivot depth location: not present
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenDepthZero_whenPivotNotPresent_thenNull() {
|
||||||
|
val n = Node(1)
|
||||||
|
assertNull(n.find(2))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the node by value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. pivot depth location: 0
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() {
|
||||||
|
val n = Node(1)
|
||||||
|
assertEquals(n, n.find(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the node by value
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. pivot depth location: not present
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenDepthOne_whenPivotNotPresent_thenNull() {
|
||||||
|
val n = Node(1, Node(0))
|
||||||
|
assertNull(n.find(2))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the node by value
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. pivot depth location: not present
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() {
|
||||||
|
val n = Node(1, Node(0))
|
||||||
|
assertEquals(n.left, n.find(0)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenDepthTwo_whenPivotAtDepth2_then_Success() {
|
||||||
|
val left = Node(1, Node(0), Node(2))
|
||||||
|
val right = Node(5, Node(4), Node(6))
|
||||||
|
val n = Node(3, left, right)
|
||||||
|
assertEquals(left.left, n.find(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for inserting a value
|
||||||
|
* Partition the test as follows:
|
||||||
|
* 1. tree depth: 0, 1, 2, > 2
|
||||||
|
* 2. depth to insert: 0, 1, > 1
|
||||||
|
* 3. is duplicate: no, yes
|
||||||
|
* 4. sub-tree: left, right
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: no
|
||||||
|
* 4. sub-tree: right
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() {
|
||||||
|
val n = Node(1)
|
||||||
|
n.insert(2)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(2, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
assertNull(n.left)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: no
|
||||||
|
* 4. sub-tree: right
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() {
|
||||||
|
val n = Node(1)
|
||||||
|
n.insert(0)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(0, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
assertNull(n.right)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: yes
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() {
|
||||||
|
val n = Node(1)
|
||||||
|
n.insert(1)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
assertNull(n.right)
|
||||||
|
assertNull(n.left)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for inserting a value
|
||||||
|
* Partition the test as follows:
|
||||||
|
* 1. tree depth: 0, 1, 2, > 2
|
||||||
|
* 2. depth to insert: 0, 1, > 1
|
||||||
|
* 3. is duplicate: no, yes
|
||||||
|
* 4. sub-tree: left, right
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: no
|
||||||
|
* 4. sub-tree: right
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() {
|
||||||
|
val n = Node(10, Node(3))
|
||||||
|
n.insert(15)
|
||||||
|
assertEquals(10, n.key)
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(15, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(3, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: no
|
||||||
|
* 4. sub-tree: left
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() {
|
||||||
|
val n = Node(10, null, Node(15))
|
||||||
|
n.insert(3)
|
||||||
|
assertEquals(10, n.key)
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(15, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(3, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for inserting a value
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. depth to insert: 1
|
||||||
|
* 3. is duplicate: yes
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() {
|
||||||
|
val n = Node(10, null, Node(15))
|
||||||
|
n.insert(15)
|
||||||
|
assertEquals(10, n.key)
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(15, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
assertNull(n.left)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for removal
|
||||||
|
* Partition the input as follows:
|
||||||
|
* 1. tree depth: 0, 1, 2, > 2
|
||||||
|
* 2. value to delete: absent, present
|
||||||
|
* 3. # child nodes: 0, 1, 2
|
||||||
|
*/
|
||||||
|
/**
|
||||||
|
* Test for removal value
|
||||||
|
* 1. tree depth: 0
|
||||||
|
* 2. value to delete: absent
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthZero_whenValueAbsent_thenNoChange() {
|
||||||
|
val n = Node(1)
|
||||||
|
n.delete(0)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
assertNull(n.left)
|
||||||
|
assertNull(n.right)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test for removal
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. value to delete: absent
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthOne_whenValueAbsent_thenNoChange() {
|
||||||
|
val n = Node(1, Node(0), Node(2))
|
||||||
|
n.delete(3)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
assertEquals(2, n.right!!.key)
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(0, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
with(n.right!!) {
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for removal
|
||||||
|
* 1. tree depth: 1
|
||||||
|
* 2. value to delete: present
|
||||||
|
* 3. # child nodes: 0
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() {
|
||||||
|
val n = Node(1, Node(0))
|
||||||
|
n.delete(0)
|
||||||
|
assertEquals(1, n.key)
|
||||||
|
assertNull(n.left)
|
||||||
|
assertNull(n.right)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test suit for removal
|
||||||
|
* 1. tree depth: 2
|
||||||
|
* 2. value to delete: present
|
||||||
|
* 3. # child nodes: 1
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() {
|
||||||
|
val n = Node(2, Node(0, null, Node(1)), Node(3))
|
||||||
|
n.delete(0)
|
||||||
|
assertEquals(2, n.key)
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(3, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(1, key)
|
||||||
|
assertNull(left)
|
||||||
|
assertNull(right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() {
|
||||||
|
val l = Node(2, Node(1), Node(5, Node(4), Node(6)))
|
||||||
|
val r = Node(10, Node(9), Node(11))
|
||||||
|
val n = Node(8, l, r)
|
||||||
|
n.delete(8)
|
||||||
|
assertEquals(6, n.key)
|
||||||
|
with(n.left!!) {
|
||||||
|
assertEquals(2, key)
|
||||||
|
assertEquals(1, left!!.key)
|
||||||
|
assertEquals(5, right!!.key)
|
||||||
|
assertEquals(4, right!!.left!!.key)
|
||||||
|
}
|
||||||
|
with(n.right!!) {
|
||||||
|
assertEquals(10, key)
|
||||||
|
assertEquals(9, left!!.key)
|
||||||
|
assertEquals(11, right!!.key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.interfaces
|
||||||
|
|
||||||
|
import org.junit.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class InterfaceExamplesUnitTest {
|
||||||
|
@Test
|
||||||
|
fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() {
|
||||||
|
val simpleClass = SimpleClass()
|
||||||
|
assertEquals("Hello, from: First Property", simpleClass.firstMethod())
|
||||||
|
assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||||
|
val someClass = SomeClass()
|
||||||
|
assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod())
|
||||||
|
assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() {
|
||||||
|
val childClass = ChildClass()
|
||||||
|
assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() {
|
||||||
|
val myClass = MyClass()
|
||||||
|
assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod())
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
plugins {
|
||||||
|
// Apply the java-library plugin to add support for Java Library
|
||||||
|
id 'java-library'
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
|
||||||
|
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
|
||||||
|
|
||||||
|
// Only necessary for JUnit 3 and 4 tests
|
||||||
|
testCompileOnly 'junit:junit:4.12'
|
||||||
|
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1'
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
jcenter()
|
||||||
|
}
|
||||||
|
|
||||||
|
test {
|
||||||
|
useJUnitPlatform {
|
||||||
|
includeTags 'fast'
|
||||||
|
excludeTags 'slow'
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.example;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CalculatorJUnit4Test {
|
||||||
|
@Test
|
||||||
|
public void testAdd() {
|
||||||
|
assertEquals(42, Integer.sum(19, 23));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.example;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Tag;
|
||||||
|
import org.junit.jupiter.api.Test;;
|
||||||
|
|
||||||
|
public class CalculatorJUnit5Test {
|
||||||
|
|
||||||
|
@Tag("fast")
|
||||||
|
@Test
|
||||||
|
public void testAdd() {
|
||||||
|
assertEquals(42, Integer.sum(19, 23));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tag("slow")
|
||||||
|
@Test
|
||||||
|
public void testAddMaxInteger() {
|
||||||
|
assertEquals(2147483646, Integer.sum(2147183646, 300000));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tag("fast")
|
||||||
|
@Test
|
||||||
|
public void testAddZero() {
|
||||||
|
assertEquals(21, Integer.sum(21, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Tag("fast")
|
||||||
|
@Test
|
||||||
|
public void testDivide() {
|
||||||
|
assertThrows(ArithmeticException.class, () -> {
|
||||||
|
Integer.divideUnsigned(42, 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
|
@ -5,6 +5,6 @@ include 'greeting-library'
|
||||||
include 'greeting-library-java'
|
include 'greeting-library-java'
|
||||||
include 'greeter'
|
include 'greeter'
|
||||||
include 'gradletaskdemo'
|
include 'gradletaskdemo'
|
||||||
|
include 'junit5'
|
||||||
|
|
||||||
println 'This will be executed during the initialization phase.'
|
println 'This will be executed during the initialization phase.'
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
|
@ -0,0 +1,20 @@
|
||||||
|
=========
|
||||||
|
|
||||||
|
## Guava and Hamcrest Cookbooks and Examples
|
||||||
|
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
||||||
|
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
||||||
|
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
||||||
|
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
||||||
|
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
||||||
|
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
||||||
|
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
||||||
|
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
||||||
|
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
||||||
|
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
||||||
|
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
||||||
|
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
||||||
|
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
||||||
|
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
|
@ -0,0 +1,66 @@
|
||||||
|
<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</groupId>
|
||||||
|
<artifactId>guava-collections</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>guava-collections</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- utils -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-collections4</artifactId>
|
||||||
|
<version>${commons-collections4.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.hamcrest</groupId>
|
||||||
|
<artifactId>java-hamcrest</artifactId>
|
||||||
|
<version>${java-hamcrest.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>guava</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- util -->
|
||||||
|
<guava.version>24.0-jre</guava.version>
|
||||||
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
|
|
||||||
|
<!-- testing -->
|
||||||
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<logger name="org.springframework" level="WARN" />
|
||||||
|
<logger name="org.springframework.transaction" level="WARN" />
|
||||||
|
|
||||||
|
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||||
|
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
|
@ -0,0 +1,13 @@
|
||||||
|
*.class
|
||||||
|
|
||||||
|
#folders#
|
||||||
|
/target
|
||||||
|
/neoDb*
|
||||||
|
/data
|
||||||
|
/src/main/webapp/WEB-INF/classes
|
||||||
|
*/META-INF/*
|
||||||
|
|
||||||
|
# Packaged files #
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.ear
|
|
@ -0,0 +1 @@
|
||||||
|
John Jane Adam Tom
|
|
@ -0,0 +1 @@
|
||||||
|
Hello world
|
|
@ -0,0 +1 @@
|
||||||
|
Test
|
|
@ -0,0 +1,4 @@
|
||||||
|
John
|
||||||
|
Jane
|
||||||
|
Adam
|
||||||
|
Tom
|
|
@ -0,0 +1 @@
|
||||||
|
Hello world
|
Binary file not shown.
|
@ -4,33 +4,19 @@
|
||||||
|
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
|
|
||||||
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
|
|
||||||
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
|
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
|
||||||
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
|
|
||||||
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
|
|
||||||
- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
|
|
||||||
- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
|
|
||||||
- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file)
|
- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file)
|
||||||
- [Guava – Lists](http://www.baeldung.com/guava-lists)
|
|
||||||
- [Guava – Sets](http://www.baeldung.com/guava-sets)
|
|
||||||
- [Guava – Maps](http://www.baeldung.com/guava-maps)
|
|
||||||
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
|
||||||
- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering)
|
- [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering)
|
||||||
- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions)
|
- [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions)
|
||||||
- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader)
|
- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader)
|
||||||
- [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer)
|
- [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer)
|
||||||
- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus)
|
- [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus)
|
||||||
- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap)
|
|
||||||
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
|
|
||||||
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
|
|
||||||
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
|
||||||
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
|
||||||
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)
|
||||||
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
|
|
||||||
- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
|
- [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math)
|
||||||
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
|
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
|
||||||
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
|
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
|
||||||
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
|
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
|
||||||
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
|
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)
|
||||||
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
|
|
||||||
|
|
|
@ -14,12 +14,6 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- utils -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.commons</groupId>
|
|
||||||
<artifactId>commons-collections4</artifactId>
|
|
||||||
<version>${commons-collections4.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
@ -56,7 +50,6 @@
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>24.0-jre</guava.version>
|
<guava.version>24.0-jre</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<commons-collections4.version>4.1</commons-collections4.version>
|
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
|
|
@ -16,3 +16,4 @@
|
||||||
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
|
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
|
||||||
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
|
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
|
||||||
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
|
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
|
||||||
|
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
|
||||||
|
|
|
@ -4,13 +4,23 @@ import javax.persistence.Entity;
|
||||||
import javax.persistence.GeneratedValue;
|
import javax.persistence.GeneratedValue;
|
||||||
import javax.persistence.GenerationType;
|
import javax.persistence.GenerationType;
|
||||||
import javax.persistence.Id;
|
import javax.persistence.Id;
|
||||||
import javax.persistence.SequenceGenerator;
|
|
||||||
|
import org.hibernate.annotations.GenericGenerator;
|
||||||
|
import org.hibernate.annotations.Parameter;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class User {
|
public class User {
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator")
|
@GeneratedValue(generator = "sequence-generator")
|
||||||
@SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4)
|
@GenericGenerator(
|
||||||
|
name = "sequence-generator",
|
||||||
|
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||||
|
parameters = {
|
||||||
|
@Parameter(name = "sequence_name", value = "user_sequence"),
|
||||||
|
@Parameter(name = "initial_value", value = "4"),
|
||||||
|
@Parameter(name = "increment_size", value = "1")
|
||||||
|
}
|
||||||
|
)
|
||||||
private long userId;
|
private long userId;
|
||||||
|
|
||||||
public long getUserId() {
|
public long getUserId() {
|
||||||
|
|
|
@ -80,7 +80,7 @@
|
||||||
<joda-time.version>2.10</joda-time.version>
|
<joda-time.version>2.10</joda-time.version>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
<maven.compiler.source>9</maven.compiler.source>
|
<maven.compiler.source>1.9</maven.compiler.source>
|
||||||
<maven.compiler.target>9</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -51,6 +51,15 @@ public class DateDiffUnitTest {
|
||||||
assertEquals(diff, 6);
|
assertEquals(diff, 6);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||||
|
LocalDateTime ldt = LocalDateTime.now();
|
||||||
|
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
||||||
|
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6);
|
||||||
|
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||||
|
assertEquals(diff, 6);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() {
|
||||||
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
|
||||||
|
|
|
@ -0,0 +1,158 @@
|
||||||
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.format.DateTimeParseException;
|
||||||
|
import java.time.format.FormatStyle;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
public class DateTimeFormatterUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
|
||||||
|
Locale.setDefault(Locale.US);
|
||||||
|
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||||
|
String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
|
||||||
|
|
||||||
|
DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
|
||||||
|
DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
|
||||||
|
DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
|
||||||
|
|
||||||
|
Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
|
||||||
|
Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
|
||||||
|
Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
|
||||||
|
Locale.setDefault(Locale.US);
|
||||||
|
LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
|
||||||
|
ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
|
||||||
|
|
||||||
|
DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
|
||||||
|
DateTimeFormatter frLocalizedFormatter =
|
||||||
|
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
|
||||||
|
String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||||
|
String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
|
||||||
|
|
||||||
|
Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
|
||||||
|
Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedDate() {
|
||||||
|
String europeanDatePattern = "dd.MM.yyyy";
|
||||||
|
DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern);
|
||||||
|
LocalDate summerDay = LocalDate.of(2016, 7, 31);
|
||||||
|
Assert.assertEquals("31.07.2016", europeanDateFormatter.format(summerDay));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedTime24() {
|
||||||
|
String timeColonPattern = "HH:mm:ss";
|
||||||
|
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
|
||||||
|
LocalTime colonTime = LocalTime.of(17, 35, 50);
|
||||||
|
Assert.assertEquals("17:35:50", timeColonFormatter.format(colonTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedTimeWithMillis() {
|
||||||
|
String timeColonPattern = "HH:mm:ss SSS";
|
||||||
|
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
|
||||||
|
LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS);
|
||||||
|
Assert.assertEquals("17:35:50 329", timeColonFormatter.format(colonTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedTimePM() {
|
||||||
|
String timeColonPattern = "hh:mm:ss a";
|
||||||
|
DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern);
|
||||||
|
LocalTime colonTime = LocalTime.of(17, 35, 50);
|
||||||
|
Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedUTCRelatedZonedDateTime() {
|
||||||
|
String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z";
|
||||||
|
DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern);
|
||||||
|
LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15);
|
||||||
|
Assert.assertEquals("31.07.2016 14:15 UTC-04:00", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedNewYorkZonedDateTime() {
|
||||||
|
String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z";
|
||||||
|
DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern);
|
||||||
|
LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15);
|
||||||
|
Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintStyledDate() {
|
||||||
|
LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23);
|
||||||
|
Assert.assertEquals("Tuesday, August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("Aug 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintStyledDateTime() {
|
||||||
|
LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45);
|
||||||
|
Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||||
|
Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldPrintFormattedDateTimeWithPredefined() {
|
||||||
|
Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9)));
|
||||||
|
Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||||
|
Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3"))));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldParseDateTime() {
|
||||||
|
Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldParseFormatStyleFull() {
|
||||||
|
ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET"));
|
||||||
|
Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldParseDateWithCustomFormatter() {
|
||||||
|
DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
|
||||||
|
Assert.assertFalse(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldParseTimeWithCustomFormatter() {
|
||||||
|
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
|
||||||
|
Assert.assertTrue(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldParseZonedDateTimeWithCustomFormatter() {
|
||||||
|
DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z");
|
||||||
|
Assert.assertEquals(7200, ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = DateTimeParseException.class)
|
||||||
|
public void shouldExpectAnExceptionIfDateTimeStringNotMatchPattern() {
|
||||||
|
DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z");
|
||||||
|
ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
package com.baeldung.zoneddatetime;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ZonedDateTimeUnitTest {
|
||||||
|
|
||||||
|
private static final Logger log = Logger.getLogger(ZonedDateTimeUnitTest.class.getName());
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testZonedDateTimeToString() {
|
||||||
|
|
||||||
|
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC"));
|
||||||
|
ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC"));
|
||||||
|
|
||||||
|
LocalDateTime localDateTime = LocalDateTime.now();
|
||||||
|
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));
|
||||||
|
|
||||||
|
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss Z");
|
||||||
|
String formattedString = zonedDateTime.format(formatter);
|
||||||
|
|
||||||
|
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss z");
|
||||||
|
String formattedString2 = zonedDateTime.format(formatter2);
|
||||||
|
|
||||||
|
log.info(formattedString);
|
||||||
|
log.info(formattedString2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testZonedDateTimeFromString() {
|
||||||
|
|
||||||
|
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00", DateTimeFormatter.ISO_ZONED_DATE_TIME);
|
||||||
|
|
||||||
|
log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -13,3 +13,4 @@
|
||||||
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||||
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
||||||
|
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||||
|
|
|
@ -31,3 +31,5 @@
|
||||||
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
|
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
|
||||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||||
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
|
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
|
||||||
|
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
|
||||||
|
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
|
||||||
|
|
|
@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||||
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
|
- [Java Bean Validation Basics](http://www.baeldung.com/javax-validation)
|
||||||
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
|
- [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements)
|
||||||
- [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints)
|
- [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints)
|
||||||
|
- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
|
||||||
|
|
|
@ -33,7 +33,7 @@
|
||||||
<version>${javax.el-api.version}</version>
|
<version>${javax.el-api.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.glassfish.web</groupId>
|
<groupId>org.glassfish</groupId>
|
||||||
<artifactId>javax.el</artifactId>
|
<artifactId>javax.el</artifactId>
|
||||||
<version>${javax.el.version}</version>
|
<version>${javax.el.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security)
|
|
@ -0,0 +1,102 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>jee-7-security</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
<name>jee-7-security</name>
|
||||||
|
<description>JavaEE 7 Spring Security Application</description>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax</groupId>
|
||||||
|
<artifactId>javaee-api</artifactId>
|
||||||
|
<version>${javaee_api.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.faces</groupId>
|
||||||
|
<artifactId>jsf-api</artifactId>
|
||||||
|
<version>${com.sun.faces.jsf.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.faces</groupId>
|
||||||
|
<artifactId>jsf-impl</artifactId>
|
||||||
|
<version>${com.sun.faces.jsf.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>jstl</artifactId>
|
||||||
|
<version>${jstl.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet</groupId>
|
||||||
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
|
<version>${javax.servlet-api.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.servlet.jsp</groupId>
|
||||||
|
<artifactId>jsp-api</artifactId>
|
||||||
|
<version>${jsp-api.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>taglibs</groupId>
|
||||||
|
<artifactId>standard</artifactId>
|
||||||
|
<version>${taglibs.standard.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.mvc</groupId>
|
||||||
|
<artifactId>javax.mvc-api</artifactId>
|
||||||
|
<version>1.0-pr</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-web</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-config</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-taglibs</artifactId>
|
||||||
|
<version>${org.springframework.security.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<version>${maven-war-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<warSourceDirectory>src/main/webapp</warSourceDirectory>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<javaee_api.version>7.0</javaee_api.version>
|
||||||
|
<com.sun.faces.jsf.version>2.2.14</com.sun.faces.jsf.version>
|
||||||
|
<jsp-api.version>2.2</jsp-api.version>
|
||||||
|
<taglibs.standard.version>1.1.2</taglibs.standard.version>
|
||||||
|
<org.springframework.security.version>4.2.3.RELEASE</org.springframework.security.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springSecurity;
|
package com.baeldung.springsecurity;
|
||||||
|
|
||||||
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springSecurity;
|
package com.baeldung.springsecurity;
|
||||||
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springSecurity.controller;
|
package com.baeldung.springsecurity.controller;
|
||||||
|
|
||||||
import javax.mvc.annotation.Controller;
|
import javax.mvc.annotation.Controller;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.springSecurity.controller;
|
package com.baeldung.springsecurity.controller;
|
||||||
|
|
||||||
import javax.mvc.annotation.Controller;
|
import javax.mvc.annotation.Controller;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="DEBUG">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
|
@ -0,0 +1,8 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<faces-config
|
||||||
|
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||||
|
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
|
||||||
|
version="2.0">
|
||||||
|
</faces-config>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue