Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Sandip Singh 2018-10-22 09:43:21 +05:30
commit 5d5a7863f1
642 changed files with 6322 additions and 1532 deletions

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
script: travis_wait 60 mvn -q install -Pdefault
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
sudo: required

View File

@ -26,3 +26,13 @@ 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
Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory

View File

@ -28,3 +28,6 @@
- [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)
- [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)

View File

@ -17,6 +17,11 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@ -85,6 +90,7 @@
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>
</project>

View File

@ -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());
}
}

View File

@ -0,0 +1,136 @@
package com.baeldung.algorithms.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;
}
}

View File

@ -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 };
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.algorithms.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));
}
}

8
apache-pulsar/.gitignore vendored Executable file
View File

@ -0,0 +1,8 @@
.classpath
.project
.settings
target
.idea
*.iml
.gradle/
build/

21
apache-pulsar/pom.xml Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.pulsar</groupId>
<artifactId>pulsar-java</artifactId>
<version>0.0.1</version>
<dependencies>
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.1.1-incubating</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
</project>

View File

@ -0,0 +1,48 @@
package com.baeldung;
import java.io.IOException;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.SubscriptionType;
public class ConsumerTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
//Configure consumer specific settings.
Consumer<byte[]> consumer = client.newConsumer()
.topic(TOPIC_NAME)
// Allow multiple consumers to attach to the same subscription
// and get messages dispatched as a queue
.subscriptionType(SubscriptionType.Shared)
.subscriptionName(SUBSCRIPTION_NAME)
.subscribe();
// Once the consumer is created, it can be used for the entire application lifecycle
System.out.println("Created consumer for the topic "+ TOPIC_NAME);
do {
// Wait until a message is available
Message<byte[]> msg = consumer.receive();
// Extract the message as a printable string and then log
String content = new String(msg.getData());
System.out.println("Received message '"+content+"' with ID "+msg.getMessageId());
// Acknowledge processing of the message so that it can be deleted
consumer.acknowledge(msg);
} while (true);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import java.io.IOException;
import java.util.stream.IntStream;
public class ProducerTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
public static void main(String[] args) throws IOException {
// Create a Pulsar client instance. A single instance can be shared across many
// producers and consumer within the same application
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
// Configure producer specific settings
Producer<byte[]> producer = client.newProducer()
// Set the topic
.topic(TOPIC_NAME)
// Enable compression
.compressionType(CompressionType.LZ4)
.create();
// Once the producer is created, it can be used for the entire application life-cycle
System.out.println("Created producer for the topic "+TOPIC_NAME);
// Send 5 test messages
IntStream.range(1, 5).forEach(i -> {
String content = String.format("hi-pulsar-%d", i);
// Build a message object
Message<byte[]> msg = MessageBuilder.create()
.setContent(content.getBytes())
.build();
// Send each message and log message content and ID when successfully received
try {
MessageId msgId = producer.send(msg);
System.out.println("Published message '"+content+"' with the ID "+msgId);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
client.close();
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.subscriptions;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class ExclusiveSubscriptionTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Exclusive;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumer1 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
ConsumerBuilder<byte[]> consumer2 = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
IntStream.range(0, 999).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
});
// Consumer 1 can subscribe to the topic
consumer1.subscribe();
// Consumer 2 cannot due to the exclusive subscription held by consumer 1
consumer2.subscribeAsync()
.handle((consumer, exception) -> {
System.out.println(exception.getMessage());
return null;
});
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.subscriptions;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageBuilder;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import java.util.stream.IntStream;
public class FailoverSubscriptionTest {
private static final String SERVICE_URL = "pulsar://localhost:6650";
private static final String TOPIC_NAME = "failover-subscription-test-topic";
private static final String SUBSCRIPTION_NAME = "test-subscription";
private static final SubscriptionType SUBSCRIPTION_TYPE = SubscriptionType.Failover;
private static final int NUM_MSGS = 10;
public static void main(String[] args) throws PulsarClientException {
PulsarClient client = PulsarClient.builder()
.serviceUrl(SERVICE_URL)
.build();
Producer<byte[]> producer = client.newProducer()
.topic(TOPIC_NAME)
.create();
ConsumerBuilder<byte[]> consumerBuilder = client.newConsumer()
.topic(TOPIC_NAME)
.subscriptionName(SUBSCRIPTION_NAME)
.subscriptionType(SUBSCRIPTION_TYPE);
Consumer<byte[]> mainConsumer = consumerBuilder
.consumerName("consumer-a")
.messageListener((consumer, msg) -> {
System.out.println("Message received by main consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
Consumer<byte[]> failoverConsumer = consumerBuilder
.consumerName("consumer-b")
.messageListener((consumer, msg) -> {
System.out.println("Message received by failover consumer");
try {
consumer.acknowledge(msg);
} catch (PulsarClientException e) {
System.out.println(e.getMessage());
}
})
.subscribe();
IntStream.range(0, NUM_MSGS).forEach(i -> {
Message<byte[]> msg = MessageBuilder.create()
.setContent(String.format("message-%d", i).getBytes())
.build();
try {
producer.send(msg);
Thread.sleep(100);
if (i > 5) mainConsumer.close();
} catch (InterruptedException | PulsarClientException e) {
System.out.println(e.getMessage());
}
});
}
}

View File

@ -9,4 +9,4 @@
- [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)
- [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)

View File

@ -32,3 +32,4 @@
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)

View File

@ -26,3 +26,4 @@
- [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)
- [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)

View File

@ -4,37 +4,23 @@
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
- [Guide to the Guava BiMap](http://www.baeldung.com/guava-bimap)
- [The Java HashMap Under the Hood](http://www.baeldung.com/java-hashmap)
- [A Guide to LinkedHashMap in Java](http://www.baeldung.com/java-linked-hashmap)
- [A Guide to TreeMap in Java](http://www.baeldung.com/java-treemap)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Iterate over a Map in Java](http://www.baeldung.com/java-iterate-map)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
@ -47,8 +33,8 @@
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [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)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)

View File

@ -14,22 +14,11 @@
</parent>
<dependencies>
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>${collections-generic.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
@ -67,12 +56,6 @@
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.6.5</version>
</dependency>
</dependencies>
<properties>

View File

@ -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);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionRemoveIf {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
names.removeIf(e -> e.startsWith("A"));
System.out.println(String.join(",", names));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Iterators {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String e = i.next();
if (e.startsWith("A")) {
i.remove();
}
}
System.out.println(String.join(",", names));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;
public class StreamFilterAndCollector {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Collection<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
System.out.println(String.join(",", filteredCollection));
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.removal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamPartitioningBy {
public static void main(String args[]) {
Collection<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Map<Boolean, List<String>> classifiedElements = names
.stream()
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
String matching = String.join(",", classifiedElements.get(Boolean.TRUE));
String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE));
System.out.println("Matching elements: " + matching);
System.out.println("Non matching elements: " + nonMatching);
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.removal;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class RemovalUnitTest {
Collection<String> names;
Collection<String> expected;
Collection<String> removed;
@Before
public void setupTestData() {
names = new ArrayList<>();
expected = new ArrayList<>();
removed = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
expected.add("John");
expected.add("Mary");
expected.add("Mark");
removed.add("Ana");
removed.add("Anthony");
}
@Test
public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String e = i.next();
if (e.startsWith("A")) {
i.remove();
}
}
assertThat(names, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
names.removeIf(e -> e.startsWith("A"));
assertThat(names, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() {
Collection<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
assertThat(filteredCollection, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() {
Map<Boolean, List<String>> classifiedElements = names
.stream()
.collect(Collectors.partitioningBy((String e) -> !e.startsWith("A")));
assertThat(classifiedElements.get(Boolean.TRUE), is(expected));
assertThat(classifiedElements.get(Boolean.FALSE), is(removed));
}
}

View File

@ -29,3 +29,4 @@
- [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)
- [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)

View File

@ -184,5 +184,25 @@ public class CompletableFutureLongRunningUnitTest {
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);
}
}

View File

@ -0,0 +1 @@
Test1

View File

@ -0,0 +1 @@
Test2

View File

@ -29,7 +29,6 @@
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
- [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions)
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
@ -150,3 +149,11 @@
- [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)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
- [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)
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}

View File

@ -1,11 +1,11 @@
package com.baeldung.nth.root.calculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class NthRootCalculatorUnitTest {

View File

@ -0,0 +1,59 @@
package com.baeldung;
import org.junit.Test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SimpleDateFormatUnitTest {
private static final Logger logger = Logger.getLogger(SimpleDateFormatUnitTest.class.getName());
@Test
public void givenSpecificDate_whenFormatted_thenCheckFormatCorrect() throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
assertEquals("24-05-1977", formatter.format(new Date(233345223232L)));
}
@Test
public void givenSpecificDate_whenFormattedUsingDateFormat_thenCheckFormatCorrect() throws Exception {
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
assertEquals("5/24/77", formatter.format(new Date(233345223232L)));
}
@Test
public void givenStringDate_whenParsed_thenCheckDateCorrect() throws Exception{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date(233276400000L);
Date parsedDate = formatter.parse("24-05-1977");
assertEquals(myDate.getTime(), parsedDate.getTime());
}
@Test
public void givenFranceLocale_whenFormatted_thenCheckFormatCorrect() throws Exception{
SimpleDateFormat franceDateFormatter = new SimpleDateFormat("EEEEE dd-MMMMMMM-yyyy", Locale.FRANCE);
Date myWednesday = new Date(1539341312904L);
assertTrue(franceDateFormatter.format(myWednesday).startsWith("vendredi"));
}
@Test
public void given2TimeZones_whenFormatted_thenCheckTimeDifference() throws Exception {
Date now = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MMM-yy HH:mm:ssZ");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
logger.info(simpleDateFormat.format(now));
//change the date format
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
logger.info(simpleDateFormat.format(now));
}
}

View File

@ -37,3 +37,5 @@
- [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [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)

View File

@ -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()
}
}

View File

@ -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

View File

@ -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")
}
}

View File

@ -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)
}
}

View File

@ -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())
}
}

