[JAVA-29427] Consolidate libraries modules (#15536)

This commit is contained in:
panos-kakos
2024-01-03 20:39:23 +02:00
committed by GitHub
parent 5c6e53c15a
commit 21d3e16584
60 changed files with 364 additions and 453 deletions
@@ -0,0 +1,29 @@
package com.baeldung.findfiles;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public class FindFileApacheUtils {
private FindFileApacheUtils() {
}
public static Iterator<File> find(Path startPath, String extension) {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
if (!extension.startsWith("."))
extension = "." + extension;
return FileUtils.iterateFiles(startPath.toFile(), WildcardFileFilter.builder()
.setWildcards("*" + extension)
.get(), TrueFileFilter.INSTANCE);
}
}
@@ -0,0 +1,34 @@
package com.baeldung.findfiles;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FindFileJava2Utils {
private FindFileJava2Utils() {
}
public static List<File> find(File startPath, String extension) {
if (!startPath.isDirectory()) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
List<File> matches = new ArrayList<>();
File[] files = startPath.listFiles();
if (files == null)
return matches;
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
for (File file : files) {
if (file.isDirectory()) {
matches.addAll(find(file, extension));
} else if (filter.test(file.toPath())) {
matches.add(file);
}
}
return matches;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
public class FindFileJava7Utils {
private FindFileJava7Utils() {
}
public static List<Path> find(Path startPath, String extension) throws IOException {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
final List<Path> matches = new ArrayList<>();
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
if (filter.test(file)) {
matches.add(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
return matches;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Consumer;
public class FindFileJava8Utils {
private FindFileJava8Utils() {
}
public static void find(Path startPath, String extension, Consumer<Path> consumer) throws IOException {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
Files.walkFileTree(startPath, new SimpleFileConsumerVisitor(filter, consumer));
}
}
@@ -0,0 +1,26 @@
package com.baeldung.findfiles;
import java.nio.file.Path;
import java.util.function.Predicate;
public class MatchExtensionPredicate implements Predicate<Path> {
private final String extension;
public MatchExtensionPredicate(String extension) {
if (!extension.startsWith("."))
extension = "." + extension;
this.extension = extension.toLowerCase();
}
@Override
public boolean test(Path path) {
if (path == null)
return false;
return path.getFileName()
.toString()
.toLowerCase()
.endsWith(extension);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class SimpleFileConsumerVisitor extends SimpleFileVisitor<Path> {
private final Predicate<Path> filter;
private final Consumer<Path> consumer;
public SimpleFileConsumerVisitor(MatchExtensionPredicate filter, Consumer<Path> consumer) {
this.filter = filter;
this.consumer = consumer;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
if (filter.test(file))
consumer.accept(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}
@@ -0,0 +1,182 @@
package com.baeldung.apache.commons;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
import org.apache.commons.collections4.bidimap.TreeBidiMap;
import org.apache.commons.collections4.map.MultiKeyMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.junit.Test;
public class CollectionsUnitTest {
private final static BidiMap<Integer, String> daysOfWeek = new TreeBidiMap<Integer, String>();
private final static MultiValuedMap<String, String> groceryCart = new ArrayListValuedHashMap<>();
private final static MultiKeyMap<String, String> days = new MultiKeyMap<String, String>();
private final static MultiKeyMap<String, String> cityCoordinates = new MultiKeyMap<String, String>();
private long start;
static {
daysOfWeek.put(1, "Monday");
daysOfWeek.put(2, "Tuesday");
daysOfWeek.put(3, "Wednesday");
daysOfWeek.put(4, "Thursday");
daysOfWeek.put(5, "Friday");
daysOfWeek.put(6, "Saturday");
daysOfWeek.put(7, "Sunday");
groceryCart.put("Fruits", "Apple");
groceryCart.put("Fruits", "Grapes");
groceryCart.put("Fruits", "Strawberries");
groceryCart.put("Vegetables", "Spinach");
groceryCart.put("Vegetables", "Cabbage");
days.put("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Weekday");
days.put("Saturday", "Sunday", "Weekend");
cityCoordinates.put("40.7128° N", "74.0060° W", "New York");
cityCoordinates.put("48.8566° N", "2.3522° E", "Paris");
cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai");
}
@Test
public void givenBidiMap_whenValue_thenKeyReturned() {
assertEquals(Integer.valueOf(7), daysOfWeek.inverseBidiMap()
.get("Sunday"));
}
@Test
public void givenBidiMap_whenKey_thenValueReturned() {
assertEquals("Tuesday", daysOfWeek.get(2));
}
@Test
public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() {
List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries");
assertEquals(fruits, groceryCart.get("Fruits"));
}
@Test
public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() {
List<String> veggies = Arrays.asList("Spinach", "Cabbage");
assertEquals(veggies, groceryCart.get("Vegetables"));
}
@Test
public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() {
assertEquals(5, groceryCart.size());
groceryCart.remove("Fruits");
assertEquals(2, groceryCart.size());
}
@Test
public void givenDaysMultiKeyMap_whenFetched_thenOK() {
assertFalse(days.get("Saturday", "Sunday")
.equals("Weekday"));
}
@Test
public void givenCoordinatesMultiKeyMap_whenQueried_thenOK() {
List<String> expectedLongitudes = Arrays.asList("72.8777° E", "2.3522° E", "74.0060° W");
List<String> longitudes = new ArrayList<>();
cityCoordinates.forEach((key, value) -> {
longitudes.add(key.getKey(1));
});
assertArrayEquals(expectedLongitudes.toArray(), longitudes.toArray());
List<String> expectedCities = Arrays.asList("Mumbai", "Paris", "New York");
List<String> cities = new ArrayList<>();
cityCoordinates.forEach((key, value) -> {
cities.add(value);
});
assertArrayEquals(expectedCities.toArray(), cities.toArray());
}
@Test
public void givenTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**TreeBidiMap**");
BidiMap<Integer, Integer> map = new TreeBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
@Test
public void givenDualTreeBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**DualTreeBidiMap**");
BidiMap<Integer, Integer> map = new DualTreeBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
@Test
public void givenDualHashBidiMap_whenHundredThousandKeys_thenPerformanceNoted() {
System.out.println("**DualHashBidiMap**");
BidiMap<Integer, Integer> map = new DualHashBidiMap<>();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = (Integer) map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = (Integer) map.getKey(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
}
@@ -0,0 +1,79 @@
package com.baeldung.findfiles;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class FindFileUtilsIntegrationTest {
private static final String TEST_EXTENSION = ".test";
private static final String OTHER_EXTENSION = ".other";
private static final List<Path> TEST_FILES = new ArrayList<>();
private static final List<Path> OTHER_FILES = new ArrayList<>();
private static Path TEST_DIR;
@BeforeAll
static void setup() throws IOException {
TEST_DIR = Files.createTempDirectory(null);
final Path nestedDir = TEST_DIR.resolve("sub-dir");
Files.createDirectories(nestedDir);
TEST_FILES.add(Files.createFile(TEST_DIR.resolve("a" + TEST_EXTENSION)));
OTHER_FILES.add(Files.createFile(TEST_DIR.resolve("a" + OTHER_EXTENSION)));
TEST_FILES.add(Files.createFile(nestedDir.resolve("b" + TEST_EXTENSION)));
OTHER_FILES.add(Files.createFile(nestedDir.resolve("b" + OTHER_EXTENSION)));
}
@AfterAll
static void cleanUp() {
FileUtils.deleteQuietly(TEST_DIR.toFile());
}
@Test
void whenFindFilesWithJava2_thenOnlyMatchingFilesFound() {
List<File> matches = FindFileJava2Utils.find(TEST_DIR.toFile(), TEST_EXTENSION);
assertEquals(TEST_FILES.size(), matches.size());
}
@Test
void whenFindFilesWithJava7_thenOnlyMatchingFilesFound() throws IOException {
List<Path> matches = FindFileJava7Utils.find(TEST_DIR, TEST_EXTENSION);
assertEquals(TEST_FILES.size(), matches.size());
}
@Test
void whenFindFilesWithJava8_thenOnlyMatchingFilesFound() throws IOException {
final AtomicInteger matches = new AtomicInteger(0);
FindFileJava8Utils.find(TEST_DIR, TEST_EXTENSION, path -> matches.incrementAndGet());
assertEquals(TEST_FILES.size(), matches.get());
}
@Test
void whenFindFilesWithApache_thenOnlyMatchingFilesFound() {
final AtomicInteger matches = new AtomicInteger(0);
Iterator<File> iterator = FindFileApacheUtils.find(TEST_DIR, TEST_EXTENSION);
iterator.forEachRemaining(file -> matches.incrementAndGet());
assertEquals(TEST_FILES.size(), matches.get());
}
}
@@ -0,0 +1,143 @@
package com.baeldung.guava;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Table;
public class GuavaUnitTest {
private final static BiMap<Integer, String> daysOfWeek = HashBiMap.create();
private final static Multimap<String, String> groceryCart = ArrayListMultimap.create();
private final static Table<String, String, String> cityCoordinates = HashBasedTable.create();
private final static Table<String, String, String> movies = HashBasedTable.create();
private long start;
static {
daysOfWeek.put(1, "Monday");
daysOfWeek.put(2, "Tuesday");
daysOfWeek.put(3, "Wednesday");
daysOfWeek.put(4, "Thursday");
daysOfWeek.put(5, "Friday");
daysOfWeek.put(6, "Saturday");
daysOfWeek.put(7, "Sunday");
groceryCart.put("Fruits", "Apple");
groceryCart.put("Fruits", "Grapes");
groceryCart.put("Fruits", "Strawberries");
groceryCart.put("Vegetables", "Spinach");
groceryCart.put("Vegetables", "Cabbage");
cityCoordinates.put("40.7128° N", "74.0060° W", "New York");
cityCoordinates.put("48.8566° N", "2.3522° E", "Paris");
cityCoordinates.put("19.0760° N", "72.8777° E", "Mumbai");
movies.put("Tom Hanks", "Meg Ryan", "You've Got Mail");
movies.put("Tom Hanks", "Catherine Zeta-Jones", "The Terminal");
movies.put("Bradley Cooper", "Lady Gaga", "A Star is Born");
movies.put("Keenu Reaves", "Sandra Bullock", "Speed");
movies.put("Tom Hanks", "Sandra Bullock", "Extremely Loud & Incredibly Close");
}
@Test
public void givenBiMap_whenValue_thenKeyReturned() {
assertEquals(Integer.valueOf(7), daysOfWeek.inverse()
.get("Sunday"));
}
@Test
public void givenBiMap_whenKey_thenValueReturned() {
assertEquals("Tuesday", daysOfWeek.get(2));
}
@Test
public void givenMultiValuedMap_whenFruitsFetched_thenFruitsReturned() {
List<String> fruits = Arrays.asList("Apple", "Grapes", "Strawberries");
assertEquals(fruits, groceryCart.get("Fruits"));
}
@Test
public void givenMultiValuedMap_whenVeggiesFetched_thenVeggiesReturned() {
List<String> veggies = Arrays.asList("Spinach", "Cabbage");
assertEquals(veggies, groceryCart.get("Vegetables"));
}
@Test
public void givenMultiValuedMap_whenFuitsRemoved_thenVeggiesPreserved() {
assertEquals(5, groceryCart.size());
groceryCart.remove("Fruits", "Apple");
assertEquals(4, groceryCart.size());
groceryCart.removeAll("Fruits");
assertEquals(2, groceryCart.size());
}
@Test
public void givenCoordinatesTable_whenFetched_thenOK() {
List<String> expectedLongitudes = Arrays.asList("74.0060° W", "2.3522° E", "72.8777° E");
assertArrayEquals(expectedLongitudes.toArray(), cityCoordinates.columnKeySet()
.toArray());
List<String> expectedCities = Arrays.asList("New York", "Paris", "Mumbai");
assertArrayEquals(expectedCities.toArray(), cityCoordinates.values()
.toArray());
assertTrue(cityCoordinates.rowKeySet()
.contains("48.8566° N"));
}
@Test
public void givenMoviesTable_whenFetched_thenOK() {
assertEquals(3, movies.row("Tom Hanks")
.size());
assertEquals(2, movies.column("Sandra Bullock")
.size());
assertEquals("A Star is Born", movies.get("Bradley Cooper", "Lady Gaga"));
assertTrue(movies.containsValue("Speed"));
}
@Test
public void givenHashBiMap_whenHundredThousandKeys_thenPerformanceNoted() {
BiMap<Integer, Integer> map = HashBiMap.create();
start = System.nanoTime();
for (int i = 0; i < 100000; i++) {
Integer key = new Integer(i);
Integer value = new Integer(i + 1);
map.put(key, value);
}
System.out.println("Insertion time:" + TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer value = map.get(new Integer(500));
System.out.println("Value:" + value);
System.out.println("Fetch time key:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
start = System.nanoTime();
Integer key = map.inverse()
.get(new Integer(501));
System.out.println("Key:" + key);
System.out.println("Fetch time value:" + TimeUnit.MICROSECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
}
}