Merge remote-tracking branch 'upstream/master' into BAEL_4302

This commit is contained in:
root 2020-08-13 15:51:21 +00:00
commit 9230a93045
724 changed files with 7232 additions and 2310 deletions

1
.gitignore vendored
View File

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

View File

@ -11,3 +11,4 @@ This module contains articles about searching algorithms.
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
- [Topological Sort of Directed Acyclic Graph](https://www.baeldung.com/cs/dag-topological-sort)

View File

@ -7,4 +7,3 @@ This module contains articles about Apache CXF
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)

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

@ -14,3 +14,4 @@ This module contains articles about core Java features that have been introduced
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Multi-Release JAR Files with Maven](https://www.baeldung.com/maven-multi-release-jars)
- [The Difference between RxJava API and the Java 9 Flow API](https://www.baeldung.com/rxjava-vs-java-flow-api)
- [How to Get a Name of a Method Being Executed?](https://www.baeldung.com/java-name-of-executing-method)

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

@ -16,6 +16,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>${jol-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
@ -37,6 +42,7 @@
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<assertj.version>3.11.1</assertj.version>
<jol-core.version>0.10</jol-core.version>
</properties>
</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>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>

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

@ -15,7 +15,15 @@ import java.util.logging.Logger;
import static org.junit.Assert.fail;
public class PrimeNumbersUnitManualTest {
/**
* This test expects the file target/test-classes/META-INF/BenchmarkList to be present.
*
* Before running the test ensure that the file is present.
* If not, please run mvn install on the module.
*
*/
public class PrimeNumbersManualTest {
private static Logger logger = Logger.getAnonymousLogger();

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

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

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

View File

@ -46,41 +46,14 @@
<version>${assertj.version}</version>
<scope>test</scope>
</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>
<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>
<properties>
<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>
</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

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

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

@ -49,11 +49,11 @@ public class EchoServer {
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
client.close();
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 {

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

@ -0,0 +1,183 @@
package com.baeldung.reflection.set.fields;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.baeldung.reflection.access.privatefields.Person;
public class SetFieldsUsingReflectionUnitTest {
@Test
public void whenSetIntegerFields_thenSuccess() throws Exception {
Person person = new Person();
Field ageField = person.getClass()
.getDeclaredField("age");
ageField.setAccessible(true);
byte age = 26;
ageField.setByte(person, age);
Assertions.assertEquals(age, person.getAge());
Field uidNumberField = person.getClass()
.getDeclaredField("uidNumber");
uidNumberField.setAccessible(true);
short uidNumber = 5555;
uidNumberField.setShort(person, uidNumber);
Assertions.assertEquals(uidNumber, person.getUidNumber());
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
int pinCode = 411057;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
Field contactNumberField = person.getClass()
.getDeclaredField("contactNumber");
contactNumberField.setAccessible(true);
long contactNumber = 123456789L;
contactNumberField.setLong(person, contactNumber);
Assertions.assertEquals(contactNumber, person.getContactNumber());
}
@Test
public void whenDoUnboxing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
Integer pinCode = 411057;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
}
@Test
public void whenDoNarrowing_thenSuccess() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
short pinCode = 4110;
pinCodeField.setInt(person, pinCode);
Assertions.assertEquals(pinCode, person.getPinCode());
}
@Test
public void whenSetFloatingTypeFields_thenSuccess() throws Exception {
Person person = new Person();
Field heightField = person.getClass()
.getDeclaredField("height");
heightField.setAccessible(true);
float height = 6.1242f;
heightField.setFloat(person, height);
Assertions.assertEquals(height, person.getHeight());
Field weightField = person.getClass()
.getDeclaredField("weight");
weightField.setAccessible(true);
double weight = 75.2564;
weightField.setDouble(person, weight);
Assertions.assertEquals(weight, person.getWeight());
}
@Test
public void whenSetCharacterFields_thenSuccess() throws Exception {
Person person = new Person();
Field genderField = person.getClass()
.getDeclaredField("gender");
genderField.setAccessible(true);
char gender = 'M';
genderField.setChar(person, gender);
Assertions.assertEquals(gender, person.getGender());
}
@Test
public void whenSetBooleanFields_thenSuccess() throws Exception {
Person person = new Person();
Field activeField = person.getClass()
.getDeclaredField("active");
activeField.setAccessible(true);
activeField.setBoolean(person, true);
Assertions.assertTrue(person.isActive());
}
@Test
public void whenSetObjectFields_thenSuccess() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
String name = "Umang Budhwar";
nameField.set(person, name);
Assertions.assertEquals(name, person.getName());
}
@Test
public void givenInt_whenSetStringField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
nameField.setAccessible(true);
Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.setInt(person, 26));
}
@Test
public void givenInt_whenSetLongField_thenIllegalArgumentException() throws Exception {
Person person = new Person();
Field pinCodeField = person.getClass()
.getDeclaredField("pinCode");
pinCodeField.setAccessible(true);
long pinCode = 411057L;
Assertions.assertThrows(IllegalArgumentException.class, () -> pinCodeField.setLong(person, pinCode));
}
@Test
public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception {
Person person = new Person();
Field nameField = person.getClass()
.getDeclaredField("name");
Assertions.assertThrows(IllegalAccessException.class, () -> nameField.set(person, "Umang Budhwar"));
}
@Test
public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass()
.getDeclaredField("firstName"));
}
@Test
public void whenAccessingNullProperty_thenNullPointerException() throws Exception {
Person person = new Person();
Assertions.assertThrows(NullPointerException.class, () -> person.getClass()
.getDeclaredField(null));
}
}

View File

@ -1,12 +1,11 @@
package com.baeldung.regex.countmatches;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import java.util.regex.Matcher;
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.
@ -65,7 +64,7 @@ public class CountMatchesUnitTest {
count++;
}
assertNotEquals(3, count);
assertEquals(2, count);
}
@Test

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>
<version>${dl4j.version}</version>
</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 -->
<dependency>
<groupId>org.datavec</groupId>
@ -53,6 +63,7 @@
<properties>
<dl4j.version>0.9.1</dl4j.version> <!-- Latest non beta version -->
<httpclient.version>4.3.5</httpclient.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
</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)

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 and Hamcrest Cookbooks and Examples
## Guava 18
### 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)