View File

@ -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'
}
}

View File

@ -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));
}
}

View File

@ -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);
});
}
}

View File

@ -5,6 +5,6 @@ include 'greeting-library'
include 'greeting-library-java'
include 'greeter'
include 'gradletaskdemo'
include 'junit5'
println 'This will be executed during the initialization phase.'

View File

@ -0,0 +1,23 @@
=========
## 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)
- [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
- [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map)

66
guava-collections/pom.xml Normal file
View File

@ -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>

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1 @@
John Jane Adam Tom

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Test

View File

@ -0,0 +1,4 @@
John
Jane
Adam
Tom

View File

@ -0,0 +1 @@
Hello world

Binary file not shown.

View File

@ -4,33 +4,16 @@
### 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)
- [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 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)
- [Guide to Guavas Ordering](http://www.baeldung.com/guava-ordering)
- [Guide to Guavas PreConditions](http://www.baeldung.com/guava-preconditions)
- [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader)
- [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer)
- [Guide to Guavas 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 Guavas Reflection Utilities](http://www.baeldung.com/guava-reflection)
- [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)
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
- [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)

View File

@ -14,12 +14,6 @@
</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>
@ -56,7 +50,6 @@
<!-- 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>

View File

@ -16,3 +16,4 @@
- [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)
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)

View File

@ -44,6 +44,11 @@
<artifactId>mariaDB4j</artifactId>
<version>${mariaDB4j.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-testing</artifactId>
<version>5.2.2.Final</version>
</dependency>
</dependencies>
<build>
@ -57,7 +62,7 @@
</build>
<properties>
<hibernate.version>5.3.2.Final</hibernate.version>
<hibernate.version>5.3.6.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<h2database.version>1.4.196</h2database.version>

View File

@ -5,6 +5,8 @@ import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
import com.baeldung.hibernate.customtypes.OfficeEmployee;
import com.baeldung.hibernate.entities.DeptEmployee;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
@ -18,8 +20,10 @@ import com.baeldung.hibernate.pojo.inheritance.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.pojo.Course;
@ -66,6 +70,7 @@ public class HibernateUtil {
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
@ -102,8 +107,12 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
metadataSources.addAnnotatedClass(OfficeEmployee.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
.build();

View File

@ -0,0 +1,69 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public class Address {
private String addressLine1;
private String addressLine2;
private String city;
private String country;
private int zipCode;
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public int getZipCode() {
return zipCode;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address = (Address) o;
return zipCode == address.zipCode &&
Objects.equals(addressLine1, address.addressLine1) &&
Objects.equals(addressLine2, address.addressLine2) &&
Objects.equals(city, address.city) &&
Objects.equals(country, address.country);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, country, zipCode);
}
}

View File

@ -0,0 +1,169 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AddressType implements CompositeUserType {
@Override
public String[] getPropertyNames() {
return new String[]{"addressLine1", "addressLine2",
"city", "country", "zipcode"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
return empAdd.getAddressLine1();
case 1:
return empAdd.getAddressLine2();
case 2:
return empAdd.getCity();
case 3:
return empAdd.getCountry();
case 4:
return Integer.valueOf(empAdd.getZipCode());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
empAdd.setAddressLine1((String) value);
case 1:
empAdd.setAddressLine2((String) value);
case 2:
empAdd.setCity((String) value);
case 3:
empAdd.setCountry((String) value);
case 4:
empAdd.setZipCode((Integer) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
return Address.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
Address empAdd = new Address();
empAdd.setAddressLine1(rs.getString(names[0]));
if (rs.wasNull())
return null;
empAdd.setAddressLine2(rs.getString(names[1]));
empAdd.setCity(rs.getString(names[2]));
empAdd.setCountry(rs.getString(names[3]));
empAdd.setZipCode(rs.getInt(names[4]));
return empAdd;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Address empAdd = (Address) value;
st.setString(index, empAdd.getAddressLine1());
st.setString(index + 1, empAdd.getAddressLine2());
st.setString(index + 2, empAdd.getCity());
st.setString(index + 3, empAdd.getCountry());
st.setInt(index + 4, empAdd.getZipCode());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
newEmpAdd.setCity(oldEmpAdd.getCity());
newEmpAdd.setCountry(oldEmpAdd.getCountry());
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
return newEmpAdd;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
public LocalDateStringJavaDescriptor() {
super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
}
@Override
public String toString(LocalDate value) {
return LocalDateType.FORMATTER.format(value);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
}
@Override
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
if (value == null)
return null;
if (String.class.isAssignableFrom(type))
return (X) LocalDateType.FORMATTER.format(value);
throw unknownUnwrap(type);
}
@Override
public <X> LocalDate wrap(X value, WrapperOptions options) {
if (value == null)
return null;
if(String.class.isInstance(value))
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import java.time.LocalDate;
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
public String getName() {
return "LocalDateString";
}
@Override
public LocalDate stringToObject(String xml) throws Exception {
return fromString(xml);
}
@Override
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
return '\'' + toString(value) + '\'';
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDate;
@TypeDef(name = "PhoneNumber",
typeClass = PhoneNumberType.class,
defaultForType = PhoneNumber.class)
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@Id
@GeneratedValue
private long id;
@Column
@Type(type = "LocalDateString")
private LocalDate dateOfJoining;
@Columns(columns = {@Column(name = "country_code"),
@Column(name = "city_code"),
@Column(name = "number")})
private PhoneNumber employeeNumber;
@Columns(columns = {@Column(name = "address_line_1"),
@Column(name = "address_line_2"),
@Column(name = "city"), @Column(name = "country"),
@Column(name = "zip_code")})
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
private Address empAddress;
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
parameters = {@Parameter(name = "currency", value = "USD")})
@Columns(columns = {@Column(name = "amount"),
@Column(name = "currency")})
private Salary salary;
public Salary getSalary() {
return salary;
}
public void setSalary(Salary salary) {
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public LocalDate getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(LocalDate dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public PhoneNumber getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(PhoneNumber employeeNumber) {
this.employeeNumber = employeeNumber;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public final class PhoneNumber {
private final int countryCode;
private final int cityCode;
private final int number;
public PhoneNumber(int countryCode, int cityCode, int number) {
this.countryCode = countryCode;
this.cityCode = cityCode;
this.number = number;
}
public int getCountryCode() {
return countryCode;
}
public int getCityCode() {
return cityCode;
}
public int getNumber() {
return number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PhoneNumber that = (PhoneNumber) o;
return countryCode == that.countryCode &&
cityCode == that.cityCode &&
number == that.number;
}
@Override
public int hashCode() {
return Objects.hash(countryCode, cityCode, number);
}
}

View File

@ -0,0 +1,98 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
}
@Override
public Class returnedClass() {
return PhoneNumber.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
int countryCode = rs.getInt(names[0]);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
return employeeNumber;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
PhoneNumber empNumber = (PhoneNumber) value;
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
return newEmpNumber;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public class Salary {
private Long amount;
private String currency;
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Salary salary = (Salary) o;
return Objects.equals(amount, salary.amount) &&
Objects.equals(currency, salary.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.hibernate.customtypes;
public class SalaryCurrencyConvertor {
public static Long convert(Long amount, String oldCurr, String newCurr){
if (newCurr.equalsIgnoreCase(oldCurr))
return amount;
return convertTo();
}
private static Long convertTo() {
return 10L;
}
}

View File

@ -0,0 +1,161 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
private String localCurrency;
@Override
public String[] getPropertyNames() {
return new String[]{"amount", "currency"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
return salary.getAmount();
case 1:
return salary.getCurrency();
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
salary.setAmount((Long) value);
case 1:
salary.setCurrency((String) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
Salary salary = new Salary();
salary.setAmount(rs.getLong(names[0]));
if (rs.wasNull())
return null;
salary.setCurrency(rs.getString(names[1]));
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
Salary salary = (Salary) value;
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
salary.getCurrency(), localCurrency));
st.setString(index + 1, salary.getCurrency());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
Salary oldSal = (Salary) value;
Salary newSal = new Salary();
newSal.setAmount(oldSal.getAmount());
newSal.setCurrency(oldSal.getCurrency());
return newSal;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
}
@Override
public void setParameterValues(Properties parameters) {
this.localCurrency = parameters.getProperty("currency");
}
}

View File

@ -0,0 +1,90 @@
package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.time.LocalDate;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
public class HibernateCustomTypesUnitTest {
@Test
public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException {
final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now());
PhoneNumber number = new PhoneNumber(1, 222, 8781902);
e.setEmployeeNumber(number);
Address empAdd = new Address();
empAdd.setAddressLine1("Street");
empAdd.setAddressLine2("Area");
empAdd.setCity("City");
empAdd.setCountry("Country");
empAdd.setZipCode(100);
e.setEmpAddress(empAdd);
Salary empSalary = new Salary();
empSalary.setAmount(1000L);
empSalary.setCurrency("USD");
e.setSalary(empSalary);
doInHibernate(this::sessionFactory, session -> {
session.save(e);
boolean contains = session.contains(e);
Assert.assertTrue(contains);
});
}
@Test
public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException {
final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now());
PhoneNumber number = new PhoneNumber(1, 222, 8781902);
e.setEmployeeNumber(number);
Address empAdd = new Address();
empAdd.setAddressLine1("Street");
empAdd.setAddressLine2("Area");
empAdd.setCity("City");
empAdd.setCountry("Country");
empAdd.setZipCode(100);
e.setEmpAddress(empAdd);
Salary empSalary = new Salary();
empSalary.setAmount(1000L);
empSalary.setCurrency("USD");
e.setSalary(empSalary);
doInHibernate(this::sessionFactory, session -> {
session.save(e);
Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode");
query.setParameter("pinCode",100);
int size = query.list().size();
Assert.assertEquals(1, size);
});
}
private SessionFactory sessionFactory() {
try {
return HibernateUtil.getSessionFactory("hibernate-customtypes.properties");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,10 @@
hibernate.connection.driver_class=org.postgresql.Driver
hibernate.connection.url=jdbc:postgresql://localhost:5432/test
hibernate.connection.username=postgres
hibernate.connection.password=thule
hibernate.connection.autocommit=true
jdbc.password=thule
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

View File

@ -1,7 +1,5 @@
package com.baeldung.jackson.xmlToJson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@ -14,43 +12,32 @@ import java.io.IOException;
public class XmlToJsonUnitTest {
@Test
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() {
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
XmlMapper xmlMapper = new XmlMapper();
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
assertEquals(poppy.getName(), "Poppy");
assertEquals(poppy.getColor(), Color.RED);
assertEquals(poppy.getPetals(), new Integer(9));
assertEquals(poppy.getName(), "Poppy");
assertEquals(poppy.getColor(), Color.RED);
assertEquals(poppy.getPetals(), new Integer(9));
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(poppy);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(poppy);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
System.out.println(json);
} catch(IOException e) {
e.printStackTrace();
}
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
}
@Test
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() {
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException {
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
try {
XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);
System.out.println(json);
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
} catch(IOException e) {
e.printStackTrace();
}
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
}
}

View File

@ -0,0 +1,11 @@
=========
## Java Collections Cookbooks and Examples
### Relevant Articles:
- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)

View File

@ -0,0 +1,40 @@
<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>java-collections-conversions</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-collections-conversions</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<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>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<assertj.version>3.6.1</assertj.version>
</properties>
</project>

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