Merge pull request #68 from eugenp/master

update
This commit is contained in:
Maiklins
2020-08-15 19:42:45 +02:00
committed by GitHub
555 changed files with 5930 additions and 629 deletions
+1
View File
@@ -85,5 +85,6 @@ transaction.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
libraries-2/*.db
@@ -0,0 +1,126 @@
package com.baeldung.algorithms.kthsmallest;
import java.util.Arrays;
import java.util.NoSuchElementException;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class KthSmallest {
public static int findKthSmallestElement(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
checkInput(k, list1, list2);
// we are looking for the minimum value
if(k == 1) {
return min(list1[0], list2[0]);
}
// we are looking for the maximum value
if(list1.length + list2.length == k) {
return max(list1[list1.length-1], list2[list2.length-1]);
}
// swap lists if needed to make sure we take at least one element from list1
if(k <= list2.length && list2[k-1] < list1[0]) {
int[] list1_ = list1;
list1 = list2;
list2 = list1_;
}
// correct left boundary if k is bigger than the size of list2
int left = k < list2.length ? 0 : k - list2.length - 1;
// the inital right boundary cannot exceed the list1
int right = min(k-1, list1.length - 1);
int nElementsList1, nElementsList2;
// binary search
do {
nElementsList1 = ((left + right) / 2) + 1;
nElementsList2 = k - nElementsList1;
if(nElementsList2 > 0) {
if (list1[nElementsList1 - 1] > list2[nElementsList2 - 1]) {
right = nElementsList1 - 2;
} else {
left = nElementsList1;
}
}
} while(!kthSmallesElementFound(list1, list2, nElementsList1, nElementsList2));
return nElementsList2 == 0 ? list1[nElementsList1-1] : max(list1[nElementsList1-1], list2[nElementsList2-1]);
}
private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) {
// we do not take any element from the second list
if(nElementsList2 < 1) {
return true;
}
if(list1[nElementsList1-1] == list2[nElementsList2-1]) {
return true;
}
if(nElementsList1 == list1.length) {
return list1[nElementsList1-1] <= list2[nElementsList2];
}
if(nElementsList2 == list2.length) {
return list2[nElementsList2-1] <= list1[nElementsList1];
}
return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1];
}
private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
if(list1 == null || list2 == null || k < 1) {
throw new IllegalArgumentException();
}
if(list1.length == 0 || list2.length == 0) {
throw new IllegalArgumentException();
}
if(k > list1.length + list2.length) {
throw new NoSuchElementException();
}
}
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray);
return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0;
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) {
i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
}
@@ -0,0 +1,288 @@
package com.baeldung.algorithms.kthsmallest;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.util.*;
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
import static org.junit.jupiter.api.Assertions.*;
public class KthSmallestUnitTest {
@Nested
class Exceptions {
@Test
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, null, null);
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
Executable executable3 = () -> findKthSmallestElement(1, null, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
Executable executable3 = () -> findKthSmallestElement(1, new int[]{}, new int[]{});
assertThrows(IllegalArgumentException.class, executable1);
assertThrows(IllegalArgumentException.class, executable2);
assertThrows(IllegalArgumentException.class, executable3);
}
@Test
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
assertThrows(IllegalArgumentException.class, executable1);
}
@Test
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
assertThrows(NoSuchElementException.class, executable1);
}
}
@Nested
class K_is_smaller_than_the_size_of_list1_and_the_size_of_list2 {
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_from_list1() {
int result = findKthSmallestElement(1, new int[]{2, 7}, new int[]{3, 5});
assertEquals(2, result);
}
@Test
public void when_k_is_1_then_the_smallest_element_is_returned_list2() {
int result = findKthSmallestElement(1, new int[]{3, 5}, new int[]{2, 7});
assertEquals(2, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(1, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(2, list1, list2);
assertEquals(1, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_1() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(3, result);
}
@Test
public void when_kth_element_and_occurs_in_both_lists() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{0, 2, 3};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_element_is_in_first_list() {
int[] list1 = new int[]{1,2,3,4};
int[] list2 = new int[]{1,3,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_kth_is_in_second_list() {
int[] list1 = new int[]{1,3,4,4};
int[] list2 = new int[]{1,2,4,5};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(2, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_elements_in_first_list_are_all_smaller_than_second_list2() {
int[] list1 = new int[]{1,3,7,9};
int[] list2 = new int[]{11,12,14,15};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(7, result);
}
@Test
public void and_only_elements_from_second_list_are_part_of_result2() {
int[] list1 = new int[]{11,12,14,15};
int[] list2 = new int[]{1,3,7,9};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(9, result);
}
}
@Nested
class K_is_bigger_than_the_size_of_at_least_one_of_the_lists {
@Test
public void k_is_smaller_than_list1_and_bigger_than_list2() {
int[] list1 = new int[]{1, 2, 3, 4, 7, 9};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void k_is_bigger_than_list1_and_smaller_than_list2() {
int[] list1 = new int[]{1, 2, 3};
int[] list2 = new int[]{1, 2, 3, 4, 7, 9};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_smaller_than_first_list() {
int[] list1 = new int[]{9, 11, 13, 55};
int[] list2 = new int[]{1, 2, 3, 7};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_bigger_than_first_list() {
int[] list1 = new int[]{1, 2, 3, 7};
int[] list2 = new int[]{9, 11, 13, 55};
int result = findKthSmallestElement(6, list1, list2);
assertEquals(11, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists() {
int[] list1 = new int[]{3, 7, 9, 11, 55};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(7, list1, list2);
assertEquals(9, result);
}
@Test
public void when_k_is_bigger_than_the_size_of_both_lists_and_list1_has_more_elements_than_list2() {
int[] list1 = new int[]{3, 7, 9, 11, 55, 77, 100, 200};
int[] list2 = new int[]{1, 2, 3, 7, 13};
int result = findKthSmallestElement(11, list1, list2);
assertEquals(77, result);
}
@Test
public void max_test() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(100, result);
}
@Test
public void max_test2() {
int[] list1 = new int[]{100, 200};
int[] list2 = new int[]{1, 2, 3};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(200, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{1, 3, 4, 7};
int result = findKthSmallestElement(4, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list2() {
int[] list1 = new int[]{1, 2, 5};
int[] list2 = new int[]{3, 4, 7};
int result = findKthSmallestElement(3, list1, list2);
assertEquals(3, result);
}
@Test
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list23() {
int[] list1 = new int[]{3, 11, 27, 53, 90};
int[] list2 = new int[]{4, 20, 21, 100};
int result = findKthSmallestElement(5, list1, list2);
assertEquals(21, result);
}
}
// @Test
// public void randomTests() {
// IntStream.range(1, 100000).forEach(i -> random());
// }
private void random() {
Random random = new Random();
int length1 = (Math.abs(random.nextInt())) % 1000 + 1;
int length2 = (Math.abs(random.nextInt())) % 1000 + 1;
int[] list1 = sortedRandomIntArrayOfLength(length1);
int[] list2 = sortedRandomIntArrayOfLength(length2);
int k = (Math.abs(random.nextInt()) % (length1 + length2)) + 1 ;
int result = findKthSmallestElement(k, list1, list2);
int result2 = getKthElementSorted(list1, list2, k);
int result3 = getKthElementMerge(list1, list2, k);
assertEquals(result2, result);
assertEquals(result2, result3);
}
private int[] sortedRandomIntArrayOfLength(int length) {
int[] intArray = new Random().ints(length).toArray();
Arrays.sort(intArray);
return intArray;
}
}
-1
View File
@@ -7,4 +7,3 @@ This module contains articles about Apache CXF
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
+3
View File
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
@@ -0,0 +1,26 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelFormula {
public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
XSSFSheet sheet = wb.getSheetAt(0);
int lastCellNum = sheet.getRow(0).getLastCellNum();
XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
formulaCell.setCellFormula(formula);
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
formulaEvaluator.evaluateFormulaCell(formulaCell);
FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
wb.write(fileOut);
wb.close();
fileOut.close();
return formulaCell.getNumericCellValue();
}
}
@@ -0,0 +1,51 @@
package com.baeldung.poi.excel.setformula;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
class ExcelFormulaUnitTest {
private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
private String fileLocation;
private ExcelFormula excelFormula;
@BeforeEach
public void setup() throws URISyntaxException {
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
excelFormula = new ExcelFormula();
}
@Test
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet = wb.getSheetAt(0);
double resultColumnA = 0;
double resultColumnB = 0;
for (int row = 0; row <= sheet.getLastRowNum(); row++) {
resultColumnA += sheet.getRow(row).getCell(0).getNumericCellValue();
resultColumnB += sheet.getRow(row).getCell(1).getNumericCellValue();
}
String colNameA = CellReference.convertNumToColString(0);
String colNameB = CellReference.convertNumToColString(1);
String startCellA = colNameA + 1;
String stopCellA = colNameA + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnA = String.format("SUM(%s:%s)", startCellA, stopCellA);
String startCellB = colNameB + 1;
String stopCellB = colNameB + (sheet.getLastRowNum() + 1);
String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB);
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
}
}
@@ -14,3 +14,4 @@ This module contains articles about core Java features that have been introduced
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
- [How to Get a Name of a Method Being Executed?](https://www.baeldung.com/java-name-of-executing-method)
@@ -5,7 +5,16 @@ import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import static org.junit.Assert.assertTrue;
@@ -138,7 +147,7 @@ public class JavaSortingUnitTest {
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
ArrayList<Integer> list = new ArrayList<>(integersSet);
list.sort((i1, i2) -> i2 - i1);
list.sort(Comparator.reverseOrder());
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
@@ -21,6 +21,12 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@@ -0,0 +1,96 @@
package com.baeldung.list.difference;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.assertj.core.api.Assertions.*;
public class FindDifferencesBetweenListsUnitTest {
private static final List<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listOne);
differences.removeAll(listTwo);
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(listTwo);
differences.removeAll(listOne);
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
List<String> differences = listOne.stream()
.filter(element -> !listTwo.contains(element))
.collect(Collectors.toList());
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() {
List<String> differences = listTwo.stream()
.filter(element -> !listOne.contains(element))
.collect(Collectors.toList());
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo)));
assertEquals(2, differences.size());
assertThat(differences).containsExactlyInAnyOrder("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne)));
assertEquals(3, differences.size());
assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
assertEquals(2, differences.size());
assertThat(differences).containsExactly("Tom", "John");
}
@Test
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Daniel", "Alan", "George");
}
@Test
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(listOne);
listTwo.forEach(differences::remove);
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
@Test
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
assertEquals(3, differences.size());
assertThat(differences).containsExactly("Tom", "John", "Jack");
}
}
@@ -15,7 +15,15 @@ import java.util.logging.Logger;
import static org.junit.Assert.fail;
public class PrimeNumbersUnitManualTest {
/**
* This test expects the file target/test-classes/META-INF/BenchmarkList to be present.
*
* Before running the test ensure that the file is present.
* If not, please run mvn install on the module.
*
*/
public class PrimeNumbersManualTest {
private static Logger logger = Logger.getAnonymousLogger();
@@ -0,0 +1,25 @@
package com.baeldung.threadlocal;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
public ThreadLocalAwareThreadPool(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
// Call remove on each ThreadLocal
}
}
@@ -0,0 +1,2 @@
test-link*
0.*
@@ -0,0 +1,15 @@
package com.baeldung.copydirectory;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class ApacheCommons {
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException {
File sourceDirectory = new File(sourceDirectoryLocation);
File destinationDirectory = new File(destinationDirectoryLocation);
FileUtils.copyDirectory(sourceDirectory, destinationDirectory);
}
}
@@ -0,0 +1,38 @@
package com.baeldung.copydirectory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CoreOld {
public static void copyDirectoryJavaUnder7(File source, File destination) throws IOException {
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
}
private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException {
if (!destinationDirectory.exists()) {
destinationDirectory.mkdir();
}
for (String f : sourceDirectory.list()) {
copyDirectoryJavaUnder7(new File(sourceDirectory, f), new File(destinationDirectory, f));
}
}
private static void copyFile(File sourceFile, File destinationFile) throws IOException {
try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) {
byte[] buf = new byte[1024];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
}
}
}
@@ -0,0 +1,22 @@
package com.baeldung.copydirectory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaNio {
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.forEach(source -> {
Path destination = Paths.get(destinationDirectoryLocation, source.toString()
.substring(sourceDirectoryLocation.length()));
try {
Files.copy(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
@@ -0,0 +1,59 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ApacheCommonsUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory3";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory3";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
ApacheCommons.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() {
assertThrows(Exception.class, () -> ApacheCommons.copyDirectory("nonExistingDirectory", destinationDirectoryLocation));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}
@@ -0,0 +1,63 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CoreOldUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory1";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory1";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
File sourceDirectory = new File(sourceDirectoryLocation);
File destinationDirectory = new File(destinationDirectoryLocation);
CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() throws IOException {
File sourceDirectory = new File("nonExistingDirectory");
File destinationDirectory = new File(destinationDirectoryLocation);
assertThrows(IOException.class, () -> CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}
@@ -0,0 +1,59 @@
package com.baeldung.copydirectory;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class JavaNioUnitTest {
private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory2";
private final String subDirectoryName = "/childDirectory";
private final String fileName = "/file.txt";
private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory2";
@BeforeEach
public void createDirectoryWithSubdirectoryAndFile() throws IOException {
Files.createDirectories(Paths.get(sourceDirectoryLocation));
Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName));
Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName));
}
@Test
public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException {
JavaNio.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation);
assertTrue(new File(destinationDirectoryLocation).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists());
assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists());
}
@Test
public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() {
assertThrows(IOException.class, () -> JavaNio.copyDirectory("nonExistingDirectory", destinationDirectoryLocation));
}
@AfterEach
public void cleanUp() throws IOException {
Files.walk(Paths.get(sourceDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
if (new File(destinationDirectoryLocation).exists()) {
Files.walk(Paths.get(destinationDirectoryLocation))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}
@@ -0,0 +1,91 @@
package com.baeldung.existence;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ExistenceUnitTest {
@Test
public void givenFile_whenDoesNotExist_thenFilesReturnsFalse() {
Path path = Paths.get("does-not-exist.txt");
assertFalse(Files.exists(path));
assertTrue(Files.notExists(path));
}
@Test
public void givenFile_whenExists_thenFilesShouldReturnTrue() throws IOException {
Path tempFile = Files.createTempFile("baeldung", "exist-nio");
assertTrue(Files.exists(tempFile));
assertFalse(Files.notExists(tempFile));
Path tempDirectory = Files.createTempDirectory("baeldung-exists");
assertTrue(Files.exists(tempDirectory));
assertFalse(Files.notExists(tempDirectory));
assertTrue(Files.isDirectory(tempDirectory));
assertFalse(Files.isDirectory(tempFile));
assertTrue(Files.isRegularFile(tempFile));
assertTrue(Files.isReadable(tempFile));
Files.deleteIfExists(tempFile);
Files.deleteIfExists(tempDirectory);
}
@Test
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
Path target = Files.createTempFile("baeldung", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));
Files.deleteIfExists(target);
assertFalse(Files.exists(symbolicLink));
assertTrue(Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS));
Files.deleteIfExists(symbolicLink);
}
@Test
public void givenFile_whenDoesNotExist_thenFileReturnsFalse() {
assertFalse(new File("invalid").exists());
assertFalse(new File("invalid").isFile());
}
@Test
public void givenFile_whenExist_thenShouldReturnTrue() throws IOException {
Path tempFilePath = Files.createTempFile("baeldung", "exist-io");
Path tempDirectoryPath = Files.createTempDirectory("baeldung-exists-io");
File tempFile = new File(tempFilePath.toString());
File tempDirectory = new File(tempDirectoryPath.toString());
assertTrue(tempFile.exists());
assertTrue(tempDirectory.exists());
assertTrue(tempFile.isFile());
assertFalse(tempDirectory.isFile());
assertTrue(tempDirectory.isDirectory());
assertFalse(tempFile.isDirectory());
assertTrue(tempFile.canRead());
Files.deleteIfExists(tempFilePath);
Files.deleteIfExists(tempDirectoryPath);
}
}
@@ -0,0 +1,96 @@
package com.baeldung.openoptions;
import org.hamcrest.CoreMatchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import static org.junit.Assert.*;
public class OpenOptionsUnitTest {
private static final String HOME = System.getProperty("user.home");
private static final String DUMMY_FILE_NAME = "sample.txt";
private static final String EXISTING_FILE_NAME = "existingFile.txt";
private static final String DUMMY_TEXT = "This is a sample text.";
private static final String ANOTHER_DUMMY_TEXT = "This is a another text.";
@BeforeClass
public static void beforeAll() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (OutputStream out = Files.newOutputStream(path)) {
out.write(DUMMY_TEXT.getBytes());
}
Files.createFile(Paths.get(HOME, EXISTING_FILE_NAME));
}
@AfterClass
public static void afterAll() throws IOException {
Files.delete(Paths.get(HOME, "newfile.txt"));
Files.delete(Paths.get(HOME, "sparse.txt"));
Files.delete(Paths.get(HOME, DUMMY_FILE_NAME));
}
@Test
public void givenExistingPath_whenCreateNewFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, "newfile.txt");
assertFalse(Files.exists(path));
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE);
assertTrue(Files.exists(path));
}
@Test
public void givenExistingPath_whenReadExistingFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (InputStream in = Files.newInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
assertThat(line, CoreMatchers.containsString(DUMMY_TEXT));
}
}
}
@Test
public void givenExistingPath_whenWriteToExistingFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
out.write(ANOTHER_DUMMY_TEXT.getBytes());
}
}
@Test
public void givenExistingPath_whenCreateSparseFile_thenCorrect() throws IOException {
Path path = Paths.get(HOME, "sparse.txt");
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE);
}
@Test
public void givenExistingPath_whenDeleteOnClose_thenCorrect() throws IOException {
Path path = Paths.get(HOME, EXISTING_FILE_NAME);
assertTrue(Files.exists(path)); // file was already created and exists
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE)) {
out.write(ANOTHER_DUMMY_TEXT.getBytes());
}
assertFalse(Files.exists(path)); // file is deleted
}
@Test
public void givenExistingPath_whenWriteAndSync_thenCorrect() throws IOException {
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
Files.write(path, ANOTHER_DUMMY_TEXT.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
}
}
@@ -37,7 +37,7 @@ public class Human {
public static int compareByNameThenAge(final Human lhs, final Human rhs) {
if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age;
return Integer.compare(lhs.age, rhs.age);
} else {
return lhs.name.compareTo(rhs.name);
}
@@ -54,7 +54,7 @@ public class Java8SortUnitTest {
final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
humans.sort((lhs, rhs) -> {
if (lhs.getName().equals(rhs.getName())) {
return lhs.getAge() - rhs.getAge();
return Integer.compare(lhs.getAge(), rhs.getAge());
} else {
return lhs.getName().compareTo(rhs.getName());
}
@@ -12,4 +12,12 @@
<artifactId>core-java-lang-oop-types</artifactId>
<name>core-java-lang-oop-types</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,26 @@
package com.baeldung.primitivetype;
import java.util.HashMap;
import java.util.Map;
public class PrimitiveTypeUtil {
private static final Map<Class<?>, Class<?>> WRAPPER_TYPE_MAP;
static {
WRAPPER_TYPE_MAP = new HashMap<Class<?>, Class<?>>(16);
WRAPPER_TYPE_MAP.put(Integer.class, int.class);
WRAPPER_TYPE_MAP.put(Byte.class, byte.class);
WRAPPER_TYPE_MAP.put(Character.class, char.class);
WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class);
WRAPPER_TYPE_MAP.put(Double.class, double.class);
WRAPPER_TYPE_MAP.put(Float.class, float.class);
WRAPPER_TYPE_MAP.put(Long.class, long.class);
WRAPPER_TYPE_MAP.put(Short.class, short.class);
WRAPPER_TYPE_MAP.put(Void.class, void.class);
}
public static boolean isPrimitiveType(Object source) {
return WRAPPER_TYPE_MAP.containsKey(source.getClass());
}
}
@@ -0,0 +1,34 @@
package com.baeldung.primitivetype;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import com.google.common.primitives.Primitives;
public class PrimitiveTypeUnitTest {
@Test
public void givenAClass_whenCheckWithPrimitiveTypeUtil_thenShouldValidate() {
assertTrue(PrimitiveTypeUtil.isPrimitiveType(false));
assertTrue(PrimitiveTypeUtil.isPrimitiveType(1L));
assertFalse(PrimitiveTypeUtil.isPrimitiveType(StringUtils.EMPTY));
}
@Test
public void givenAClass_whenCheckWithCommonsLang_thenShouldValidate() {
assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.FALSE.getClass()));
assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class));
assertFalse(ClassUtils.isPrimitiveOrWrapper(StringUtils.EMPTY.getClass()));
}
@Test
public void givenAClass_whenCheckWithGuava_thenShouldValidate() {
assertTrue(Primitives.isWrapperType(Boolean.FALSE.getClass()));
assertFalse(Primitives.isWrapperType(StringUtils.EMPTY.getClass()));
assertFalse(Primitives.isWrapperType(Boolean.TYPE.getClass()));
}
}
@@ -45,7 +45,7 @@ public class Player implements Comparable<Player> {
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
return Integer.compare(getRanking(), otherPlayer.getRanking());
}
}
@@ -6,7 +6,7 @@ public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
return Integer.compare(firstPlayer.getAge(), secondPlayer.getAge());
}
}

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