commit
d0d9402822
9
.gitignore
vendored
9
.gitignore
vendored
@ -48,3 +48,12 @@ dependency-reduced-pom.xml
|
|||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
*.dll
|
*.dll
|
||||||
|
|
||||||
|
xml/src/test/resources/example_dom4j_new.xml
|
||||||
|
xml/src/test/resources/example_dom4j_updated.xml
|
||||||
|
xml/src/test/resources/example_jaxb_new.xml
|
||||||
|
core-java-io/hard_link.txt
|
||||||
|
core-java-io/target_link.txt
|
||||||
|
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||||
|
ethereum/logs/
|
||||||
|
jmeter/src/main/resources/*-JMeter.csv
|
@ -19,7 +19,7 @@ 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 -Dgib.enabled=false`
|
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||||
|
|
||||||
|
|
||||||
Working with the code in Eclipse
|
Working with the code in Eclipse
|
||||||
|
3
apache-meecrowave/README.md
Normal file
3
apache-meecrowave/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
================================
|
||||||
|
- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)
|
@ -46,7 +46,6 @@
|
|||||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||||
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
|
|
||||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||||
@ -55,3 +54,5 @@
|
|||||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||||
|
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
|
||||||
|
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||||
|
@ -99,6 +99,16 @@
|
|||||||
<artifactId>joda-time</artifactId>
|
<artifactId>joda-time</artifactId>
|
||||||
<version>${joda.version}</version>
|
<version>${joda.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.aspectj</groupId>
|
||||||
|
<artifactId>aspectjrt</artifactId>
|
||||||
|
<version>${asspectj.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.aspectj</groupId>
|
||||||
|
<artifactId>aspectjweaver</artifactId>
|
||||||
|
<version>${asspectj.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -170,6 +180,7 @@
|
|||||||
<joda.version>2.10</joda.version>
|
<joda.version>2.10</joda.version>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<asspectj.version>1.8.9</asspectj.version>
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
<jmh-core.version>1.19</jmh-core.version>
|
<jmh-core.version>1.19</jmh-core.version>
|
||||||
<jmh-generator.version>1.19</jmh-generator.version>
|
<jmh-generator.version>1.19</jmh-generator.version>
|
||||||
|
@ -0,0 +1,9 @@
|
|||||||
|
package com.baeldung.aspect;
|
||||||
|
|
||||||
|
public aspect ChangeCallsToCurrentTimeInMillisMethod {
|
||||||
|
long around():
|
||||||
|
call(public static native long java.lang.System.currentTimeMillis())
|
||||||
|
&& within(user.code.base.pckg.*) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,87 @@
|
|||||||
|
package com.baeldung.list;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class AddElementsUnitTest {
|
||||||
|
|
||||||
|
List<Flower> flowers;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
this.flowers = new ArrayList<>(Arrays.asList(
|
||||||
|
new Flower("Poppy", 12),
|
||||||
|
new Flower("Anemone", 8),
|
||||||
|
new Flower("Catmint", 12)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
|
||||||
|
Flower flower = anotherList.get(0);
|
||||||
|
flower.setPetals(flowers.get(0).getPetals() * 3);
|
||||||
|
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
|
||||||
|
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
|
||||||
|
|
||||||
|
assertEquals(target.size(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
|
||||||
|
flowers.stream()
|
||||||
|
.skip(1)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
|
||||||
|
flowers.stream()
|
||||||
|
.filter(f -> f.getPetals() > 10)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
|
||||||
|
Optional.ofNullable(flowers)
|
||||||
|
.ifPresent(target::addAll);
|
||||||
|
|
||||||
|
assertNotNull(target);
|
||||||
|
assertEquals(target.size(), 3);
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.util;
|
package com.baeldung.util;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@ -9,6 +10,8 @@ import java.time.LocalTime;
|
|||||||
import java.time.ZoneId;
|
import java.time.ZoneId;
|
||||||
import java.time.temporal.ChronoField;
|
import java.time.temporal.ChronoField;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.joda.time.DateTimeUtils;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class CurrentDateTimeUnitTest {
|
public class CurrentDateTimeUnitTest {
|
||||||
@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest {
|
|||||||
|
|
||||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -19,11 +19,23 @@
|
|||||||
<version>${awaitility.version}</version>
|
<version>${awaitility.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>${guava.version}</version>
|
<version>${guava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-runner</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -50,6 +62,8 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
|
<assertj.version>3.10.0</assertj.version>
|
||||||
|
<junit.platform.version>1.2.0</junit.platform.version>
|
||||||
<awaitility.version>1.7.0</awaitility.version>
|
<awaitility.version>1.7.0</awaitility.version>
|
||||||
<maven.compiler.source>1.9</maven.compiler.source>
|
<maven.compiler.source>1.9</maven.compiler.source>
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.java9.language.stream;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.filtering;
|
||||||
|
import static java.util.stream.Collectors.groupingBy;
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
public class StreamsGroupingCollectionFilter {
|
||||||
|
|
||||||
|
static public Map<Integer, List<Integer>> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
|
||||||
|
Function<Integer, Integer> getQuantityOfDigits = item -> (int) Math.log10(item) + 1;
|
||||||
|
|
||||||
|
return baseCollection.stream()
|
||||||
|
.collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList())));
|
||||||
|
}
|
||||||
|
|
||||||
|
static public Map<Integer, List<Integer>> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
|
||||||
|
|
||||||
|
return baseCollection.stream()
|
||||||
|
.filter(item -> item % 2 == 0)
|
||||||
|
.collect(groupingBy(item -> (int) Math.log10(item) + 1, toList()));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.java9.maps.initialize;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MapsInitializer {
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void createMapWithMapOf() {
|
||||||
|
Map<String, String> emptyMap = Map.of();
|
||||||
|
Map<String, String> singletonMap = Map.of("key1", "value");
|
||||||
|
Map<String, String> map = Map.of("key1","value1", "key2", "value2");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createMapWithMapEntries() {
|
||||||
|
Map<String, String> map = Map.ofEntries(
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("name", "John"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("city", "budapest"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("zip", "000000"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("home", "1231231231")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void createMutableMaps() {
|
||||||
|
Map<String, String> map = new HashMap<String, String> (Map.of("key1","value1", "key2", "value2"));
|
||||||
|
Map<String, String> map2 = new HashMap<String, String> ( Map.ofEntries(
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("name", "John"),
|
||||||
|
new AbstractMap.SimpleEntry<String, String>("city", "budapest")));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.java9.language.stream;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.platform.runner.JUnitPlatform;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
@RunWith(JUnitPlatform.class)
|
||||||
|
public class CollectionFilterUnitTest {
|
||||||
|
|
||||||
|
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8);
|
||||||
|
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap();
|
||||||
|
private static Map<Integer, List<Integer>> createExpectedFilterAfterGroupingMap() {
|
||||||
|
Map<Integer, List<Integer>> map = new HashMap<>();
|
||||||
|
map.put(1, Arrays.asList(8));
|
||||||
|
map.put(2, Arrays.asList(12, 56));
|
||||||
|
map.put(3, Collections.emptyList());
|
||||||
|
map.put(4, Arrays.asList(8002, 2668));
|
||||||
|
return map;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap();
|
||||||
|
private static Map<Integer, List<Integer>> createExpectedFilterBeforeGroupingMap() {
|
||||||
|
Map<Integer, List<Integer>> map = new HashMap<>();
|
||||||
|
map.put(1, Arrays.asList(8));
|
||||||
|
map.put(2, Arrays.asList(12, 56));
|
||||||
|
map.put(4, Arrays.asList(8002, 2668));
|
||||||
|
return map;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
|
||||||
|
Map<Integer, List<Integer>> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
|
||||||
|
Map<Integer, List<Integer>> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
|
||||||
|
|
||||||
|
assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP);
|
||||||
|
assertThat(filteredBeforeGroupingMap).doesNotContainKey(3)
|
||||||
|
.containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -30,3 +30,4 @@
|
|||||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
- [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)
|
- [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)
|
- [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)
|
||||||
|
@ -36,19 +36,37 @@
|
|||||||
<artifactId>commons-lang3</artifactId>
|
<artifactId>commons-lang3</artifactId>
|
||||||
<version>${commons-lang3.version}</version>
|
<version>${commons-lang3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.collections</groupId>
|
||||||
|
<artifactId>eclipse-collections-api</artifactId>
|
||||||
|
<version>${eclipse.collections.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.eclipse.collections</groupId>
|
||||||
|
<artifactId>eclipse-collections</artifactId>
|
||||||
|
<version>${eclipse.collections.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>${assertj.version}</version>
|
<version>${assertj.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-runner</artifactId>
|
||||||
|
<version>${junit.platform.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<junit.platform.version>1.2.0</junit.platform.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>
|
<commons-collections4.version>4.1</commons-collections4.version>
|
||||||
<collections-generic.version>4.01</collections-generic.version>
|
<collections-generic.version>4.01</collections-generic.version>
|
||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<eclipse.collections.version>9.2.0</eclipse.collections.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,18 +1,19 @@
|
|||||||
package com.baeldung.convertlisttomap;
|
package com.baeldung.convertlisttomap;
|
||||||
|
|
||||||
|
import com.google.common.collect.Maps;
|
||||||
|
import org.apache.commons.collections4.MapUtils;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.apache.commons.collections4.IterableUtils;
|
|
||||||
import org.apache.commons.collections4.MapUtils;
|
|
||||||
import com.google.common.collect.Maps;
|
|
||||||
|
|
||||||
public class ConvertListToMapService {
|
public class ConvertListToMapService {
|
||||||
|
|
||||||
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
|
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
|
||||||
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
|
||||||
|
Map<Integer, Animal> map = new HashMap<>();
|
||||||
|
|
||||||
for (Animal animal : list) {
|
for (Animal animal : list) {
|
||||||
map.put(animal.getId(), animal);
|
map.put(animal.getId(), animal);
|
||||||
}
|
}
|
||||||
@ -30,20 +31,9 @@ public class ConvertListToMapService {
|
|||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<Integer, Animal> convertListWithApacheCommons1(List<Animal> list) {
|
public Map<Integer, Animal> convertListWithApacheCommons(List<Animal> list) {
|
||||||
|
|
||||||
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
Map<Integer, Animal> map = new HashMap<>();
|
||||||
|
|
||||||
IterableUtils.forEach(list, animal -> {
|
|
||||||
map.put(animal.getId(), animal);
|
|
||||||
});
|
|
||||||
|
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Map<Integer, Animal> convertListWithApacheCommons2(List<Animal> list) {
|
|
||||||
|
|
||||||
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
|
|
||||||
|
|
||||||
MapUtils.populateMap(map, list, Animal::getId);
|
MapUtils.populateMap(map, list, Animal::getId);
|
||||||
|
|
@ -0,0 +1,16 @@
|
|||||||
|
package com.baeldung.java.filtering;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.CollectionUtils;
|
||||||
|
import org.apache.commons.collections4.Predicate;
|
||||||
|
|
||||||
|
public class CollectionUtilsCollectionFilter {
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
|
||||||
|
Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;
|
||||||
|
|
||||||
|
CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
|
||||||
|
return baseCollection;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.java.filtering;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.eclipse.collections.api.block.predicate.Predicate;
|
||||||
|
import org.eclipse.collections.impl.factory.Lists;
|
||||||
|
import org.eclipse.collections.impl.utility.Iterate;
|
||||||
|
|
||||||
|
public class EclipseCollectionsCollectionFilter {
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
|
||||||
|
Predicate<Integer> eclipsePredicate = item -> item % 2 == 0;
|
||||||
|
Collection<Integer> filteredList = Lists.mutable.ofAll(baseCollection)
|
||||||
|
.select(eclipsePredicate);
|
||||||
|
|
||||||
|
return filteredList;
|
||||||
|
}
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbersUsingIterate(Collection<Integer> baseCollection) {
|
||||||
|
Predicate<Integer> eclipsePredicate = new Predicate<Integer>() {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean accept(Integer arg0) {
|
||||||
|
return arg0 % 2 == 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Collection<Integer> filteredList = Iterate.select(baseCollection, eclipsePredicate);
|
||||||
|
|
||||||
|
return filteredList;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,17 @@
|
|||||||
|
package com.baeldung.java.filtering;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import com.google.common.base.Predicate;
|
||||||
|
import com.google.common.collect.Collections2;
|
||||||
|
|
||||||
|
public class GuavaCollectionFilter {
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
|
||||||
|
Predicate<Integer> guavaPredicate = item -> item % 2 == 0;
|
||||||
|
|
||||||
|
Collection<Integer> filteredCollection = Collections2.filter(baseCollection, guavaPredicate);
|
||||||
|
return filteredCollection;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.java.filtering;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class StreamsCollectionFilter {
|
||||||
|
|
||||||
|
public static <T> Collection<T> filterCollectionHelperMethod(Collection<T> baseCollection, Predicate<T> predicate) {
|
||||||
|
return baseCollection.stream()
|
||||||
|
.filter(predicate)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbersUsingHelperMethod(Collection<Integer> baseCollection) {
|
||||||
|
return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
|
||||||
|
Predicate<Integer> streamsPredicate = item -> item % 2 == 0;
|
||||||
|
|
||||||
|
return baseCollection.stream()
|
||||||
|
.filter(streamsPredicate)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.java.list;
|
||||||
|
|
||||||
|
public class Flower {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private int petals;
|
||||||
|
|
||||||
|
public Flower(String name, int petals) {
|
||||||
|
this.name = name;
|
||||||
|
this.petals = petals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPetals() {
|
||||||
|
return petals;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPetals(int petals) {
|
||||||
|
this.petals = petals;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.java.map.initialize;
|
||||||
|
|
||||||
|
import java.util.AbstractMap;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class MapInitializer {
|
||||||
|
|
||||||
|
public static Map<String, String> articleMapOne;
|
||||||
|
static {
|
||||||
|
articleMapOne = new HashMap<>();
|
||||||
|
articleMapOne.put("ar01", "Intro to Map");
|
||||||
|
articleMapOne.put("ar02", "Some article");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map<String, String> createSingletonMap() {
|
||||||
|
Map<String, String> passwordMap = Collections.singletonMap("username1", "password1");
|
||||||
|
return passwordMap;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createEmptyMap() {
|
||||||
|
Map<String, String> emptyMap = Collections.emptyMap();
|
||||||
|
return emptyMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createUsingDoubleBrace() {
|
||||||
|
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
{
|
||||||
|
put("key1", "value1");
|
||||||
|
put("key2", "value2");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return doubleBraceMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createMapUsingStreamStringArray() {
|
||||||
|
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
|
||||||
|
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamObjectArray() {
|
||||||
|
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
|
||||||
|
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
|
||||||
|
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
|
||||||
|
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
|
||||||
|
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||||
|
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> createImmutableMapWithStreams() {
|
||||||
|
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
|
||||||
|
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
|
||||||
|
return map;
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,13 +1,14 @@
|
|||||||
package com.baeldung.convertlisttomap;
|
package com.baeldung.convertlisttomap;
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
import org.junit.Before;
|
||||||
import static org.hamcrest.Matchers.*;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.junit.Before;
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
import org.junit.Test;
|
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||||
|
|
||||||
public class ConvertListToMapServiceUnitTest {
|
public class ConvertListToMapServiceUnitTest {
|
||||||
List<Animal> list;
|
List<Animal> list;
|
||||||
@ -29,6 +30,7 @@ public class ConvertListToMapServiceUnitTest {
|
|||||||
list.add(cow);
|
list.add(cow);
|
||||||
Animal goat = new Animal(5, "Goat");
|
Animal goat = new Animal(5, "Goat");
|
||||||
list.add(goat);
|
list.add(goat);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -56,18 +58,11 @@ public class ConvertListToMapServiceUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenAList_whenConvertWithApacheCommons1_thenReturnMapWithTheSameElements() {
|
public void givenAList_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() {
|
||||||
|
|
||||||
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons1(list);
|
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(list);
|
||||||
|
|
||||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenAList_whenConvertWithApacheCommons2_thenReturnMapWithTheSameElements() {
|
|
||||||
|
|
||||||
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons2(list);
|
|
||||||
|
|
||||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -0,0 +1,68 @@
|
|||||||
|
package com.baeldung.convertlisttomap;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.hasItem;
|
||||||
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
|
||||||
|
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
|
||||||
|
List<Animal> duplicatedIdList;
|
||||||
|
|
||||||
|
private ConvertListToMapService convertListService = new ConvertListToMapService();
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
this.duplicatedIdList = new ArrayList<>();
|
||||||
|
|
||||||
|
Animal cat = new Animal(1, "Cat");
|
||||||
|
duplicatedIdList.add(cat);
|
||||||
|
Animal dog = new Animal(2, "Dog");
|
||||||
|
duplicatedIdList.add(dog);
|
||||||
|
Animal pig = new Animal(3, "Pig");
|
||||||
|
duplicatedIdList.add(pig);
|
||||||
|
Animal cow = new Animal(4, "Cow");
|
||||||
|
duplicatedIdList.add(cow);
|
||||||
|
Animal goat = new Animal(4, "Goat");
|
||||||
|
duplicatedIdList.add(goat);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(duplicatedIdList);
|
||||||
|
|
||||||
|
assertThat(map.values(), hasSize(4));
|
||||||
|
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {
|
||||||
|
|
||||||
|
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(duplicatedIdList);
|
||||||
|
|
||||||
|
assertThat(map.values(), hasSize(4));
|
||||||
|
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalStateException.class)
|
||||||
|
public void givenADupIdList_whenConvertAfterJava8_thenException() {
|
||||||
|
|
||||||
|
convertListService.convertListAfterJava8(duplicatedIdList);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void givenADupIdList_whenConvertWithGuava_thenException() {
|
||||||
|
|
||||||
|
convertListService.convertListWithGuava(duplicatedIdList);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.java.filtering;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.platform.runner.JUnitPlatform;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
|
||||||
|
@RunWith(JUnitPlatform.class)
|
||||||
|
public class CollectionFiltersUnitTest {
|
||||||
|
|
||||||
|
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8);
|
||||||
|
private static final Collection<Integer> EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
|
||||||
|
final Collection<String> baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other");
|
||||||
|
|
||||||
|
Collection<String> filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4);
|
||||||
|
|
||||||
|
assertThat(filtered).containsExactlyInAnyOrder("java", "type");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() {
|
||||||
|
Collection<Integer> filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
|
||||||
|
Collection<Integer> filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION));
|
||||||
|
Collection<Integer> filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
|
||||||
|
Collection<Integer> filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION);
|
||||||
|
Collection<Integer> filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
|
||||||
|
|
||||||
|
assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils)
|
||||||
|
.hasSameElementsAs(filteredWithEclipseCollections)
|
||||||
|
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
|
||||||
|
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
|
||||||
|
.hasSameElementsAs(filteredWithGuava)
|
||||||
|
.hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,27 @@
|
|||||||
|
package com.baeldung.java.map.initialize;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class MapInitializerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStaticMap_whenUpdated_thenCorrect() {
|
||||||
|
|
||||||
|
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
|
||||||
|
|
||||||
|
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=UnsupportedOperationException.class)
|
||||||
|
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
|
||||||
|
|
||||||
|
Map<String, String> map = MapInitializer.createSingletonMap();
|
||||||
|
map.put("username2", "password2");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.list.listoflist;
|
||||||
|
|
||||||
|
import com.baeldung.java.list.Flower;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import java.util.*;
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class AddElementsToListUnitTest {
|
||||||
|
|
||||||
|
List<Flower> flowers;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
this.flowers = new ArrayList<>(Arrays.asList(
|
||||||
|
new Flower("Poppy", 12),
|
||||||
|
new Flower("Anemone", 8),
|
||||||
|
new Flower("Catmint", 12)));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
|
||||||
|
List<Flower> anotherList = new ArrayList<>();
|
||||||
|
anotherList.addAll(flowers);
|
||||||
|
Flower flower = anotherList.get(0);
|
||||||
|
flower.setPetals(flowers.get(0).getPetals() * 3);
|
||||||
|
assertEquals(anotherList.size(), flowers.size());
|
||||||
|
Assert.assertTrue(anotherList.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
|
||||||
|
assertEquals(target.size(), 4);
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
flowers.stream()
|
||||||
|
.skip(1)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
|
||||||
|
List<Flower> flowerVase = new ArrayList<>();
|
||||||
|
flowers.stream()
|
||||||
|
.filter(f -> f.getPetals() > 10)
|
||||||
|
.forEachOrdered(flowerVase::add);
|
||||||
|
assertEquals(flowerVase.size() + 1, flowers.size());
|
||||||
|
assertFalse(flowerVase.containsAll(flowers));
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
|
||||||
|
List<Flower> target = new ArrayList<>();
|
||||||
|
Optional.ofNullable(flowers)
|
||||||
|
.ifPresent(target::addAll);
|
||||||
|
assertNotNull(target);
|
||||||
|
assertEquals(target.size(), 3);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.list.removefirst;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RemoveFirstElementUnitTest {
|
||||||
|
|
||||||
|
private List<String> list = new ArrayList<>();
|
||||||
|
private LinkedList<String> linkedList = new LinkedList<>();
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init() {
|
||||||
|
|
||||||
|
list.add("cat");
|
||||||
|
list.add("dog");
|
||||||
|
list.add("pig");
|
||||||
|
list.add("cow");
|
||||||
|
list.add("goat");
|
||||||
|
|
||||||
|
linkedList.add("cat");
|
||||||
|
linkedList.add("dog");
|
||||||
|
linkedList.add("pig");
|
||||||
|
linkedList.add("cow");
|
||||||
|
linkedList.add("goat");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_whenRemoveFirst_thenRemoved() {
|
||||||
|
list.remove(0);
|
||||||
|
|
||||||
|
assertThat(list, hasSize(4));
|
||||||
|
assertThat(list, not(contains("cat")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
|
||||||
|
|
||||||
|
linkedList.removeFirst();
|
||||||
|
|
||||||
|
assertThat(linkedList, hasSize(4));
|
||||||
|
assertThat(linkedList, not(contains("cat")));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -28,3 +28,5 @@
|
|||||||
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
||||||
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
||||||
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
|
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
|
||||||
|
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
|
||||||
|
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
|
||||||
|
59
core-java-persistence/pom.xml
Normal file
59
core-java-persistence/pom.xml
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
<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.core-java-persistence</groupId>
|
||||||
|
<artifactId>core-java-persistence</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>core-java-persistence</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.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj-core.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>${h2database.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-dbcp2</artifactId>
|
||||||
|
<version>${commons-dbcp2.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.zaxxer</groupId>
|
||||||
|
<artifactId>HikariCP</artifactId>
|
||||||
|
<version>${HikariCP.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mchange</groupId>
|
||||||
|
<artifactId>c3p0</artifactId>
|
||||||
|
<version>${c3p0.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-persistence</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
<properties>
|
||||||
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
<h2database.version>1.4.197</h2database.version>
|
||||||
|
<commons-dbcp2.version>2.4.0</commons-dbcp2.version>
|
||||||
|
<HikariCP.version>3.2.0</HikariCP.version>
|
||||||
|
<c3p0.version>0.9.5.2</c3p0.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
@ -0,0 +1,92 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class BasicConnectionPool implements ConnectionPool {
|
||||||
|
|
||||||
|
private final String url;
|
||||||
|
private final String user;
|
||||||
|
private final String password;
|
||||||
|
private final List<Connection> connectionPool;
|
||||||
|
private final List<Connection> usedConnections = new ArrayList<>();
|
||||||
|
private static final int INITIAL_POOL_SIZE = 10;
|
||||||
|
private final int MAX_POOL_SIZE = 20;
|
||||||
|
|
||||||
|
public static BasicConnectionPool create(String url, String user, String password) throws SQLException {
|
||||||
|
List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE);
|
||||||
|
for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
|
||||||
|
pool.add(createConnection(url, user, password));
|
||||||
|
}
|
||||||
|
return new BasicConnectionPool(url, user, password, pool);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) {
|
||||||
|
this.url = url;
|
||||||
|
this.user = user;
|
||||||
|
this.password = password;
|
||||||
|
this.connectionPool = connectionPool;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Connection getConnection() throws SQLException {
|
||||||
|
if (connectionPool.isEmpty()) {
|
||||||
|
if (usedConnections.size() < MAX_POOL_SIZE) {
|
||||||
|
connectionPool.add(createConnection(url, user, password));
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("Maximum pool size reached, no available connections!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection connection = connectionPool.remove(connectionPool.size() - 1);
|
||||||
|
usedConnections.add(connection);
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean releaseConnection(Connection connection) {
|
||||||
|
connectionPool.add(connection);
|
||||||
|
return usedConnections.remove(connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Connection createConnection(String url, String user, String password) throws SQLException {
|
||||||
|
return DriverManager.getConnection(url, user, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getSize() {
|
||||||
|
return connectionPool.size() + usedConnections.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Connection> getConnectionPool() {
|
||||||
|
return connectionPool;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUrl() {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getUser() {
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shutdown() throws SQLException {
|
||||||
|
usedConnections.forEach(this::releaseConnection);
|
||||||
|
for (Connection c : connectionPool) {
|
||||||
|
c.close();
|
||||||
|
}
|
||||||
|
connectionPool.clear();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import com.mchange.v2.c3p0.ComboPooledDataSource;
|
||||||
|
import java.beans.PropertyVetoException;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class C3poDataSource {
|
||||||
|
|
||||||
|
private static final ComboPooledDataSource cpds = new ComboPooledDataSource();
|
||||||
|
|
||||||
|
static {
|
||||||
|
try {
|
||||||
|
cpds.setDriverClass("org.h2.Driver");
|
||||||
|
cpds.setJdbcUrl("jdbc:h2:mem:test");
|
||||||
|
cpds.setUser("user");
|
||||||
|
cpds.setPassword("password");
|
||||||
|
} catch (PropertyVetoException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection getConnection() throws SQLException {
|
||||||
|
return cpds.getConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private C3poDataSource(){}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface ConnectionPool {
|
||||||
|
|
||||||
|
Connection getConnection() throws SQLException;
|
||||||
|
|
||||||
|
boolean releaseConnection(Connection connection);
|
||||||
|
|
||||||
|
List<Connection> getConnectionPool();
|
||||||
|
|
||||||
|
int getSize();
|
||||||
|
|
||||||
|
String getUrl();
|
||||||
|
|
||||||
|
String getUser();
|
||||||
|
|
||||||
|
String getPassword();
|
||||||
|
|
||||||
|
void shutdown() throws SQLException;;
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import org.apache.commons.dbcp2.BasicDataSource;
|
||||||
|
|
||||||
|
public class DBCPDataSource {
|
||||||
|
|
||||||
|
private static final BasicDataSource ds = new BasicDataSource();
|
||||||
|
|
||||||
|
static {
|
||||||
|
ds.setUrl("jdbc:h2:mem:test");
|
||||||
|
ds.setUsername("user");
|
||||||
|
ds.setPassword("password");
|
||||||
|
ds.setMinIdle(5);
|
||||||
|
ds.setMaxIdle(10);
|
||||||
|
ds.setMaxOpenPreparedStatements(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection getConnection() throws SQLException {
|
||||||
|
return ds.getConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private DBCPDataSource(){}
|
||||||
|
}
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import com.zaxxer.hikari.HikariConfig;
|
||||||
|
import com.zaxxer.hikari.HikariDataSource;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class HikariCPDataSource {
|
||||||
|
|
||||||
|
private static final HikariConfig config = new HikariConfig();
|
||||||
|
private static final HikariDataSource ds;
|
||||||
|
|
||||||
|
static {
|
||||||
|
config.setJdbcUrl("jdbc:h2:mem:test");
|
||||||
|
config.setUsername("user");
|
||||||
|
config.setPassword("password");
|
||||||
|
config.addDataSourceProperty("cachePrepStmts", "true");
|
||||||
|
config.addDataSourceProperty("prepStmtCacheSize", "250");
|
||||||
|
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
|
||||||
|
ds = new HikariDataSource(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection getConnection() throws SQLException {
|
||||||
|
return ds.getConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
private HikariCPDataSource(){}
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.fail;
|
||||||
|
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BasicConnectionPoolUnitTest {
|
||||||
|
|
||||||
|
private static ConnectionPool connectionPool;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpBasicConnectionPoolInstance() throws SQLException {
|
||||||
|
connectionPool = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenCalledgetConnection_thenCorrect() throws Exception {
|
||||||
|
assertTrue(connectionPool.getConnection().isValid(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenCalledreleaseConnection_thenCorrect() throws Exception {
|
||||||
|
Connection connection = connectionPool.getConnection();
|
||||||
|
assertThat(connectionPool.releaseConnection(connection)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenCalledgetUrl_thenCorrect() {
|
||||||
|
assertThat(connectionPool.getUrl()).isEqualTo("jdbc:h2:mem:test");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenCalledgetUser_thenCorrect() {
|
||||||
|
assertThat(connectionPool.getUser()).isEqualTo("user");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenCalledgetPassword_thenCorrect() {
|
||||||
|
assertThat(connectionPool.getPassword()).isEqualTo("password");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = RuntimeException.class)
|
||||||
|
public void givenBasicConnectionPoolInstance_whenAskedForMoreThanMax_thenError() throws Exception {
|
||||||
|
// this test needs to be independent so it doesn't share the same connection pool as other tests
|
||||||
|
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
|
||||||
|
final int MAX_POOL_SIZE = 20;
|
||||||
|
for (int i = 0; i < MAX_POOL_SIZE + 1; i++) {
|
||||||
|
cp.getConnection();
|
||||||
|
}
|
||||||
|
fail();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBasicConnectionPoolInstance_whenSutdown_thenEmpty() throws Exception {
|
||||||
|
ConnectionPool cp = BasicConnectionPool.create("jdbc:h2:mem:test", "user", "password");
|
||||||
|
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(10);
|
||||||
|
|
||||||
|
((BasicConnectionPool) cp).shutdown();
|
||||||
|
assertThat(((BasicConnectionPool)cp).getSize()).isEqualTo(0);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class C3poDataSourceUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenC3poDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
|
||||||
|
assertTrue(C3poDataSource.getConnection().isValid(1));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DBCPDataSourceUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDBCPDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
|
||||||
|
assertTrue(DBCPDataSource.getConnection().isValid(1));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.connectionpool;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class HikariCPDataSourceUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHikariDataSourceClass_whenCalledgetConnection_thenCorrect() throws SQLException {
|
||||||
|
assertTrue(HikariCPDataSource.getConnection().isValid(1));
|
||||||
|
}
|
||||||
|
}
|
@ -163,3 +163,8 @@
|
|||||||
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
|
||||||
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
|
||||||
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
|
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
|
||||||
|
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
|
||||||
|
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||||
|
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
|
||||||
|
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||||
|
- [Exception Handling in Java](http://www.baeldung.com/java-exceptions)
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
<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>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>core-java</artifactId>
|
<artifactId>core-java</artifactId>
|
||||||
@ -73,9 +73,10 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>${assertj.version}</version>
|
<version>${assertj-core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-codec</groupId>
|
<groupId>commons-codec</groupId>
|
||||||
<artifactId>commons-codec</artifactId>
|
<artifactId>commons-codec</artifactId>
|
||||||
@ -146,6 +147,30 @@
|
|||||||
<artifactId>icu4j</artifactId>
|
<artifactId>icu4j</artifactId>
|
||||||
<version>${icu4j.version}</version>
|
<version>${icu4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<!-- Mime Type Resolution Libraries -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.tika</groupId>
|
||||||
|
<artifactId>tika-core</artifactId>
|
||||||
|
<version>${tika.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>net.sf.jmimemagic</groupId>
|
||||||
|
<artifactId>jmimemagic</artifactId>
|
||||||
|
<version>${jmime-magic.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- instrumentation -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.javassist</groupId>
|
||||||
|
<artifactId>javassist</artifactId>
|
||||||
|
<version>${javaassist.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun</groupId>
|
||||||
|
<artifactId>tools</artifactId>
|
||||||
|
<version>1.8.0</version>
|
||||||
|
<scope>system</scope>
|
||||||
|
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -301,7 +326,7 @@
|
|||||||
</arguments>
|
</arguments>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
@ -348,6 +373,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.codehaus.mojo</groupId>
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
<artifactId>exec-maven-plugin</artifactId>
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>${exec-maven-plugin.version}</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>run-benchmarks</id>
|
<id>run-benchmarks</id>
|
||||||
@ -372,9 +398,115 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</profile>
|
</profile>
|
||||||
|
|
||||||
|
<!-- java instrumentation profiles to build jars -->
|
||||||
|
<profile>
|
||||||
|
<id>buildAgentLoader</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<classifier>agentLoader</classifier>
|
||||||
|
<classesDirectory>target/classes</classesDirectory>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<addClasspath>true</addClasspath>
|
||||||
|
</manifest>
|
||||||
|
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||||
|
</archive>
|
||||||
|
|
||||||
|
<includes>
|
||||||
|
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
|
||||||
|
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
<profile>
|
||||||
|
<id>buildApplication</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<classifier>application</classifier>
|
||||||
|
<classesDirectory>target/classes</classesDirectory>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<addClasspath>true</addClasspath>
|
||||||
|
</manifest>
|
||||||
|
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||||
|
</archive>
|
||||||
|
|
||||||
|
<includes>
|
||||||
|
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
|
||||||
|
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
|
||||||
|
<include>com/baeldung/instrumentation/application/Launcher.class</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
<profile>
|
||||||
|
<id>buildAgent</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<classifier>agent</classifier>
|
||||||
|
<classesDirectory>target/classes</classesDirectory>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<addClasspath>true</addClasspath>
|
||||||
|
</manifest>
|
||||||
|
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
|
||||||
|
</archive>
|
||||||
|
|
||||||
|
<includes>
|
||||||
|
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
|
||||||
|
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
</profiles>
|
</profiles>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
||||||
<!-- marshalling -->
|
<!-- marshalling -->
|
||||||
<jackson.version>2.8.5</jackson.version>
|
<jackson.version>2.8.5</jackson.version>
|
||||||
<gson.version>2.8.2</gson.version>
|
<gson.version>2.8.2</gson.version>
|
||||||
@ -395,16 +527,18 @@
|
|||||||
<vavr.version>0.9.0</vavr.version>
|
<vavr.version>0.9.0</vavr.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj-core.version>3.10.0</assertj-core.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
<springframework.spring-web.version>4.3.4.RELEASE</springframework.spring-web.version>
|
||||||
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
|
<springframework.boot.spring-boot-starter.version>1.5.8.RELEASE</springframework.boot.spring-boot-starter.version>
|
||||||
|
|
||||||
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
<javamoney.moneta.version>1.1</javamoney.moneta.version>
|
||||||
<h2database.version>1.4.197</h2database.version>
|
<h2database.version>1.4.197</h2database.version>
|
||||||
<esapi.version>2.1.0.1</esapi.version>
|
<esapi.version>2.1.0.1</esapi.version>
|
||||||
<jmh-core.version>1.19</jmh-core.version>
|
<jmh-core.version>1.19</jmh-core.version>
|
||||||
|
|
||||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||||
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
<javax.mail.version>1.5.0-b01</javax.mail.version>
|
||||||
@ -412,7 +546,13 @@
|
|||||||
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
|
||||||
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
|
||||||
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
|
||||||
|
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||||
<icu4j.version>61.1</icu4j.version>
|
<icu4j.version>61.1</icu4j.version>
|
||||||
|
<!-- Mime Type Libraries -->
|
||||||
|
<tika.version>1.18</tika.version>
|
||||||
|
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||||
|
<!-- instrumentation -->
|
||||||
|
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.instrumentation.agent;
|
||||||
|
|
||||||
|
import javassist.CannotCompileException;
|
||||||
|
import javassist.ClassPool;
|
||||||
|
import javassist.CtClass;
|
||||||
|
import javassist.CtMethod;
|
||||||
|
import javassist.NotFoundException;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.instrument.ClassFileTransformer;
|
||||||
|
import java.lang.instrument.IllegalClassFormatException;
|
||||||
|
import java.security.ProtectionDomain;
|
||||||
|
|
||||||
|
public class AtmTransformer implements ClassFileTransformer {
|
||||||
|
|
||||||
|
private static Logger LOGGER = LoggerFactory.getLogger(AtmTransformer.class);
|
||||||
|
|
||||||
|
private static final String WITHDRAW_MONEY_METHOD = "withdrawMoney";
|
||||||
|
|
||||||
|
/** The internal form class name of the class to transform */
|
||||||
|
private String targetClassName;
|
||||||
|
/** The class loader of the class we want to transform */
|
||||||
|
private ClassLoader targetClassLoader;
|
||||||
|
|
||||||
|
public AtmTransformer(String targetClassName, ClassLoader targetClassLoader) {
|
||||||
|
this.targetClassName = targetClassName;
|
||||||
|
this.targetClassLoader = targetClassLoader;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
|
||||||
|
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
|
||||||
|
byte[] byteCode = classfileBuffer;
|
||||||
|
|
||||||
|
String finalTargetClassName = this.targetClassName.replaceAll("\\.", "/"); //replace . with /
|
||||||
|
if (!className.equals(finalTargetClassName)) {
|
||||||
|
return byteCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (className.equals(finalTargetClassName) && loader.equals(targetClassLoader)) {
|
||||||
|
LOGGER.info("[Agent] Transforming class MyAtm");
|
||||||
|
try {
|
||||||
|
ClassPool cp = ClassPool.getDefault();
|
||||||
|
CtClass cc = cp.get(targetClassName);
|
||||||
|
CtMethod m = cc.getDeclaredMethod(WITHDRAW_MONEY_METHOD);
|
||||||
|
m.addLocalVariable("startTime", CtClass.longType);
|
||||||
|
m.insertBefore("startTime = System.currentTimeMillis();");
|
||||||
|
|
||||||
|
StringBuilder endBlock = new StringBuilder();
|
||||||
|
|
||||||
|
m.addLocalVariable("endTime", CtClass.longType);
|
||||||
|
m.addLocalVariable("opTime", CtClass.longType);
|
||||||
|
endBlock.append("endTime = System.currentTimeMillis();");
|
||||||
|
endBlock.append("opTime = (endTime-startTime)/1000;");
|
||||||
|
|
||||||
|
endBlock.append("LOGGER.info(\"[Application] Withdrawal operation completed in:\" + opTime + \" seconds!\");");
|
||||||
|
|
||||||
|
m.insertAfter(endBlock.toString());
|
||||||
|
|
||||||
|
byteCode = cc.toBytecode();
|
||||||
|
cc.detach();
|
||||||
|
} catch (NotFoundException | CannotCompileException | IOException e) {
|
||||||
|
LOGGER.error("Exception", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return byteCode;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,59 @@
|
|||||||
|
package com.baeldung.instrumentation.agent;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.lang.instrument.Instrumentation;
|
||||||
|
|
||||||
|
public class MyInstrumentationAgent {
|
||||||
|
private static Logger LOGGER = LoggerFactory.getLogger(MyInstrumentationAgent.class);
|
||||||
|
|
||||||
|
public static void premain(String agentArgs, Instrumentation inst) {
|
||||||
|
LOGGER.info("[Agent] In premain method");
|
||||||
|
|
||||||
|
String className = "com.baeldung.instrumentation.application.MyAtm";
|
||||||
|
transformClass(className,inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void agentmain(String agentArgs, Instrumentation inst) {
|
||||||
|
LOGGER.info("[Agent] In agentmain method");
|
||||||
|
|
||||||
|
String className = "com.baeldung.instrumentation.application.MyAtm";
|
||||||
|
transformClass(className,inst);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void transformClass(String className, Instrumentation instrumentation) {
|
||||||
|
Class<?> targetCls = null;
|
||||||
|
ClassLoader targetClassLoader = null;
|
||||||
|
// see if we can get the class using forName
|
||||||
|
try {
|
||||||
|
targetCls = Class.forName(className);
|
||||||
|
targetClassLoader = targetCls.getClassLoader();
|
||||||
|
transform(targetCls, targetClassLoader, instrumentation);
|
||||||
|
return;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOGGER.error("Class [{}] not found with Class.forName");
|
||||||
|
}
|
||||||
|
// otherwise iterate all loaded classes and find what we want
|
||||||
|
for(Class<?> clazz: instrumentation.getAllLoadedClasses()) {
|
||||||
|
if(clazz.getName().equals(className)) {
|
||||||
|
targetCls = clazz;
|
||||||
|
targetClassLoader = targetCls.getClassLoader();
|
||||||
|
transform(targetCls, targetClassLoader, instrumentation);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new RuntimeException("Failed to find class [" + className + "]");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void transform(Class<?> clazz, ClassLoader classLoader, Instrumentation instrumentation) {
|
||||||
|
AtmTransformer dt = new AtmTransformer(clazz.getName(), classLoader);
|
||||||
|
instrumentation.addTransformer(dt, true);
|
||||||
|
try {
|
||||||
|
instrumentation.retransformClasses(clazz);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("Transform failed for class: [" + clazz.getName() + "]", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.instrumentation.application;
|
||||||
|
|
||||||
|
import com.sun.tools.attach.VirtualMachine;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by adi on 6/10/18.
|
||||||
|
*/
|
||||||
|
public class AgentLoader {
|
||||||
|
private static Logger LOGGER = LoggerFactory.getLogger(AgentLoader.class);
|
||||||
|
|
||||||
|
public static void run(String[] args) {
|
||||||
|
String agentFilePath = "/home/adi/Desktop/agent-1.0.0-jar-with-dependencies.jar";
|
||||||
|
String applicationName = "MyAtmApplication";
|
||||||
|
|
||||||
|
//iterate all jvms and get the first one that matches our application name
|
||||||
|
Optional<String> jvmProcessOpt = Optional.ofNullable(VirtualMachine.list()
|
||||||
|
.stream()
|
||||||
|
.filter(jvm -> {
|
||||||
|
LOGGER.info("jvm:{}", jvm.displayName());
|
||||||
|
return jvm.displayName().contains(applicationName);
|
||||||
|
})
|
||||||
|
.findFirst().get().id());
|
||||||
|
|
||||||
|
if(!jvmProcessOpt.isPresent()) {
|
||||||
|
LOGGER.error("Target Application not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
File agentFile = new File(agentFilePath);
|
||||||
|
try {
|
||||||
|
String jvmPid = jvmProcessOpt.get();
|
||||||
|
LOGGER.info("Attaching to target JVM with PID: " + jvmPid);
|
||||||
|
VirtualMachine jvm = VirtualMachine.attach(jvmPid);
|
||||||
|
jvm.loadAgent(agentFile.getAbsolutePath());
|
||||||
|
jvm.detach();
|
||||||
|
LOGGER.info("Attached to target JVM and loaded Java agent successfully");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.instrumentation.application;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by adi on 6/14/18.
|
||||||
|
*/
|
||||||
|
public class Launcher {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
if(args[0].equals("StartMyAtmApplication")) {
|
||||||
|
new MyAtmApplication().run(args);
|
||||||
|
} else if(args[0].equals("LoadAgent")) {
|
||||||
|
new AgentLoader().run(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.instrumentation.application;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Created by adi on 6/11/18.
|
||||||
|
*/
|
||||||
|
public class MyAtm {
|
||||||
|
private static Logger LOGGER = LoggerFactory.getLogger(MyAtm.class);
|
||||||
|
|
||||||
|
private static final int account = 10;
|
||||||
|
|
||||||
|
public static void withdrawMoney(int amount) throws InterruptedException {
|
||||||
|
Thread.sleep(2000l); //processing going on here
|
||||||
|
LOGGER.info("[Application] Successful Withdrawal of [{}] units!", amount);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.instrumentation.application;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class MyAtmApplication {
|
||||||
|
|
||||||
|
private static Logger LOGGER = LoggerFactory.getLogger(MyAtmApplication.class);
|
||||||
|
|
||||||
|
public static void run(String[] args) throws Exception {
|
||||||
|
LOGGER.info("[Application] Starting ATM application");
|
||||||
|
MyAtm.withdrawMoney(Integer.parseInt(args[2]));
|
||||||
|
|
||||||
|
Thread.sleep(Long.valueOf(args[1]));
|
||||||
|
|
||||||
|
MyAtm.withdrawMoney(Integer.parseInt(args[3]));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
5
core-java/src/main/resources/META-INF/MANIFEST.MF
Normal file
5
core-java/src/main/resources/META-INF/MANIFEST.MF
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
|
||||||
|
Can-Redefine-Classes: true
|
||||||
|
Can-Retransform-Classes: true
|
||||||
|
Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
|
||||||
|
Main-Class: com.baeldung.instrumentation.application.Launcher
|
13
core-java/src/main/resources/log4j2.xml
Normal file
13
core-java/src/main/resources/log4j2.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="Console" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="debug">
|
||||||
|
<AppenderRef ref="Console"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
BIN
core-java/src/main/resources/product.png
Normal file
BIN
core-java/src/main/resources/product.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 54 KiB |
@ -0,0 +1,131 @@
|
|||||||
|
package com.baeldung.java.mimetype;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.FileNameMap;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import javax.activation.MimetypesFileTypeMap;
|
||||||
|
|
||||||
|
import org.apache.tika.Tika;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import net.sf.jmimemagic.Magic;
|
||||||
|
import net.sf.jmimemagic.MagicException;
|
||||||
|
import net.sf.jmimemagic.MagicMatch;
|
||||||
|
import net.sf.jmimemagic.MagicMatchNotFoundException;
|
||||||
|
import net.sf.jmimemagic.MagicParseException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test class demonstrating various strategies to resolve MIME type of a file.
|
||||||
|
* @author tritty
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class MimeTypeUnitTest {
|
||||||
|
/**
|
||||||
|
* Expected Ouput.
|
||||||
|
*/
|
||||||
|
public static final String PNG_EXT = "image/png";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The location of the file.
|
||||||
|
*/
|
||||||
|
public static final String FILE_LOC = "src/test/resources/product.png";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method, demonstrating usage in Java 7.
|
||||||
|
*
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingJava7_thenSuccess() throws IOException {
|
||||||
|
final Path path = new File(FILE_LOC).toPath();
|
||||||
|
final String mimeType = Files.probeContentType(path);
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating the usage of URLConnection to resolve MIME type.
|
||||||
|
*
|
||||||
|
* @throws MalformedURLException
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingGetContentType_thenSuccess() throws MalformedURLException, IOException {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final URLConnection connection = file.toURL()
|
||||||
|
.openConnection();
|
||||||
|
final String mimeType = connection.getContentType();
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating the usage of URLConnection to resolve MIME type.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingGuessContentTypeFromName_thenSuccess() {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final String mimeType = URLConnection.guessContentTypeFromName(file.getName());
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating the usage of FileNameMap from URLConnection
|
||||||
|
* to resolve MIME type of a file.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingGetFileNameMap_thenSuccess() {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final FileNameMap fileNameMap = URLConnection.getFileNameMap();
|
||||||
|
final String mimeType = fileNameMap.getContentTypeFor(file.getName());
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating the usage of MimeTypesFileTypeMap for resolution of
|
||||||
|
* MIME type.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingMimeTypesFileTypeMap_thenSuccess() {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
|
||||||
|
final String mimeType = fileTypeMap.getContentType(file.getName());
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating usage of jMimeMagic.
|
||||||
|
*
|
||||||
|
* @throws MagicParseException
|
||||||
|
* @throws MagicMatchNotFoundException
|
||||||
|
* @throws MagicException
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingJmimeMagic_thenSuccess() throws MagicParseException, MagicMatchNotFoundException, MagicException {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final Magic magic = new Magic();
|
||||||
|
final MagicMatch match = magic.getMagicMatch(file, false);
|
||||||
|
assertEquals(match.getMimeType(), PNG_EXT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test method demonstrating usage of Apache Tika.
|
||||||
|
*
|
||||||
|
* @throws IOException
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void whenUsingTika_thenSuccess() throws IOException {
|
||||||
|
final File file = new File(FILE_LOC);
|
||||||
|
final Tika tika = new Tika();
|
||||||
|
final String mimeType = tika.detect(file);
|
||||||
|
assertEquals(mimeType, PNG_EXT);
|
||||||
|
}
|
||||||
|
}
|
1588
core-java/src/test/resources/META-INF/mime.types
Normal file
1588
core-java/src/test/resources/META-INF/mime.types
Normal file
File diff suppressed because it is too large
Load Diff
BIN
core-java/src/test/resources/product.png
Normal file
BIN
core-java/src/test/resources/product.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 54 KiB |
@ -34,3 +34,5 @@
|
|||||||
- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
|
- [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security)
|
||||||
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
|
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
|
||||||
- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum)
|
- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum)
|
||||||
|
- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project)
|
||||||
|
- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection)
|
||||||
|
113
geotools/pom.xml
113
geotools/pom.xml
@ -1,61 +1,62 @@
|
|||||||
<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"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
<modelVersion>4.0.0</modelVersion>
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<groupId>com.baeldung</groupId>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>geotools</artifactId>
|
<artifactId>geotools</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<name>geotools</name>
|
<name>geotools</name>
|
||||||
<url>http://maven.apache.org</url>
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.geotools</groupId>
|
<groupId>org.geotools</groupId>
|
||||||
<artifactId>gt-shapefile</artifactId>
|
<artifactId>gt-shapefile</artifactId>
|
||||||
<version>${geotools-shapefile.version}</version>
|
<version>${geotools-shapefile.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.geotools</groupId>
|
<groupId>org.geotools</groupId>
|
||||||
<artifactId>gt-epsg-hsql</artifactId>
|
<artifactId>gt-epsg-hsql</artifactId>
|
||||||
<version>${geotools.version}</version>
|
<version>${geotools.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.geotools</groupId>
|
<groupId>org.geotools</groupId>
|
||||||
<artifactId>gt-swing</artifactId>
|
<artifactId>gt-swing</artifactId>
|
||||||
<version>${geotools-swing.version}</version>
|
<version>${geotools-swing.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
<repository>
|
||||||
<id>maven2-repository.dev.java.net</id>
|
<id>maven2-repository.dev.java.net</id>
|
||||||
<name>Java.net repository</name>
|
<name>Java.net repository</name>
|
||||||
<url>http://download.java.net/maven/2</url>
|
<url>http://download.java.net/maven/2</url>
|
||||||
</repository>
|
</repository>
|
||||||
<repository>
|
<repository>
|
||||||
<id>osgeo</id>
|
<id>osgeo</id>
|
||||||
<name>Open Source Geospatial Foundation Repository</name>
|
<name>Open Source Geospatial Foundation Repository</name>
|
||||||
<url>http://download.osgeo.org/webdav/geotools/</url>
|
<url>http://download.osgeo.org/webdav/geotools/</url>
|
||||||
</repository>
|
</repository>
|
||||||
<repository>
|
<repository>
|
||||||
<snapshots>
|
<snapshots>
|
||||||
<enabled>true</enabled>
|
<enabled>true</enabled>
|
||||||
</snapshots>
|
</snapshots>
|
||||||
<id>opengeo</id>
|
<id>opengeo</id>
|
||||||
<name>OpenGeo Maven Repository</name>
|
<name>OpenGeo Maven Repository</name>
|
||||||
<url>http://repo.opengeo.org</url>
|
<url>http://repo.opengeo.org</url>
|
||||||
</repository>
|
</repository>
|
||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<geotools.version>15.2</geotools.version>
|
||||||
|
<geotools-swing.version>15.2</geotools-swing.version>
|
||||||
|
<geotools-shapefile.version>15.2</geotools-shapefile.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<geotools.version>15.2</geotools.version>
|
|
||||||
<geotools-swing.version>15.2</geotools-swing.version>
|
|
||||||
<geotools-shapefile.version>15.2</geotools-shapefile.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
</project>
|
||||||
|
2
google-web-toolkit/README.md
Normal file
2
google-web-toolkit/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Introduction to GWT](http://www.baeldung.com/gwt)
|
@ -6,10 +6,16 @@
|
|||||||
<!-- POM file generated with GWT webAppCreator -->
|
<!-- POM file generated with GWT webAppCreator -->
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>google-web-toolkit</artifactId>
|
<artifactId>google_web_toolkit</artifactId>
|
||||||
<packaging>war</packaging>
|
<packaging>war</packaging>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- ensure all GWT deps use the same version (unless overridden) -->
|
<!-- ensure all GWT deps use the same version (unless overridden) -->
|
||||||
|
@ -22,6 +22,8 @@
|
|||||||
<!-- Specify the app entry point class. -->
|
<!-- Specify the app entry point class. -->
|
||||||
<entry-point class='com.baeldung.client.Google_web_toolkit'/>
|
<entry-point class='com.baeldung.client.Google_web_toolkit'/>
|
||||||
|
|
||||||
|
<set-property name="user.agent" value="gecko1_8"/>
|
||||||
|
|
||||||
<!-- Specify the paths for translatable code -->
|
<!-- Specify the paths for translatable code -->
|
||||||
<source path='client'/>
|
<source path='client'/>
|
||||||
<source path='shared'/>
|
<source path='shared'/>
|
||||||
|
@ -5,8 +5,6 @@
|
|||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>hibernate5</artifactId>
|
<artifactId>hibernate5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<name>hibernate5</name>
|
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -59,9 +57,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<!-- Maven plugins -->
|
|
||||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
|
||||||
<hibernate.version>5.3.2.Final</hibernate.version>
|
<hibernate.version>5.3.2.Final</hibernate.version>
|
||||||
<mysql.version>6.0.6</mysql.version>
|
<mysql.version>6.0.6</mysql.version>
|
||||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||||
|
13
hibernate5/src/main/resources/logback.xml
Normal file
13
hibernate5/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern> %date [%thread] %-5level %logger{36} - %message%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -347,7 +347,7 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</pluginManagement>
|
</pluginManagement>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<!-- <plugin>
|
||||||
<groupId>com.github.ekryd.sortpom</groupId>
|
<groupId>com.github.ekryd.sortpom</groupId>
|
||||||
<artifactId>sortpom-maven-plugin</artifactId>
|
<artifactId>sortpom-maven-plugin</artifactId>
|
||||||
<version>${sortpom-maven-plugin.version}</version>
|
<version>${sortpom-maven-plugin.version}</version>
|
||||||
@ -367,7 +367,7 @@
|
|||||||
<keepBlankLines>true</keepBlankLines>
|
<keepBlankLines>true</keepBlankLines>
|
||||||
<expandEmptyElements>false</expandEmptyElements>
|
<expandEmptyElements>false</expandEmptyElements>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin> -->
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>com.spotify</groupId>
|
<groupId>com.spotify</groupId>
|
||||||
<artifactId>docker-maven-plugin</artifactId>
|
<artifactId>docker-maven-plugin</artifactId>
|
||||||
|
88
jnosql/jnosql-artemis/pom.xml
Normal file
88
jnosql/jnosql-artemis/pom.xml
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>jnosql-artemis</artifactId>
|
||||||
|
<packaging>war</packaging>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
|
||||||
|
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>${artifactId}</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||||
|
<artifactId>liberty-maven-plugin</artifactId>
|
||||||
|
<version>${liberty-maven-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<assemblyArtifact>
|
||||||
|
<groupId>io.openliberty</groupId>
|
||||||
|
<artifactId>openliberty-webProfile8</artifactId>
|
||||||
|
<version>RELEASE</version>
|
||||||
|
<type>zip</type>
|
||||||
|
</assemblyArtifact>
|
||||||
|
<installAppPackages>project</installAppPackages>
|
||||||
|
<looseApplication>true</looseApplication>
|
||||||
|
<configFile>src/main/liberty/config/server.xml</configFile>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>install-server</id>
|
||||||
|
<phase>prepare-package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>install-server</goal>
|
||||||
|
<goal>create-server</goal>
|
||||||
|
<goal>install-feature</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>install-apps</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>install-apps</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax</groupId>
|
||||||
|
<artifactId>javaee-web-api</artifactId>
|
||||||
|
<version>8.0</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.artemis</groupId>
|
||||||
|
<artifactId>artemis-configuration</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.artemis</groupId>
|
||||||
|
<artifactId>artemis-document</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>mongodb-driver</artifactId>
|
||||||
|
<version>${jnosql.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import javax.enterprise.context.Initialized;
|
||||||
|
import javax.enterprise.event.Observes;
|
||||||
|
import javax.ws.rs.ApplicationPath;
|
||||||
|
import javax.ws.rs.core.Application;
|
||||||
|
|
||||||
|
@ApplicationPath("")
|
||||||
|
public class AppConfig extends Application {
|
||||||
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import de.flapdoodle.embed.mongo.MongodExecutable;
|
||||||
|
import de.flapdoodle.embed.mongo.MongodProcess;
|
||||||
|
import de.flapdoodle.embed.mongo.MongodStarter;
|
||||||
|
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
|
||||||
|
import de.flapdoodle.embed.mongo.config.Net;
|
||||||
|
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||||
|
import de.flapdoodle.embed.process.runtime.Network;
|
||||||
|
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.context.Destroyed;
|
||||||
|
import javax.enterprise.context.Initialized;
|
||||||
|
import javax.enterprise.event.Observes;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
public class EmbeddedMongoDBSetup {
|
||||||
|
|
||||||
|
private static final String MONGODB_HOST = "localhost";
|
||||||
|
private static final int MONGODB_PORT = 27019;
|
||||||
|
|
||||||
|
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
|
||||||
|
private static MongodExecutable _mongodExe;
|
||||||
|
private static MongodProcess _mongod;
|
||||||
|
|
||||||
|
public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
|
||||||
|
try {
|
||||||
|
System.out.println("Starting Embedded MongoDB");
|
||||||
|
initdb();
|
||||||
|
System.out.println("Embedded MongoDB started");
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println("Embedded MongoDB starting error !!");
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initdb() throws IOException {
|
||||||
|
_mongodExe = starter.prepare(new MongodConfigBuilder()
|
||||||
|
.version(Version.Main.DEVELOPMENT)
|
||||||
|
.net(new Net(MONGODB_HOST, MONGODB_PORT, Network.localhostIsIPv6()))
|
||||||
|
.build());
|
||||||
|
_mongod = _mongodExe.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void destroy(@Observes @Destroyed(ApplicationScoped.class) Object init) {
|
||||||
|
System.out.println("Stopping Embedded MongoDB");
|
||||||
|
_mongod.stop();
|
||||||
|
_mongodExe.stop();
|
||||||
|
System.out.println("Embedded MongoDB stopped !");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import org.jnosql.artemis.ConfigurationUnit;
|
||||||
|
import org.jnosql.diana.api.document.DocumentCollectionManager;
|
||||||
|
import org.jnosql.diana.api.document.DocumentCollectionManagerFactory;
|
||||||
|
import org.jnosql.diana.mongodb.document.MongoDBDocumentCollectionManager;
|
||||||
|
import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.enterprise.inject.Disposes;
|
||||||
|
import javax.enterprise.inject.Produces;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
public class EntityManagerProducer {
|
||||||
|
|
||||||
|
private static final String DATABASE = "todos";
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@ConfigurationUnit(name = "document")
|
||||||
|
private DocumentCollectionManagerFactory<MongoDBDocumentCollectionManager> managerFactory;
|
||||||
|
|
||||||
|
@Produces
|
||||||
|
public DocumentCollectionManager getEntityManager() {
|
||||||
|
return managerFactory.get(DATABASE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void close(@Disposes DocumentCollectionManager entityManager) {
|
||||||
|
entityManager.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import com.baeldung.jnosql.artemis.qualifier.Repo;
|
||||||
|
import org.jnosql.artemis.Database;
|
||||||
|
import org.jnosql.artemis.DatabaseType;
|
||||||
|
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
@Repo
|
||||||
|
public class RepositoryTodoManager implements TodoManager {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
@Database(DatabaseType.DOCUMENT)
|
||||||
|
private TodoRepository repository;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Todo add(Todo todo) {
|
||||||
|
return repository.save(todo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Todo get(String id) {
|
||||||
|
Optional<Todo> todo = repository.findById(id);
|
||||||
|
return todo.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Todo> getAll() {
|
||||||
|
return repository.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String id) {
|
||||||
|
repository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import com.baeldung.jnosql.artemis.qualifier.Template;
|
||||||
|
import org.jnosql.artemis.document.DocumentTemplate;
|
||||||
|
import org.jnosql.diana.api.document.DocumentQuery;
|
||||||
|
|
||||||
|
import javax.enterprise.context.ApplicationScoped;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
|
||||||
|
|
||||||
|
@ApplicationScoped
|
||||||
|
@Template
|
||||||
|
public class TemplateTodoManager implements TodoManager {
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
private DocumentTemplate documentTemplate;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Todo add(Todo todo) {
|
||||||
|
return documentTemplate.insert(todo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Todo get(String id) {
|
||||||
|
Optional<Todo> todo = documentTemplate.find(Todo.class, id);
|
||||||
|
return todo.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Todo> getAll() {
|
||||||
|
DocumentQuery query = select().from("Todo").build();
|
||||||
|
return documentTemplate.select(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void delete(String id) {
|
||||||
|
documentTemplate.delete(Todo.class, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import org.jnosql.artemis.Column;
|
||||||
|
import org.jnosql.artemis.Entity;
|
||||||
|
import org.jnosql.artemis.Id;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
public class Todo implements Serializable {
|
||||||
|
|
||||||
|
@Id("id")
|
||||||
|
public String id;
|
||||||
|
@Column
|
||||||
|
public String name;
|
||||||
|
@Column
|
||||||
|
public String description;
|
||||||
|
|
||||||
|
public Todo() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Todo(String id, String name, String description) {
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface TodoManager {
|
||||||
|
|
||||||
|
Todo add(Todo todo);
|
||||||
|
|
||||||
|
Todo get(String id);
|
||||||
|
|
||||||
|
List<Todo> getAll();
|
||||||
|
|
||||||
|
void delete(String id);
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import org.jnosql.artemis.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public interface TodoRepository extends Repository<Todo, String> {
|
||||||
|
List<Todo> findByName(String name);
|
||||||
|
List<Todo> findAll();
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.jnosql.artemis;
|
||||||
|
|
||||||
|
import com.baeldung.jnosql.artemis.qualifier.Repo;
|
||||||
|
import com.baeldung.jnosql.artemis.qualifier.Template;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import javax.ws.rs.*;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import javax.ws.rs.core.UriBuilder;
|
||||||
|
|
||||||
|
@Path("todos")
|
||||||
|
public class TodoResource {
|
||||||
|
|
||||||
|
/*
|
||||||
|
Use eiher @Template or @Repo
|
||||||
|
*/
|
||||||
|
@Inject
|
||||||
|
@Template
|
||||||
|
//@Repo
|
||||||
|
private TodoManager todoManager;
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public Response all() {
|
||||||
|
return Response.ok(todoManager.getAll()).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{id}")
|
||||||
|
@Produces(MediaType.APPLICATION_JSON)
|
||||||
|
public Response get(@PathParam("id") String id) {
|
||||||
|
Todo todo = todoManager.get(id);
|
||||||
|
return Response.ok(todo).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
@Consumes(MediaType.APPLICATION_JSON)
|
||||||
|
public Response add(Todo todo) {
|
||||||
|
Todo savedTodo = todoManager.add(todo);
|
||||||
|
System.out.println(savedTodo.id);
|
||||||
|
return Response.created(
|
||||||
|
UriBuilder.fromResource(this.getClass()).path(String.valueOf(savedTodo.id)).build())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.jnosql.artemis.qualifier;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target({ElementType.FIELD, ElementType.TYPE})
|
||||||
|
@Qualifier
|
||||||
|
public @interface Repo {
|
||||||
|
}
|
@ -0,0 +1,13 @@
|
|||||||
|
package com.baeldung.jnosql.artemis.qualifier;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Target({ElementType.FIELD, ElementType.TYPE})
|
||||||
|
@Qualifier
|
||||||
|
public @interface Template {
|
||||||
|
}
|
6
jnosql/jnosql-artemis/src/main/liberty/config/server.xml
Normal file
6
jnosql/jnosql-artemis/src/main/liberty/config/server.xml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
<server description="OpenLiberty Server">
|
||||||
|
<featureManager>
|
||||||
|
<feature>webProfile-8.0</feature>
|
||||||
|
</featureManager>
|
||||||
|
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
|
||||||
|
</server>
|
@ -0,0 +1,6 @@
|
|||||||
|
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
||||||
|
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
|
||||||
|
bean-discovery-mode="all">
|
||||||
|
</beans>
|
@ -0,0 +1,10 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"description": "The mongodb document configuration",
|
||||||
|
"name": "document",
|
||||||
|
"provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
|
||||||
|
"settings": {
|
||||||
|
"mongodb-server-host-1":"localhost:27019"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
10
jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
Normal file
10
jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"description": "The mongodb document configuration",
|
||||||
|
"name": "document",
|
||||||
|
"provider": "org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration",
|
||||||
|
"settings": {
|
||||||
|
"mongodb-server-host-1":"localhost:27019"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
93
jnosql/jnosql-diana/pom.xml
Normal file
93
jnosql/jnosql-diana/pom.xml
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>jnosql-diana</artifactId>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>exec-maven-plugin</artifactId>
|
||||||
|
<version>1.6.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>document</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.document.DocumentApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>column</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.column.ColumnFamilyApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>key</id>
|
||||||
|
<goals>
|
||||||
|
<goal>java</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<mainClass>com.baeldung.jnosql.diana.key.KeyValueApp</mainClass>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
|
||||||
|
<!--NoSQL Document oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-document</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>mongodb-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--NoSQL Column oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-column</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>cassandra-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!--NoSQL Key Value oriented-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>diana-key-value</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jnosql.diana</groupId>
|
||||||
|
<artifactId>hazelcast-driver</artifactId>
|
||||||
|
<version>0.0.5</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
</project>
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.jnosql.diana.column;
|
||||||
|
|
||||||
|
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
|
||||||
|
import org.jnosql.diana.api.column.*;
|
||||||
|
import org.jnosql.diana.cassandra.column.CassandraConfiguration;
|
||||||
|
|
||||||
|
public class ColumnFamilyApp {
|
||||||
|
|
||||||
|
private static final String KEY_SPACE = "myKeySpace";
|
||||||
|
private static final String COLUMN_FAMILY = "books";
|
||||||
|
|
||||||
|
public static void main(String... args) throws Exception {
|
||||||
|
|
||||||
|
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
|
||||||
|
|
||||||
|
ColumnConfiguration configuration = new CassandraConfiguration();
|
||||||
|
try(ColumnFamilyManagerFactory entityManagerFactory = configuration.get()) {
|
||||||
|
ColumnFamilyManager entityManager = entityManagerFactory.get(KEY_SPACE);
|
||||||
|
ColumnEntity columnEntity = ColumnEntity.of(COLUMN_FAMILY);
|
||||||
|
Column key = Columns.of("id", 10L);
|
||||||
|
Column name = Columns.of("name", "JNoSQL in Acion");
|
||||||
|
columnEntity.add(key);
|
||||||
|
columnEntity.add(name);
|
||||||
|
ColumnEntity saved = entityManager.insert(columnEntity);
|
||||||
|
System.out.println(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
|
||||||
|
EmbeddedCassandraServerHelper.stopEmbeddedCassandra();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,67 @@
|
|||||||
|
package com.baeldung.jnosql.diana.document;
|
||||||
|
|
||||||
|
import org.jnosql.diana.api.Settings;
|
||||||
|
import org.jnosql.diana.api.document.*;
|
||||||
|
import org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.delete;
|
||||||
|
import static org.jnosql.diana.api.document.query.DocumentQueryBuilder.select;
|
||||||
|
|
||||||
|
public class DocumentApp {
|
||||||
|
|
||||||
|
private static final String DB_NAME = "my-db";
|
||||||
|
private static final String DOCUMENT_COLLECTION = "books";
|
||||||
|
|
||||||
|
public static final String KEY_NAME = "_id";
|
||||||
|
|
||||||
|
DocumentConfiguration configuration = new MongoDBDocumentConfiguration();
|
||||||
|
|
||||||
|
public static void main(String... args) throws Exception {
|
||||||
|
MongoDbInit.startMongoDb();
|
||||||
|
|
||||||
|
DocumentApp app = new DocumentApp();
|
||||||
|
app.process();
|
||||||
|
|
||||||
|
MongoDbInit.stopMongoDb();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void process() {
|
||||||
|
|
||||||
|
Map<String, Object> map = new HashMap<>();
|
||||||
|
map.put("mongodb-server-host-1", "localhost:27017");
|
||||||
|
|
||||||
|
try (DocumentCollectionManagerFactory managerFactory = configuration.get(Settings.of(map));
|
||||||
|
DocumentCollectionManager manager = managerFactory.get(DB_NAME);) {
|
||||||
|
|
||||||
|
DocumentEntity documentEntity = DocumentEntity.of(DOCUMENT_COLLECTION);
|
||||||
|
documentEntity.add(Document.of(KEY_NAME, "100"));
|
||||||
|
documentEntity.add(Document.of("name", "JNoSQL in Action"));
|
||||||
|
documentEntity.add(Document.of("pages", 620));
|
||||||
|
|
||||||
|
//CREATE
|
||||||
|
DocumentEntity saved = manager.insert(documentEntity);
|
||||||
|
|
||||||
|
//READ
|
||||||
|
DocumentQuery query = select().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
|
||||||
|
List<DocumentEntity> entities = manager.select(query);
|
||||||
|
System.out.println(entities.get(0));
|
||||||
|
|
||||||
|
//UPDATE
|
||||||
|
saved.add(Document.of("author", "baeldung"));
|
||||||
|
DocumentEntity updated = manager.update(saved);
|
||||||
|
System.out.println(updated);
|
||||||
|
|
||||||
|
//DELETE
|
||||||
|
DocumentDeleteQuery deleteQuery = delete().from(DOCUMENT_COLLECTION).where(KEY_NAME).eq("100").build();
|
||||||
|
manager.delete(deleteQuery);
|
||||||
|
|
||||||
|
List<DocumentEntity> documentEntityList = manager.select(select().from(DOCUMENT_COLLECTION).build());
|
||||||
|
System.out.println(documentEntityList);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.jnosql.diana.document;
|
||||||
|
|
||||||
|
import de.flapdoodle.embed.mongo.MongodExecutable;
|
||||||
|
import de.flapdoodle.embed.mongo.MongodProcess;
|
||||||
|
import de.flapdoodle.embed.mongo.MongodStarter;
|
||||||
|
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
|
||||||
|
import de.flapdoodle.embed.mongo.config.Net;
|
||||||
|
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||||
|
import de.flapdoodle.embed.process.runtime.Network;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public abstract class MongoDbInit {
|
||||||
|
|
||||||
|
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
|
||||||
|
private static MongodExecutable _mongodExe;
|
||||||
|
private static MongodProcess _mongod;
|
||||||
|
|
||||||
|
public static void startMongoDb() throws IOException {
|
||||||
|
_mongodExe = starter.prepare(new MongodConfigBuilder()
|
||||||
|
.version(Version.Main.DEVELOPMENT)
|
||||||
|
.net(new Net("localhost", 27017, Network.localhostIsIPv6()))
|
||||||
|
.build());
|
||||||
|
_mongod = _mongodExe.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void stopMongoDb(){
|
||||||
|
_mongod.stop();
|
||||||
|
_mongodExe.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package com.baeldung.jnosql.diana.key;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class Book implements Serializable {
|
||||||
|
|
||||||
|
private String isbn;
|
||||||
|
private String name;
|
||||||
|
private String author;
|
||||||
|
private int pages;
|
||||||
|
|
||||||
|
public Book() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public Book(String isbn, String name, String author, int pages) {
|
||||||
|
this.isbn = isbn;
|
||||||
|
this.name = name;
|
||||||
|
this.author = author;
|
||||||
|
this.pages = pages;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIsbn() {
|
||||||
|
return isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsbn(String isbn) {
|
||||||
|
this.isbn = isbn;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAuthor() {
|
||||||
|
return author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAuthor(String author) {
|
||||||
|
this.author = author;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPages() {
|
||||||
|
return pages;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPages(int pages) {
|
||||||
|
this.pages = pages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Book{" +
|
||||||
|
"isbn='" + isbn + '\'' +
|
||||||
|
", name='" + name + '\'' +
|
||||||
|
", author='" + author + '\'' +
|
||||||
|
", pages=" + pages +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.jnosql.diana.key;
|
||||||
|
|
||||||
|
import com.hazelcast.core.Hazelcast;
|
||||||
|
import org.jnosql.diana.api.Value;
|
||||||
|
import org.jnosql.diana.api.key.BucketManager;
|
||||||
|
import org.jnosql.diana.api.key.BucketManagerFactory;
|
||||||
|
import org.jnosql.diana.api.key.KeyValueConfiguration;
|
||||||
|
import org.jnosql.diana.api.key.KeyValueEntity;
|
||||||
|
import org.jnosql.diana.hazelcast.key.HazelcastKeyValueConfiguration;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class KeyValueApp {
|
||||||
|
|
||||||
|
private static final String BUCKET_NAME = "books";
|
||||||
|
|
||||||
|
public static void main(String... args) throws Exception {
|
||||||
|
KeyValueConfiguration configuration = new HazelcastKeyValueConfiguration();
|
||||||
|
try (BucketManagerFactory managerFactory = configuration.get()) {
|
||||||
|
BucketManager manager = managerFactory.getBucketManager(BUCKET_NAME);
|
||||||
|
|
||||||
|
Book book = new Book("12345", "JNoSQL in Action", "baeldung", 420);
|
||||||
|
KeyValueEntity keyValueEntity = KeyValueEntity.of(book.getIsbn(), book);
|
||||||
|
manager.put(keyValueEntity);
|
||||||
|
|
||||||
|
Optional<Value> optionalValue = manager.get("12345");
|
||||||
|
Value value = optionalValue.get();
|
||||||
|
Book savedBook = value.get(Book.class);
|
||||||
|
System.out.println(savedBook);
|
||||||
|
}
|
||||||
|
Hazelcast.shutdownAll();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
cassandra-host-1=localhost
|
||||||
|
cassandra-port=9142
|
||||||
|
#cassandra-threads-number=2
|
||||||
|
cassandra-query-1=CREATE KEYSPACE IF NOT EXISTS myKeySpace WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
|
||||||
|
cassandra-query-2=CREATE COLUMNFAMILY IF NOT EXISTS myKeySpace.books (id bigint PRIMARY KEY, name text);
|
@ -0,0 +1 @@
|
|||||||
|
hazelcast-instanceName=hazelcast
|
@ -0,0 +1,2 @@
|
|||||||
|
#Define Host and Port
|
||||||
|
mongodb-server-host-1=localhost:27017
|
23
jnosql/pom.xml
Normal file
23
jnosql/pom.xml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
<?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>
|
||||||
|
|
||||||
|
<groupId>com.baeldung.jnosql</groupId>
|
||||||
|
<artifactId>jnosql</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
<jnosql.version>0.0.5</jnosql.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>jnosql-diana</module>
|
||||||
|
<module>jnosql-artemis</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
|
</project>
|
@ -1,2 +0,0 @@
|
|||||||
## Relevant articles:
|
|
||||||
- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order)
|
|
@ -141,6 +141,13 @@
|
|||||||
<artifactId>hazelcast</artifactId>
|
<artifactId>hazelcast</artifactId>
|
||||||
<version>${hazelcast.version}</version>
|
<version>${hazelcast.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.jmapper-framework</groupId>
|
||||||
|
<artifactId>jmapper-core</artifactId>
|
||||||
|
<version>${jmapper.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -275,6 +282,7 @@
|
|||||||
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
||||||
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
|
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
|
||||||
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
||||||
|
<jmapper.version>1.6.0.1</jmapper.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
56
libraries-data/src/main/java/com/baeldung/jmapper/User.java
Normal file
56
libraries-data/src/main/java/com/baeldung/jmapper/User.java
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
private LocalDate birthDate;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(long id, String email, LocalDate birthDate) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
this.birthDate = birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDate getBirthDate() {
|
||||||
|
return birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBirthDate(LocalDate birthDate) {
|
||||||
|
this.birthDate = birthDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,69 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Period;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JMap;
|
||||||
|
import com.googlecode.jmapper.annotations.JMapConversion;
|
||||||
|
|
||||||
|
public class UserDto {
|
||||||
|
|
||||||
|
@JMap
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@JMap("email")
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
@JMap("birthDate")
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
@JMapConversion(from={"birthDate"}, to={"age"})
|
||||||
|
public int conversion(LocalDate birthDate){
|
||||||
|
return Period.between(birthDate, LocalDate.now()).getYears();
|
||||||
|
}
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto(long id, String username, int age) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.username = username;
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAge(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", username=" + username + ", age=" + age + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JGlobalMap;
|
||||||
|
|
||||||
|
@JGlobalMap
|
||||||
|
public class UserDto1 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto1() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto1(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.annotations.JMap;
|
||||||
|
|
||||||
|
|
||||||
|
public class User {
|
||||||
|
|
||||||
|
@JMap(classes = {UserDto1.class, UserDto2.class})
|
||||||
|
private long id;
|
||||||
|
|
||||||
|
@JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class})
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "User [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
|
||||||
|
public class UserDto1 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto1() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto1(long id, String username) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto [id=" + id + ", username=" + username + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.jmapper.relational;
|
||||||
|
|
||||||
|
|
||||||
|
public class UserDto2 {
|
||||||
|
|
||||||
|
private long id;
|
||||||
|
private String email;
|
||||||
|
|
||||||
|
// constructors
|
||||||
|
|
||||||
|
public UserDto2() {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserDto2(long id, String email) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters and setters
|
||||||
|
|
||||||
|
public long getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(long id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEmail(String email) {
|
||||||
|
this.email = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "UserDto2 [id=" + id + ", email=" + email + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
10
libraries-data/src/main/resources/user_jmapper.xml
Normal file
10
libraries-data/src/main/resources/user_jmapper.xml
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="username">
|
||||||
|
<value name="email"/>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
5
libraries-data/src/main/resources/user_jmapper1.xml
Normal file
5
libraries-data/src/main/resources/user_jmapper1.xml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto1">
|
||||||
|
<global/>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
21
libraries-data/src/main/resources/user_jmapper2.xml
Normal file
21
libraries-data/src/main/resources/user_jmapper2.xml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.relational.User">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="email">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="username"/>
|
||||||
|
<attribute name="email"/>
|
||||||
|
</attributes>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
@ -0,0 +1,114 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.global;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.googlecode.jmapper.JMapper;
|
||||||
|
import com.googlecode.jmapper.api.JMapperAPI;
|
||||||
|
|
||||||
|
public class JMapperIntegrationTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotation_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseGlobalMapAnnotation_thenConverted(){
|
||||||
|
JMapper<UserDto1, User> userMapper= new JMapper<>(UserDto1.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotationExplicitConversion_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
assertTrue(result.getAge() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
//======================= XML
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXml_thenConverted(){
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class,"user_jmapper.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXmlGlobal_thenConverted(){
|
||||||
|
JMapper<UserDto1, User> userMapper = new JMapper<>(UserDto1.class, User.class,"user_jmapper1.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== API
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApi_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
|
||||||
|
.add(attribute("id").value("id"))
|
||||||
|
.add(attribute("username").value("email"))
|
||||||
|
) ;
|
||||||
|
JMapper<UserDto, User> userMapper = new JMapper<>(UserDto.class, User.class, jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto result = userMapper.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getUsername());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApiGlobal_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI() .add(mappedClass(UserDto.class)
|
||||||
|
.add(global())
|
||||||
|
) ;
|
||||||
|
JMapper<UserDto1, User> userMapper1 = new JMapper<>(UserDto1.class, User.class,jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com", LocalDate.of(1980,8,20));
|
||||||
|
UserDto1 result = userMapper1.getDestination(user);
|
||||||
|
|
||||||
|
System.out.println(result);
|
||||||
|
assertEquals(user.getId(), result.getId());
|
||||||
|
assertEquals(user.getEmail(), result.getEmail());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,76 @@
|
|||||||
|
package com.baeldung.jmapper;
|
||||||
|
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.attribute;
|
||||||
|
import static com.googlecode.jmapper.api.JMapperAPI.mappedClass;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.jmapper.relational.User;
|
||||||
|
import com.baeldung.jmapper.relational.UserDto1;
|
||||||
|
import com.baeldung.jmapper.relational.UserDto2;
|
||||||
|
import com.googlecode.jmapper.RelationalJMapper;
|
||||||
|
import com.googlecode.jmapper.api.JMapperAPI;
|
||||||
|
|
||||||
|
public class JMapperRelationalIntegrationTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseAnnotation_thenConverted(){
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2= relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
//======================= XML
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseXml_thenConverted(){
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,"user_jmapper2.xml");
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ===== API
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUser_whenUseApi_thenConverted(){
|
||||||
|
JMapperAPI jmapperApi = new JMapperAPI()
|
||||||
|
.add(mappedClass(User.class)
|
||||||
|
.add(attribute("id").value("id").targetClasses(UserDto1.class,UserDto2.class))
|
||||||
|
.add(attribute("email").targetAttributes("username","email").targetClasses(UserDto1.class,UserDto2.class)) )
|
||||||
|
;
|
||||||
|
RelationalJMapper<User> relationalMapper = new RelationalJMapper<>(User.class,jmapperApi);
|
||||||
|
|
||||||
|
User user = new User(1L,"john@test.com");
|
||||||
|
UserDto1 result1 = relationalMapper.oneToMany(UserDto1.class, user);
|
||||||
|
UserDto2 result2 = relationalMapper.oneToMany(UserDto2.class, user);
|
||||||
|
|
||||||
|
System.out.println(result1);
|
||||||
|
System.out.println(result2);
|
||||||
|
assertEquals(user.getId(), result1.getId());
|
||||||
|
assertEquals(user.getEmail(), result1.getUsername());
|
||||||
|
assertEquals(user.getId(), result2.getId());
|
||||||
|
assertEquals(user.getEmail(), result2.getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user