@@ -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)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
@@ -55,3 +54,5 @@
|
||||
- [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)
|
||||
- [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>
|
||||
<version>${joda.version}</version>
|
||||
</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>
|
||||
|
||||
<build>
|
||||
@@ -170,6 +180,7 @@
|
||||
<joda.version>2.10</joda.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<asspectj.version>1.8.9</asspectj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
|
||||
+9
@@ -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;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
@@ -9,6 +10,8 @@ import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
@@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest {
|
||||
|
||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,11 +19,23 @@
|
||||
<version>${awaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -50,6 +62,8 @@
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.10.0</assertj.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<awaitility.version>1.7.0</awaitility.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
|
||||
+27
@@ -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()));
|
||||
}
|
||||
}
|
||||
+51
@@ -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 Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
|
||||
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
|
||||
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
|
||||
|
||||
@@ -36,19 +36,37 @@
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</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>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<eclipse.collections.version>9.2.0</eclipse.collections.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
+3
-3
@@ -1,13 +1,13 @@
|
||||
package com.baeldung.convertlisttomap;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class ConvertListToMapService {
|
||||
|
||||
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
|
||||
+16
@@ -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;
|
||||
}
|
||||
}
|
||||
+32
@@ -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;
|
||||
}
|
||||
}
|
||||
+17
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -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());
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -1,13 +1,14 @@
|
||||
package com.baeldung.convertlisttomap;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
|
||||
public class ConvertListToMapServiceUnitTest {
|
||||
List<Animal> list;
|
||||
+5
-5
@@ -1,15 +1,15 @@
|
||||
package com.baeldung.convertlisttomap;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
|
||||
List<Animal> duplicatedIdList;
|
||||
+44
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -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)
|
||||
- [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)
|
||||
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
|
||||
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
|
||||
|
||||
@@ -163,3 +163,8 @@
|
||||
- [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)
|
||||
- [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)
|
||||
|
||||
@@ -173,6 +173,19 @@
|
||||
<artifactId>c3p0</artifactId>
|
||||
<version>${c3p0.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>
|
||||
|
||||
<build>
|
||||
@@ -400,6 +413,111 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</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>
|
||||
|
||||
<properties>
|
||||
@@ -453,6 +571,8 @@
|
||||
<!-- 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>
|
||||
|
||||
</project>
|
||||
|
||||
+2
-4
@@ -33,7 +33,7 @@ public class BasicConnectionPool implements ConnectionPool {
|
||||
|
||||
@Override
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (connectionPool.size() == 0) {
|
||||
if (connectionPool.isEmpty()) {
|
||||
if (usedConnections.size() < MAX_POOL_SIZE) {
|
||||
connectionPool.add(createConnection(url, user, password));
|
||||
} else {
|
||||
@@ -76,9 +76,7 @@ public class BasicConnectionPool implements ConnectionPool {
|
||||
}
|
||||
|
||||
public void shutdown() throws SQLException {
|
||||
for (Connection c : usedConnections) {
|
||||
this.releaseConnection(c);
|
||||
}
|
||||
usedConnections.forEach(this::releaseConnection);
|
||||
for (Connection c : connectionPool) {
|
||||
c.close();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+59
@@ -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);
|
||||
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user