View File

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

View File

@ -1,4 +1,6 @@
## Guava 21
### Relevant articles:
- [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)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)

View File

@ -13,17 +13,8 @@
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
</dependencies>
<properties>
<guava.version>21.0</guava.version>
<jool.version>0.9.12</jool.version>
</properties>
</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"
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>
<artifactId>guava-collections</artifactId>
<artifactId>guava-collections-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-collections</name>
<name>guava-collections-list</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

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

View File

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

View File

@ -8,9 +8,8 @@ This module contains articles about Google Guava collections
- [Guava Ordering Cookbook](https://www.baeldung.com/guava-order)
- [Guide to Guavas Ordering](https://www.baeldung.com/guava-ordering)
- [Hamcrest Collections Cookbook](https://www.baeldung.com/hamcrest-collections-arrays)
- [Partition a List in Java](https://www.baeldung.com/java-list-split)
- [Filtering and Transforming Collections in Guava](https://www.baeldung.com/guava-filter-and-transform-a-collection)
- [Guava Join and Split Collections](https://www.baeldung.com/guava-joiner-and-splitter-tutorial)
- [Guava Lists](https://www.baeldung.com/guava-lists)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Guide to Guava Table](https://www.baeldung.com/guava-table)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)

View File

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>guava-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>guava-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>${jool.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<jool.version>0.9.12</jool.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
<junit-jupiter.version>5.6.2</junit-jupiter.version>
</properties>
</project>

View File

@ -0,0 +1,10 @@
## Guava Core
This module contains articles about core or base functionality provided by Google Guava
### Relevant Articles:
- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables)
- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher)
- [Guide to Guavas PreConditions](https://www.baeldung.com/guava-preconditions)
- [Introduction to Guava Memoizer](https://www.baeldung.com/guava-memoizer)
- [Guava Functional Cookbook](https://www.baeldung.com/guava-functions-predicates)

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