Merge pull request #4 from eugenp/master

Updating local repository
This commit is contained in:
Umang Budhwar 2020-08-17 21:58:18 +05:30 committed by GitHub
commit 969280640c
1385 changed files with 9543 additions and 2696 deletions

1
.gitignore vendored
View File

@ -85,5 +85,6 @@ transaction.log
*-shell.log *-shell.log
apache-cxf/cxf-aegis/baeldung.xml apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
libraries-2/*.db libraries-2/*.db

View File

@ -8,4 +8,5 @@
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms) - [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher) - [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver) - [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5) - More articles: [[<-- prev]](/../algorithms-miscellaneous-5)

View File

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

View File

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

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) - [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) - [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) - [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)

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

View File

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

View File

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

View File

@ -6,4 +6,4 @@ This module contains articles about Apache Shiro
- [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro) - [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro)
- [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control) - [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control)
- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro)

View File

@ -31,6 +31,6 @@ public class UseDateTimeFormatterUnitTest {
public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() { public void givenALocalDate_whenFormattingWithStyleAndLocale_thenPass() {
String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK); String result = subject.formatWithStyleAndLocale(localDateTime, FormatStyle.MEDIUM, Locale.UK);
assertThat(result).isEqualTo("25 Jan 2015, 06:30:00"); assertThat(result).isEqualTo("25-Jan-2015 06:30:00");
} }
} }

View File

@ -3,6 +3,7 @@ package com.baeldung.datetime;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
@ -24,10 +25,11 @@ public class UseToInstantUnitTest {
@Test @Test
public void givenADate_whenConvertingToLocalDate_thenAsExpected() { public void givenADate_whenConvertingToLocalDate_thenAsExpected() {
Date givenDate = new Date(1465817690000L); LocalDateTime currentDateTime = LocalDateTime.now();
Date givenDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate); LocalDateTime localDateTime = subject.convertDateToLocalDate(givenDate);
assertThat(localDateTime).isEqualTo("2016-06-13T13:34:50"); assertThat(localDateTime).isEqualTo(currentDateTime);
} }
} }

View File

@ -54,7 +54,7 @@ public class UseZonedDateTimeUnitTest {
@Test @Test
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() { public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]"); ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris")); ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 10, 15, 30, 0, ZoneId.of("Europe/Paris"));
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris")); assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));

View File

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

View File

@ -0,0 +1,39 @@
package com.baeldung.arraycompare;
import java.util.Objects;
public class Plane {
private final String name;
private final String model;
public Plane(String name, String model) {
this.name = name;
this.model = model;
}
public String getName() {
return name;
}
public String getModel() {
return model;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Plane plane = (Plane) o;
return Objects.equals(name, plane.name) && Objects.equals(model, plane.model);
}
@Override
public int hashCode() {
return Objects.hash(name, model);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class DeepEqualsCompareUnitTest {
@Test
public void givenSameContents_whenDeepEquals_thenTrue() {
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
}
@Test
public void givenSameContentsWithDifferentOrder_whenDeepEquals_thenFalse() {
final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") },
new Plane[] { new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") },
new Plane[] { new Plane("Plane 1", "A320") } };
assertThat(Arrays.deepEquals(planes1, planes2)).isFalse();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class EqualsCompareUnitTest {
@Test
public void givenSameContents_whenEquals_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(Arrays.equals(planes1, planes2)).isTrue();
}
@Test
public void givenSameContentsDifferentOrder_whenEquals_thenFalse() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(Arrays.equals(planes1, planes2)).isFalse();
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class LengthsCompareUnitTest {
@Test
public void givenSameContent_whenSizeCompare_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 };
assertThat(planes1).hasSize(8);
assertThat(quantities).hasSize(8);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Comparator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class OrderCompareUnitTest {
@Test
public void givenSameContentDifferentOrder_whenSortedAndDeepEquals_thenTrue() {
final Plane[][] planes1 = new Plane[][] {
new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } };
final Plane[][] planes2 = new Plane[][] {
new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } };
Comparator<Plane> planeComparator = (o1, o2) -> {
if (o1.getName()
.equals(o2.getName())) {
return o2.getModel()
.compareTo(o1.getModel());
}
return o2.getName()
.compareTo(o1.getName());
};
Arrays.sort(planes1[0], planeComparator);
Arrays.sort(planes2[0], planeComparator);
assertThat(Arrays.deepEquals(planes1, planes2)).isTrue();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.arraycompare;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ReferenceCompareUnitTest {
@Test
public void givenSameReferences_whenSame_thenTrue() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = planes1;
assertThat(planes1).isSameAs(planes2);
planes2[0] = "747";
assertThat(planes1).isSameAs(planes2);
assertThat(planes2[0]).isEqualTo("747");
assertThat(planes1[0]).isEqualTo("747");
}
@Test
public void givenSameContentDifferentReferences_whenSame_thenFalse() {
final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" };
assertThat(planes1).isNotSameAs(planes2);
}
}

View File

@ -5,7 +5,16 @@ import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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 java.util.Map.Entry;
import static org.junit.Assert.assertTrue; 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)); HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
ArrayList<Integer> list = new ArrayList<>(integersSet); ArrayList<Integer> list = new ArrayList<>(integersSet);
list.sort((i1, i2) -> i2 - i1); list.sort(Comparator.reverseOrder());
integersSet = new LinkedHashSet<>(list); integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray())); assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));

View File

@ -3,6 +3,7 @@
## Core Java Collections Cookbooks and Examples ## Core Java Collections Cookbooks and Examples
### Relevant Articles: ### Relevant Articles:
- [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint) - [Time Comparison of Arrays.sort(Object[]) and Arrays.sort(int[])](https://www.baeldung.com/arrays-sortobject-vs-sortint)
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector) - [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences) - [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
@ -10,3 +11,4 @@
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) - [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Fail-Safe Iterator vs Fail-Fast Iterator](https://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack) - [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
- [Convert an Array of Primitives to a List](https://www.baeldung.com/java-primitive-array-to-list)

View File

@ -16,6 +16,11 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId> <artifactId>jmh-core</artifactId>
@ -37,6 +42,7 @@
<properties> <properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version> <openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version> <assertj.version>3.11.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,178 @@
package com.baeldung.collections.bitset;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import java.util.BitSet;
import static org.assertj.core.api.Assertions.assertThat;
public class BitSetUnitTest {
@Test
public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() {
boolean[] bits = new boolean[1024 * 1024];
System.out.println(ClassLayout.parseInstance(bits).toPrintable());
}
@Test
public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() {
BitSet bitSet = new BitSet(1024 * 1024);
System.out.println(GraphLayout.parseInstance(bitSet).toPrintable());
}
@Test
public void givenBitSet_whenSetting_thenShouldBeTrue() {
BitSet bitSet = new BitSet();
bitSet.set(10);
assertThat(bitSet.get(10)).isTrue();
bitSet.set(20, 30);
for (int i = 20; i <= 29; i++) {
assertThat(bitSet.get(i)).isTrue();
}
assertThat(bitSet.get(30)).isFalse();
bitSet.set(10, false);
assertThat(bitSet.get(10)).isFalse();
bitSet.set(20, 30, false);
for (int i = 20; i <= 30; i++) {
assertThat(bitSet.get(i)).isFalse();
}
}
@Test
public void givenBitSet_whenClearing_thenShouldBeFalse() {
BitSet bitSet = new BitSet();
bitSet.set(42);
assertThat(bitSet.get(42)).isTrue();
bitSet.clear(42);
assertThat(bitSet.get(42)).isFalse();
bitSet.set(10, 20);
for (int i = 10; i < 20; i++) {
assertThat(bitSet.get(i)).isTrue();
}
bitSet.clear(10, 20);
for (int i = 10; i < 20; i++) {
assertThat(bitSet.get(i)).isFalse();
}
bitSet.set(10, 20);
bitSet.clear();
for (int i = 0; i < 100; i++) {
assertThat(bitSet.get(i)).isFalse();
}
}
@Test
public void givenBitSet_whenGettingElements_thenShouldReturnRequestedBits() {
BitSet bitSet = new BitSet();
bitSet.set(42);
assertThat(bitSet.get(42)).isTrue();
assertThat(bitSet.get(43)).isFalse();
bitSet.set(10, 20);
BitSet newBitSet = bitSet.get(10, 20);
for (int i = 0; i < 10; i++) {
assertThat(newBitSet.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenFlip_thenTogglesTrueToFalseAndViceVersa() {
BitSet bitSet = new BitSet();
bitSet.set(42);
bitSet.flip(42);
assertThat(bitSet.get(42)).isFalse();
bitSet.flip(12);
assertThat(bitSet.get(12)).isTrue();
bitSet.flip(30, 40);
for (int i = 30; i < 40; i++) {
assertThat(bitSet.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenGettingTheSize_thenReturnsTheSize() {
BitSet defaultBitSet = new BitSet();
assertThat(defaultBitSet.size()).isEqualTo(64);
BitSet bitSet = new BitSet(1024);
assertThat(bitSet.size()).isEqualTo(1024);
assertThat(bitSet.cardinality()).isEqualTo(0);
bitSet.set(10, 30);
assertThat(bitSet.cardinality()).isEqualTo(30 - 10);
assertThat(bitSet.length()).isEqualTo(30);
bitSet.set(100);
assertThat(bitSet.length()).isEqualTo(101);
assertThat(bitSet.isEmpty()).isFalse();
bitSet.clear();
assertThat(bitSet.isEmpty()).isTrue();
}
@Test
public void givenBitSet_whenSetOperations_thenShouldReturnAnotherBitSet() {
BitSet first = new BitSet();
first.set(5, 10);
BitSet second = new BitSet();
second.set(7, 15);
assertThat(first.intersects(second)).isTrue();
first.and(second);
assertThat(first.get(7)).isTrue();
assertThat(first.get(8)).isTrue();
assertThat(first.get(9)).isTrue();
assertThat(first.get(10)).isFalse();
first.clear();
first.set(5, 10);
first.xor(second);
for (int i = 5; i < 7; i++) {
assertThat(first.get(i)).isTrue();
}
for (int i = 10; i < 15; i++) {
assertThat(first.get(i)).isTrue();
}
}
@Test
public void givenBitSet_whenStream_thenStreamsAllSetBits() {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
bitSet.stream().forEach(System.out::println);
assertThat(bitSet.stream().count()).isEqualTo(10);
}
@Test
public void givenBitSet_whenNextOrPrev_thenReturnsTheNextOrPrevClearOrSetBit() {
BitSet bitSet = new BitSet();
bitSet.set(15, 25);
assertThat(bitSet.nextSetBit(13)).isEqualTo(15);
assertThat(bitSet.nextSetBit(25)).isEqualTo(-1);
assertThat(bitSet.nextClearBit(23)).isEqualTo(25);
assertThat(bitSet.previousClearBit(24)).isEqualTo(14);
assertThat(bitSet.previousSetBit(29)).isEqualTo(24);
assertThat(bitSet.previousSetBit(14)).isEqualTo(-1);
}
}

View File

@ -21,6 +21,12 @@
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version> <version>${commons-collections4.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>

View File

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

View File

@ -21,20 +21,15 @@
<version>${eclipse-collections.version}</version> <version>${eclipse-collections.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.sf.trove4j</groupId> <groupId>com.carrotsearch</groupId>
<artifactId>trove4j</artifactId> <artifactId>hppc</artifactId>
<version>${trove4j.version}</version> <version>${hppc.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>it.unimi.dsi</groupId> <groupId>it.unimi.dsi</groupId>
<artifactId>fastutil</artifactId> <artifactId>fastutil</artifactId>
<version>${fastutil.version}</version> <version>${fastutil.version}</version>
</dependency> </dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>${colt.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
@ -69,9 +64,8 @@
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version> <eclipse-collections.version>8.2.0</eclipse-collections.version>
<trove4j.version>3.0.2</trove4j.version> <hppc.version>0.7.2</hppc.version>
<fastutil.version>8.1.0</fastutil.version> <fastutil.version>8.1.0</fastutil.version>
<colt.version>1.2.0</colt.version>
<assertj.version>3.11.1</assertj.version> <assertj.version>3.11.1</assertj.version>
</properties> </properties>

View File

@ -1,29 +1,68 @@
package com.baeldung.map.primitives; package com.baeldung.map.primitives;
import cern.colt.map.AbstractIntDoubleMap; import com.carrotsearch.hppc.IntLongHashMap;
import cern.colt.map.OpenIntDoubleHashMap; import com.carrotsearch.hppc.IntLongScatterMap;
import gnu.trove.map.TDoubleIntMap; import com.carrotsearch.hppc.IntObjectHashMap;
import gnu.trove.map.hash.TDoubleIntHashMap; import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectScatterMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMap; import it.unimi.dsi.fastutil.ints.Int2BooleanMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanMaps;
import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap; import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap;
import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps; import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap; import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableIntIntMap; import org.eclipse.collections.api.map.primitive.MutableIntIntMap;
import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap; import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap;
import org.eclipse.collections.impl.factory.primitive.IntIntMaps; import org.eclipse.collections.impl.factory.primitive.IntIntMaps;
import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps; import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps;
import static java.lang.String.format;
import java.math.BigDecimal;
public class PrimitiveMaps { public class PrimitiveMaps {
public static void main(String[] args) { public static void main(String[] args) {
hppcMap();
eclipseCollectionsMap(); eclipseCollectionsMap();
troveMap();
coltMap();
fastutilMap(); fastutilMap();
} }
private static void hppcMap() {
//Regular maps
IntLongHashMap intLongHashMap = new IntLongHashMap();
intLongHashMap.put(25,1L);
intLongHashMap.put(150,Long.MAX_VALUE);
intLongHashMap.put(1,0L);
intLongHashMap.get(150);
IntObjectMap<BigDecimal> intObjectMap = new IntObjectHashMap<BigDecimal>();
intObjectMap.put(1, BigDecimal.valueOf(1));
intObjectMap.put(2, BigDecimal.valueOf(2500));
BigDecimal value = intObjectMap.get(2);
//Scatter maps
IntLongScatterMap intLongScatterMap = new IntLongScatterMap();
intLongScatterMap.put(1, 1L);
intLongScatterMap.put(2, -2L);
intLongScatterMap.put(1000,0L);
intLongScatterMap.get(1000);
IntObjectScatterMap<BigDecimal> intObjectScatterMap = new IntObjectScatterMap<BigDecimal>();
intObjectScatterMap.put(1, BigDecimal.valueOf(1));
intObjectScatterMap.put(2, BigDecimal.valueOf(2500));
value = intObjectScatterMap.get(2);
}
private static void fastutilMap() { private static void fastutilMap() {
Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap(); Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap();
int2BooleanMap.put(1, true); int2BooleanMap.put(1, true);
@ -32,13 +71,19 @@ public class PrimitiveMaps {
boolean value = int2BooleanMap.get(1); boolean value = int2BooleanMap.get(1);
Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP; //Lambda style iteration
} Int2BooleanMaps.fastForEach(int2BooleanMap, entry -> {
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
});
//Iterator based loop
ObjectIterator<Int2BooleanMap.Entry> iterator = Int2BooleanMaps.fastIterator(int2BooleanMap);
while(iterator.hasNext()) {
Int2BooleanMap.Entry entry = iterator.next();
System.out.println(String.format("Key: %d, Value: %b",entry.getIntKey(),entry.getBooleanValue()));
}
private static void coltMap() {
AbstractIntDoubleMap map = new OpenIntDoubleHashMap();
map.put(1, 4.5);
double value = map.get(1);
} }
private static void eclipseCollectionsMap() { private static void eclipseCollectionsMap() {
@ -53,17 +98,5 @@ public class PrimitiveMaps {
dObject.addToValue("stability", 0.8); dObject.addToValue("stability", 0.8);
} }
private static void troveMap() {
double[] doubles = new double[] {1.2, 4.5, 0.3};
int[] ints = new int[] {1, 4, 0};
TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints);
doubleIntMap.put(1.2, 22);
doubleIntMap.put(4.5, 16);
doubleIntMap.adjustValue(1.2, 1);
doubleIntMap.adjustValue(4.5, 4);
doubleIntMap.adjustValue(0.3, 7);
}
} }

View File

@ -15,7 +15,15 @@ import java.util.logging.Logger;
import static org.junit.Assert.fail; 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(); private static Logger logger = Logger.getAnonymousLogger();

View File

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

View File

@ -3,10 +3,12 @@
This module contains articles about basic Java concurrency This module contains articles about basic Java concurrency
### Relevant Articles: ### Relevant Articles:
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify) - [wait and notify() Methods in Java](https://www.baeldung.com/java-wait-notify)
- [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep)
- [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized)
- [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle)
- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) - [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference)
- [Why are Local Variables Thread-Safe in Java](https://www.baeldung.com/java-local-variables-thread-safe)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) - [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@ -0,0 +1,31 @@
package com.baeldung.consoleout;
import java.io.Console;
public class ConsoleAndOut {
public static void main(String[] args) {
try {
printConsoleObject();
readPasswordFromConsole();
} catch (Exception ex) {
// Eating NullPointerExcpetion which will occur when this
// program will be run from mediums other than console
}
printSysOut();
}
static void printConsoleObject() {
Console console = System.console();
console.writer().print(console);
}
static void readPasswordFromConsole() {
Console console = System.console();
char[] password = console.readPassword("Enter password: ");
console.printf(String.valueOf(password));
}
static void printSysOut() {
System.out.println(System.out);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.consoleout;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class ConsoleAndOutUnitTest {
@Test
void whenRetreivingConsole_thenPrintConsoleObject() {
assertThrows(NullPointerException.class, () -> {
ConsoleAndOut.printConsoleObject();
});
}
@Test
void whenReadingPassword_thenReadPassword() {
assertThrows(NullPointerException.class, () -> {
ConsoleAndOut.readPasswordFromConsole();
});
}
@Test
void whenRetrievingSysOut_thenPrintSysOutObject() {
ConsoleAndOut.printSysOut();
}
}

View File

@ -13,3 +13,4 @@ This module contains articles about core java exceptions
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) - [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
- [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) - [How to Find an Exceptions Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
- [Java IOException “Too many open files”](https://www.baeldung.com/java-too-many-open-files) - [Java IOException “Too many open files”](https://www.baeldung.com/java-too-many-open-files)
- [When Does Java Throw the ExceptionInInitializerError?](https://www.baeldung.com/java-exceptionininitializererror)

View File

@ -0,0 +1,2 @@
test-link*
0.*

View File

@ -3,5 +3,7 @@
This module contains articles about core Java input and output (IO) This module contains articles about core Java input and output (IO)
### Relevant Articles: ### Relevant Articles:
- [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file) - [Java Create a File](https://www.baeldung.com/java-how-to-create-a-file)
- [Check If a Directory Is Empty in Java](https://www.baeldung.com/java-check-empty-directory)
- [[<-- Prev]](/core-java-modules/core-java-io-2) - [[<-- Prev]](/core-java-modules/core-java-io-2)

View File

@ -46,41 +46,14 @@
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.github.tomakehurst/wiremock -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>core-java-io-3</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build> </build>
<properties> <properties>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<wiremock.version>2.26.3</wiremock.version>
</properties> </properties>
</project> </project>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,4 +9,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks) - [Adding Shutdown Hooks for JVM Applications](https://www.baeldung.com/jvm-shutdown-hooks)
- [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout) - [boolean and boolean[] Memory Layout in the JVM](https://www.baeldung.com/jvm-boolean-memory-layout)
- [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length) - [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length)
- [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm) - More articles: [[<-- prev]](/core-java-modules/core-java-jvm)

View File

@ -0,0 +1,19 @@
package com.baeldung.loadedclasslisting;
import java.util.Arrays;
public class Launcher {
public static void main(String[] args) {
printClassesLoadedBy("BOOTSTRAP");
printClassesLoadedBy("SYSTEM");
printClassesLoadedBy("EXTENSION");
}
private static void printClassesLoadedBy(String classLoaderType) {
System.out.println(classLoaderType + " ClassLoader : ");
Class<?>[] classes = ListLoadedClassesAgent.listLoadedClasses(classLoaderType);
Arrays.asList(classes)
.forEach(clazz -> System.out.println(clazz.getCanonicalName()));
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.loadedclasslisting;
import java.lang.instrument.Instrumentation;
public class ListLoadedClassesAgent {
private static Instrumentation instrumentation;
public static void premain(String agentArgs, Instrumentation instrumentation) {
ListLoadedClassesAgent.instrumentation = instrumentation;
}
public static Class<?>[] listLoadedClasses(String classLoaderType) {
if (instrumentation == null) {
throw new IllegalStateException(
"ListLoadedClassesAgent is not initialized.");
}
return instrumentation.getInitiatedClasses(
getClassLoader(classLoaderType));
}
private static ClassLoader getClassLoader(String classLoaderType) {
ClassLoader classLoader = null;
switch (classLoaderType) {
case "SYSTEM":
classLoader = ClassLoader.getSystemClassLoader();
break;
case "EXTENSION":
classLoader = ClassLoader.getSystemClassLoader().getParent();
break;
// passing a null value to the Instrumentation : getInitiatedClasses method
// defaults to the bootstrap class loader
case "BOOTSTRAP":
break;
default:
break;
}
return classLoader;
}
}

View File

@ -0,0 +1 @@
Premain-Class: com.baeldung.loadedclasslisting.ListLoadedClassesAgent

View File

@ -37,7 +37,7 @@ public class Human {
public static int compareByNameThenAge(final Human lhs, final Human rhs) { public static int compareByNameThenAge(final Human lhs, final Human rhs) {
if (lhs.name.equals(rhs.name)) { if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age; return Integer.compare(lhs.age, rhs.age);
} else { } else {
return lhs.name.compareTo(rhs.name); return lhs.name.compareTo(rhs.name);
} }

View File

@ -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)); final List<Human> humans = Lists.newArrayList(new Human("Sarah", 12), new Human("Sarah", 10), new Human("Zack", 12));
humans.sort((lhs, rhs) -> { humans.sort((lhs, rhs) -> {
if (lhs.getName().equals(rhs.getName())) { if (lhs.getName().equals(rhs.getName())) {
return lhs.getAge() - rhs.getAge(); return Integer.compare(lhs.getAge(), rhs.getAge());
} else { } else {
return lhs.getName().compareTo(rhs.getName()); return lhs.getName().compareTo(rhs.getName());
} }

View File

@ -3,4 +3,5 @@
This module contains articles about core features in the Java language This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom) - [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [[<-- Prev]](/core-java-modules/core-java-lang-2) - [[<-- Prev]](/core-java-modules/core-java-lang-2)

View File

@ -12,4 +12,12 @@
<artifactId>core-java-lang-oop-types</artifactId> <artifactId>core-java-lang-oop-types</artifactId>
<name>core-java-lang-oop-types</name> <name>core-java-lang-oop-types</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</project> </project>

View File

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

View File

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

View File

@ -45,7 +45,7 @@ public class Player implements Comparable<Player> {
@Override @Override
public int compareTo(Player otherPlayer) { public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking()); return Integer.compare(getRanking(), otherPlayer.getRanking());
} }
} }

View File

@ -6,7 +6,7 @@ public class PlayerAgeComparator implements Comparator<Player> {
@Override @Override
public int compare(Player firstPlayer, Player secondPlayer) { public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge()); return Integer.compare(firstPlayer.getAge(), secondPlayer.getAge());
} }
} }

View File

@ -6,7 +6,7 @@ public class PlayerRankingComparator implements Comparator<Player> {
@Override @Override
public int compare(Player firstPlayer, Player secondPlayer) { public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking()); return Integer.compare(firstPlayer.getRanking(), secondPlayer.getRanking());
} }
} }

View File

@ -0,0 +1,26 @@
package com.baeldung.comparator;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class AvoidingSubtractionUnitTest {
@Test
public void givenTwoPlayers_whenUsingSubtraction_thenOverflow() {
Comparator<Player> comparator = (p1, p2) -> p1.getRanking() - p2.getRanking();
Player player1 = new Player(59, "John", Integer.MAX_VALUE);
Player player2 = new Player(67, "Roger", -1);
List<Player> players = Arrays.asList(player1, player2);
players.sort(comparator);
System.out.println(players);
assertEquals("John", players.get(0).getName());
assertEquals("Roger", players.get(1).getName());
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.comparator; package com.baeldung.comparator;
import static org.junit.Assert.assertEquals; import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import org.junit.Before; import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class Java8ComparatorUnitTest { public class Java8ComparatorUnitTest {
@ -28,7 +28,7 @@ public class Java8ComparatorUnitTest {
@Test @Test
public void whenComparing_UsingLambda_thenSorted() { public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************"); System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking(); Comparator<Player> byRanking = (Player player1, Player player2) -> Integer.compare(player1.getRanking(), player2.getRanking());
System.out.println("Before Sorting : " + footballTeam); System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking); Collections.sort(footballTeam, byRanking);

View File

@ -49,11 +49,11 @@ public class EchoServer {
if (new String(buffer.array()).trim().equals(POISON_PILL)) { if (new String(buffer.array()).trim().equals(POISON_PILL)) {
client.close(); client.close();
System.out.println("Not accepting client messages anymore"); System.out.println("Not accepting client messages anymore");
} else {
buffer.flip();
client.write(buffer);
buffer.clear();
} }
buffer.flip();
client.write(buffer);
buffer.clear();
} }
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException { private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {

View File

@ -0,0 +1,51 @@
import javax.imageio.ImageIO;
import java.awt.Component;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ScreenshotUnitTest {
@Test
public void givenMainScreen_whenTakeScreenshot_thenSaveToFile() throws Exception {
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
File imageFile = File.createTempFile("single-screen", "bmp");
ImageIO.write(capture, "bmp", imageFile);
assertTrue(imageFile.exists());
}
@Test
public void givenMultipleScreens_whenTakeScreenshot_thenSaveToFile() throws Exception {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
BufferedImage capture = new Robot().createScreenCapture(allScreenBounds);
File imageFile = File.createTempFile("all-screens", "bmp");
ImageIO.write(capture, "bmp", imageFile);
assertTrue(imageFile.exists());
}
@Test
public void givenComponent_whenTakeScreenshot_thenSaveToFile(Component component) throws Exception {
Rectangle componentRect = component.getBounds();
BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB);
component.paint(bufferedImage.getGraphics());
File imageFile = File.createTempFile("component-screenshot", "bmp");
ImageIO.write(bufferedImage, "bmp", imageFile);
assertTrue(imageFile.exists());
}
}

View File

@ -1,12 +1,11 @@
package com.baeldung.regex.countmatches; package com.baeldung.regex.countmatches;
import static org.junit.Assert.assertNotEquals; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Unit Test intended to count number of matches of a RegEx using Java 8 and 9. * Unit Test intended to count number of matches of a RegEx using Java 8 and 9.
@ -65,7 +64,7 @@ public class CountMatchesUnitTest {
count++; count++;
} }
assertNotEquals(3, count); assertEquals(2, count);
} }
@Test @Test

View File

@ -9,4 +9,5 @@ This module contains articles about core Java Security
- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing)
- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java)
- [Checksums in Java](https://www.baeldung.com/java-checksums) - [Checksums in Java](https://www.baeldung.com/java-checksums)
- [How to Read PEM File to Get Public and Private Keys](https://www.baeldung.com/java-read-pem-file-keys)
- More articles: [[<-- prev]](/core-java-modules/core-java-security) - More articles: [[<-- prev]](/core-java-modules/core-java-security)

View File

@ -1,13 +1,13 @@
## Core Java Cookbooks and Examples ## Core Java Cookbooks and Examples
### Relevant Articles: ### Relevant Articles:
[Getting Started with Java Properties](http://www.baeldung.com/java-properties) - [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
[Introduction to Java Serialization](http://www.baeldung.com/java-serialization) - [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
[Guide to UUID in Java](http://www.baeldung.com/java-uuid) - [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
[Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
[Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Introduction to Javadoc](http://www.baeldung.com/javadoc)
[Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) - [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid) - [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)

View File

@ -22,6 +22,7 @@
<!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 --> <!-- <module>core-java-11</module> --> <!-- We haven't upgraded to java 11. Fixing in BAEL-10841 -->
<!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 --> <!-- <module>core-java-12</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 --> <!-- <module>core-java-13</module> --> <!-- We haven't upgraded to java 12. Fixing in BAEL-10841 -->
<!-- <module>core-java-14</module> --> <!-- We haven't upgraded to java 14.-->
<module>core-java-8</module> <module>core-java-8</module>
<module>core-java-8-2</module> <module>core-java-8-2</module>
@ -59,11 +60,16 @@
<module>core-java-concurrency-basic</module> <module>core-java-concurrency-basic</module>
<module>core-java-concurrency-basic-2</module> <module>core-java-concurrency-basic-2</module>
<module>core-java-concurrency-collections</module> <module>core-java-concurrency-collections</module>
<module>core-java-concurrency-collections-2</module>
<module>core-java-console</module>
<!--<module>core-java-8-datetime</module>--> <!-- unit test case failure -->
<module>core-java-8-datetime-2</module>
<!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 --> <!-- <module>core-java-date-operations-1</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-date-operations-2</module> <module>core-java-date-operations-2</module>
<!-- We haven't upgraded to java 9. --> <!-- We haven't upgraded to java 9. -->
<!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> --> <!-- <module>core-java-datetime-computations</module> <module>core-java-datetime-conversion</module> <module>core-java-datetime-java8</module> <module>core-java-datetime-string</module> -->
<module>core-java-8-datetime</module>
<module>core-java-exceptions</module> <module>core-java-exceptions</module>
<module>core-java-exceptions-2</module> <module>core-java-exceptions-2</module>

View File

@ -3,6 +3,7 @@
This module contains articles about core Kotlin collections. This module contains articles about core Kotlin collections.
### Relevant articles: ### Relevant articles:
- [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts) - [Split a List Into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
- [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list) - [Finding an Element in a List Using Kotlin](https://www.baeldung.com/kotlin-finding-element-in-list)
- [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) - [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api)
@ -12,3 +13,4 @@ This module contains articles about core Kotlin collections.
- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce) - [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce)
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort) - [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)
- [Working With Lists in Kotlin](https://www.baeldung.com/kotlin/lists) - [Working With Lists in Kotlin](https://www.baeldung.com/kotlin/lists)
- [Iterating Collections by Index in Kotlin](https://www.baeldung.com/kotlin/iterating-collections-by-index)

View File

@ -7,4 +7,5 @@ This module contains articles about Object-Oriented Programming in Kotlin
- [Generics in Kotlin](https://www.baeldung.com/kotlin-generics) - [Generics in Kotlin](https://www.baeldung.com/kotlin-generics)
- [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties) - [Delegated Properties in Kotlin](https://www.baeldung.com/kotlin-delegated-properties)
- [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern) - [Delegation Pattern in Kotlin](https://www.baeldung.com/kotlin-delegation-pattern)
- [Anonymous Inner Classes in Kotlin](https://www.baeldung.com/kotlin/anonymous-inner-classes)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop) - [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang-oop)

View File

@ -0,0 +1,88 @@
package com.baeldung.exceptionhandling
import java.io.IOException
class ExceptionHandling {
fun tryCatchBlock(): Int? {
try {
val message = "Welcome to Kotlin Tutorials"
return message.toInt()
} catch (exception: NumberFormatException) {
println("NumberFormatException in the code")
return null
}
}
fun tryCatchExpression(): Int? {
val number = try {
val message = "Welcome to Kotlin Tutorials"
message.toInt()
} catch (exception: NumberFormatException) {
println("NumberFormatException in the code")
null
}
return number
}
fun multipleCatchBlock(): Int? {
return try {
val result = 25 / 0
result
} catch (exception: NumberFormatException) {
println("NumberFormatException in the code")
null
} catch (exception: ArithmeticException) {
println("ArithmeticException in the code")
null
} catch (exception: Exception) {
println("Exception in the code")
null
}
}
fun nestedTryCatchBlock(): Int? {
return try {
val firstNumber = 50 / 2 * 0
try {
val secondNumber = 100 / firstNumber
secondNumber
} catch (exception: ArithmeticException) {
println("ArithmeticException in the code")
null
}
} catch (exception: NumberFormatException) {
println("NumberFormatException in the code")
null
}
}
fun finallyBlock(): Int? {
return try {
val message = "Welcome to Kotlin Tutorials"
message.toInt()
} catch (exception: NumberFormatException) {
println("NumberFormatException in the code")
null
} finally {
println("In the Finally block")
}
}
fun throwKeyword(): Int {
val message = "Welcome to Kotlin Tutorials"
if (message.length > 10) throw IllegalArgumentException("String is invalid")
else return message.length
}
fun throwExpression(): Int? {
val message: String? = null
return message?.length ?: throw IllegalArgumentException("String is null")
}
@Throws(IOException::class)
fun throwsAnnotation(): String?{
val filePath = null
return filePath ?: throw IOException("File path is invalid")
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.exceptionhandling
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.io.IOException
import kotlin.test.assertNull
class ExceptionHandlingUnitTest {
private val classUnderTest: ExceptionHandling = ExceptionHandling()
@Test
fun givenInvalidConversion_whenTryCatchUsed_thenReturnsCatchBlockValue(){
assertNull(classUnderTest.tryCatchBlock())
}
@Test
fun givenInvalidConversion_whenTryCatchExpressionUsed_thenReturnsCatchBlockValue(){
assertNull(classUnderTest.tryCatchExpression())
}
@Test
fun givenDivisionByZero_whenMultipleCatchUsed_thenReturnsCatchBlockValue(){
assertNull(classUnderTest.multipleCatchBlock())
}
@Test
fun givenDivisionByZero_whenNestedTryCatchUsed_thenReturnsNestedCatchBlockValue(){
assertNull(classUnderTest.nestedTryCatchBlock())
}
@Test
fun givenInvalidConversion_whenTryCatchFinallyUsed_thenReturnsCatchAndFinallyBlock(){
assertNull(classUnderTest.finallyBlock())
}
@Test
fun givenIllegalArgument_whenThrowKeywordUsed_thenThrowsException(){
assertThrows<IllegalArgumentException> { classUnderTest.throwKeyword() }
}
@Test
fun givenIllegalArgument_whenElvisExpressionUsed_thenThrowsException(){
assertThrows<IllegalArgumentException> { classUnderTest.throwExpression() }
}
@Test
fun whenAnnotationUsed_thenThrowsException(){
assertThrows<IOException> { classUnderTest.throwsAnnotation() }
}
}

View File

@ -37,6 +37,16 @@
<artifactId>deeplearning4j-nn</artifactId> <artifactId>deeplearning4j-nn</artifactId>
<version>${dl4j.version}</version> <version>${dl4j.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.datavec/datavec-api --> <!-- https://mvnrepository.com/artifact/org.datavec/datavec-api -->
<dependency> <dependency>
<groupId>org.datavec</groupId> <groupId>org.datavec</groupId>
@ -53,6 +63,7 @@
<properties> <properties>
<dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version --> <dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version -->
<httpclient.version>4.3.5</httpclient.version> <httpclient.version>4.3.5</httpclient.version>
<slf4j.version>1.7.5</slf4j.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,47 @@
package com.baeldung.deeplearning4j.cnn;
import lombok.Getter;
import org.deeplearning4j.datasets.iterator.impl.CifarDataSetIterator;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import java.util.List;
@Getter
class CifarDataSetService implements IDataSetService {
private final InputType inputType = InputType.convolutional(32, 32, 3);
private final int trainImagesNum = 512;
private final int testImagesNum = 128;
private final int trainBatch = 16;
private final int testBatch = 8;
private final CifarDataSetIterator trainIterator;
private final CifarDataSetIterator testIterator;
CifarDataSetService() {
trainIterator = new CifarDataSetIterator(trainBatch, trainImagesNum, true);
testIterator = new CifarDataSetIterator(testBatch, testImagesNum, false);
}
@Override
public DataSetIterator trainIterator() {
return trainIterator;
}
@Override
public DataSetIterator testIterator() {
return testIterator;
}
@Override
public InputType inputType() {
return inputType;
}
@Override
public List<String> labels() {
return trainIterator.getLabels();
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.deeplearning4j.cnn;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.eval.Evaluation;
@Slf4j
class CnnExample {
public static void main(String... args) {
CnnModel network = new CnnModel(new CifarDataSetService(), new CnnModelProperties());
network.train();
Evaluation evaluation = network.evaluate();
log.info(evaluation.stats());
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.deeplearning4j.cnn;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.eval.Evaluation;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import java.util.stream.IntStream;
@Slf4j
class CnnModel {
private final IDataSetService dataSetService;
private final MultiLayerNetwork network;
private final CnnModelProperties properties;
CnnModel(IDataSetService dataSetService, CnnModelProperties properties) {
this.dataSetService = dataSetService;
this.properties = properties;
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.seed(1611)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(properties.getLearningRate())
.regularization(true)
.updater(properties.getOptimizer())
.list()
.layer(0, conv5x5())
.layer(1, pooling2x2Stride2())
.layer(2, conv3x3Stride1Padding2())
.layer(3, pooling2x2Stride1())
.layer(4, conv3x3Stride1Padding1())
.layer(5, pooling2x2Stride1())
.layer(6, dense())
.pretrain(false)
.backprop(true)
.setInputType(dataSetService.inputType())
.build();
network = new MultiLayerNetwork(configuration);
}
void train() {
network.init();
int epochsNum = properties.getEpochsNum();
IntStream.range(1, epochsNum + 1).forEach(epoch -> {
log.info("Epoch {} / {}", epoch, epochsNum);
network.fit(dataSetService.trainIterator());
});
}
Evaluation evaluate() {
return network.evaluate(dataSetService.testIterator());
}
private ConvolutionLayer conv5x5() {
return new ConvolutionLayer.Builder(5, 5)
.nIn(3)
.nOut(16)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride2() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(2, 2)
.build();
}
private ConvolutionLayer conv3x3Stride1Padding2() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(32)
.stride(1, 1)
.padding(2, 2)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride1() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(1, 1)
.build();
}
private ConvolutionLayer conv3x3Stride1Padding1() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(64)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private OutputLayer dense() {
return new OutputLayer.Builder(LossFunctions.LossFunction.MEAN_SQUARED_LOGARITHMIC_ERROR)
.activation(Activation.SOFTMAX)
.weightInit(WeightInit.XAVIER_UNIFORM)
.nOut(dataSetService.labels().size() - 1)
.build();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.deeplearning4j.cnn;
import lombok.Value;
import org.deeplearning4j.nn.conf.Updater;
@Value
class CnnModelProperties {
private final int epochsNum = 512;
private final double learningRate = 0.001;
private final Updater optimizer = Updater.ADAM;
}

View File

@ -0,0 +1,16 @@
package com.baeldung.deeplearning4j.cnn;
import org.deeplearning4j.nn.conf.inputs.InputType;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import java.util.List;
interface IDataSetService {
DataSetIterator trainIterator();
DataSetIterator testIterator();
InputType inputType();
List<String> labels();
}

View File

@ -0,0 +1,3 @@
### Relevant Article:
- [Creating Docker Images with Spring Boot](https://www.baeldung.com/spring-boot-docker-images)

310
docker/docker-spring-boot/mvnw vendored Executable file
View File

@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
docker/docker-spring-boot/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.baeldung.docker</groupId>
<artifactId>spring-boot-docker</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-docker</name>
<description>Demo project showing Spring Boot and Docker</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layers>
<enabled>true</enabled>
</layers>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,15 @@
# To build, run the following command from the top level project directory:
#
# docker build -f src/main/docker/Dockerfile .
FROM adoptopenjdk:11-jre-hotspot as builder
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=layertools -jar application.jar extract
FROM adoptopenjdk:11-jre-hotspot
COPY --from=builder dependencies/ ./
COPY --from=builder snapshot-dependencies/ ./
COPY --from=builder spring-boot-loader/ ./
COPY --from=builder application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

View File

@ -1,14 +1,13 @@
package com.baeldung.multipledb; package com.baeldung.docker;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class MultipleDbApplication { public class DemoApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(MultipleDbApplication.class, args); SpringApplication.run(DemoApplication.class, args);
} }
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.docker;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public ResponseEntity<String> hello()
{
return ResponseEntity.ok("hello2 ");
}
}

5
excelformula/README.md Normal file
View File

@ -0,0 +1,5 @@
## Apache POI
This module contains articles about Apache POI
### Relevant Articles:

View File

@ -1,7 +0,0 @@
## Guava
This module contains articles a Google Guava
### Relevant Articles:
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)

View File

@ -1,8 +1,5 @@
========= ## Guava 18
## Guava and Hamcrest Cookbooks and Examples
### Relevant Articles: ### Relevant Articles:
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
- [Guava 18: Whats New?](http://www.baeldung.com/whats-new-in-guava-18) - [Guava 18: Whats New?](http://www.baeldung.com/whats-new-in-guava-18)

View File

@ -1,5 +1,3 @@
=========
## Guava 19 ## Guava 19

View File

@ -1,4 +1,6 @@
## Guava 21
### Relevant articles: ### Relevant articles:
- [New Stream, Comparator and Collector in Guava 21](http://www.baeldung.com/guava-21-new) - [New Stream, Comparator and Collector in Guava 21](http://www.baeldung.com/guava-21-new)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) - [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)

View File

@ -13,17 +13,8 @@
<relativePath>../</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
</dependencies>
<properties> <properties>
<guava.version>21.0</guava.version> <guava.version>21.0</guava.version>
<jool.version>0.9.12</jool.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,8 @@
## Guava Collections List examples
This module contains articles about list collections in Guava
### Relevant Articles:
- [Partition a List in Java](https://www.baeldung.com/java-list-split)
- [Guava Lists](https://www.baeldung.com/guava-lists)

View File

@ -4,15 +4,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>guava-collections</artifactId> <artifactId>guava-collections-list</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<name>guava-collections</name> <name>guava-collections-list</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -9,9 +9,9 @@
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath> <relativePath>../</relativePath>
</parent> </parent>
<dependencies> <dependencies>

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