[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LowercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
|
||||
|
||||
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.abstractclasses.test;
|
||||
|
||||
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
|
||||
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UppercaseFileReaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
|
||||
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
|
||||
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
|
||||
|
||||
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.asciiart;
|
||||
|
||||
import java.awt.Font;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
|
||||
public class AsciiArtIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
|
||||
AsciiArt asciiArt = new AsciiArt();
|
||||
String text = "BAELDUNG";
|
||||
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
|
||||
|
||||
asciiArt.drawString(text, "*", settings);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.bitwiseoperator.test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class BitwiseOperatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenAndOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 & value2;
|
||||
assertEquals(4, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenOrOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 | value2;
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoIntegers_whenXorOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int value2 = 5;
|
||||
int result = value1 ^ value2;
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneInteger_whenNotOperator_thenNewDecimalNumber() {
|
||||
int value1 = 6;
|
||||
int result = ~value1;
|
||||
assertEquals(result, -7);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenSignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int rightShift = value >> 2;
|
||||
assertEquals(-3, rightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenLeftShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int leftShift = value << 2;
|
||||
assertEquals(-48, leftShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOnePositiveInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = 12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(3, unsignedRightShift);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneNegativeInteger_whenUnsignedRightShiftOperator_thenNewDecimalNumber() {
|
||||
int value = -12;
|
||||
int unsignedRightShift = value >>> 2;
|
||||
assertEquals(1073741821, unsignedRightShift);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.classloader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class CustomClassLoaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
|
||||
|
||||
CustomClassLoader customClassLoader = new CustomClassLoader();
|
||||
Class<?> c = customClassLoader.findClass(PrintClassLoader.class.getName());
|
||||
|
||||
Object ob = c.newInstance();
|
||||
|
||||
Method md = c.getMethod("printClassLoaders");
|
||||
md.invoke(ob);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.classloader;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PrintClassLoaderUnitTest {
|
||||
@Test(expected = ClassNotFoundException.class)
|
||||
public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception {
|
||||
PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance();
|
||||
sampleClassLoader.printClassLoaders();
|
||||
Class.forName(PrintClassLoader.class.getName(), true, PrintClassLoader.class.getClassLoader().getParent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.curltojava;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaCurlExamplesLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenCommand_whenCalled_thenProduceZeroExitCode() throws IOException {
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
InputStream inputStream = process.getInputStream();
|
||||
// Consume the inputStream so the process can exit
|
||||
JavaCurlExamples.consumeInputStream(inputStream);
|
||||
int exitCode = process.exitValue();
|
||||
|
||||
Assert.assertEquals(0, exitCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewCommands_whenCalled_thenCheckIfIsAlive() throws IOException {
|
||||
String command = "curl -X GET https://postman-echo.com/get?foo1=bar1&foo2=bar2";
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
|
||||
processBuilder.directory(new File("/home/"));
|
||||
Process process = processBuilder.start();
|
||||
|
||||
// Re-use processBuilder
|
||||
processBuilder.command(new String[]{"newCommand", "arguments"});
|
||||
|
||||
Assert.assertEquals(true, process.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestPost_thenCheckIfReturnContent() throws IOException {
|
||||
String command = "curl -X POST https://postman-echo.com/post --data foo1=bar1&foo2=bar2";
|
||||
Process process = Runtime.getRuntime().exec(command);
|
||||
|
||||
// Get the POST result
|
||||
String content = JavaCurlExamples.inputStreamToString(process.getInputStream());
|
||||
|
||||
Assert.assertTrue(null != content && !content.isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.deserialization;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InvalidClassException;
|
||||
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DeserializationUnitTest {
|
||||
|
||||
private static final String serializedObj = "rO0ABXNyACljb20uYmFlbGR1bmcuZGVzZXJpYWxpemF0aW9uLkFwcGxlUHJvZHVjdAAAAAAAdMuxAgADTAANaGVhZHBob25lUG9ydHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wADWxpZ2h0bmluZ1BvcnRxAH4AAUwAD3RodW5kZXJib2x0UG9ydHEAfgABeHB0ABFoZWFkcGhvbmVQb3J0MjAyMHQAEWxpZ2h0bmluZ1BvcnQyMDIwdAATdGh1bmRlcmJvbHRQb3J0MjAyMA";
|
||||
|
||||
private static long userDefinedSerialVersionUID = 1234567L;
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the original "AppleProduct" (no exceptions are thrown)
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void testDeserializeObj_compatible() throws IOException, ClassNotFoundException {
|
||||
|
||||
assertEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
|
||||
AppleProduct macBook = new AppleProduct();
|
||||
macBook.headphonePort = "headphonePort2020";
|
||||
macBook.thunderboltPort = "thunderboltPort2020";
|
||||
macBook.lightningPort = "lightningPort2020";
|
||||
|
||||
// serializes the "AppleProduct" object
|
||||
String serializedProduct = SerializationUtility.serializeObjectToString(macBook);
|
||||
|
||||
// deserializes the "AppleProduct" object
|
||||
AppleProduct deserializedProduct = (AppleProduct) DeserializationUtility.deSerializeObjectFromString(serializedProduct);
|
||||
|
||||
assertTrue(deserializedProduct.headphonePort.equalsIgnoreCase(macBook.headphonePort));
|
||||
assertTrue(deserializedProduct.thunderboltPort.equalsIgnoreCase(macBook.thunderboltPort));
|
||||
assertTrue(deserializedProduct.lightningPort.equalsIgnoreCase(macBook.lightningPort));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the deserialization of the modified (non-compatible) "AppleProduct".
|
||||
* The test should result in an InvalidClassException being thrown.
|
||||
*
|
||||
* Note: to run this test:
|
||||
* 1. Modify the value of the serialVersionUID identifier in AppleProduct.java
|
||||
* 2. Remove the @Ignore annotation
|
||||
* 3. Run the test individually (do not run the entire set of tests)
|
||||
* 4. Revert the changes made in 1 & 2 (so that you're able to re-run the tests successfully)
|
||||
*
|
||||
* @throws ClassNotFoundException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Ignore
|
||||
@Test(expected = InvalidClassException.class)
|
||||
public void testDeserializeObj_incompatible() throws ClassNotFoundException, IOException {
|
||||
|
||||
assertNotEquals(userDefinedSerialVersionUID, AppleProduct.getSerialVersionUID());
|
||||
// attempts to deserialize the "AppleProduct" object
|
||||
DeserializationUtility.deSerializeObjectFromString(serializedObj);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.encoding;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CharacterEncodingExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTextFile_whenCalledWithEncodingASCII_thenProduceIncorrectResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.readFile(
|
||||
"src/test/resources/encoding.txt", "US-ASCII"),
|
||||
"The fa<66><61>ade pattern is a software-design pattern commonly used with object-oriented programming.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextFile_whenCalledWithEncodingUTF8_thenProduceCorrectResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.readFile(
|
||||
"src/test/resources/encoding.txt", "UTF-8"),
|
||||
"The façade pattern is a software-design pattern commonly used with object-oriented programming.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterA_whenConvertedtoBinaryWithEncodingASCII_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("A", "US-ASCII"),
|
||||
"1000001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterA_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("A", "UTF-8"),
|
||||
"1000001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingBig5_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "Big5"),
|
||||
"10111011 1111001 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF8_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "UTF-8"),
|
||||
"11101000 10101010 10011110 ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCharacterCh_whenConvertedtoBinaryWithEncodingUTF32_thenProduceResult() throws IOException {
|
||||
Assert.assertEquals(
|
||||
CharacterEncodingExamples.convertToBinary("語", "UTF-32"),
|
||||
"0 0 10001010 10011110 ");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.exceptions;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.classic.spi.LoggingEvent;
|
||||
import ch.qos.logback.core.Appender;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class GlobalExceptionHandlerUnitTest {
|
||||
|
||||
@Mock
|
||||
private Appender<ILoggingEvent> mockAppender;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.addAppender(mockAppender);
|
||||
|
||||
Handler globalExceptionHandler = new Handler();
|
||||
Thread.setDefaultUncaughtExceptionHandler(globalExceptionHandler);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
logger.detachAppender(mockAppender);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArithmeticException_thenUseUncaughtExceptionHandler() throws InterruptedException {
|
||||
|
||||
Thread globalExceptionHandlerThread = new Thread() {
|
||||
public void run() {
|
||||
GlobalExceptionHandler globalExceptionHandlerObj = new GlobalExceptionHandler();
|
||||
globalExceptionHandlerObj.performArithmeticOperation(99, 0);
|
||||
}
|
||||
};
|
||||
|
||||
globalExceptionHandlerThread.start();
|
||||
globalExceptionHandlerThread.join();
|
||||
|
||||
verify(mockAppender).doAppend(captorLoggingEvent.capture());
|
||||
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
|
||||
|
||||
assertThat(loggingEvent.getLevel()).isEqualTo(Level.INFO);
|
||||
assertThat(loggingEvent.getFormattedMessage()).isEqualTo("Unhandled exception caught!");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.externalizable;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ExternalizableUnitTest {
|
||||
|
||||
private final static String OUTPUT_FILE = "externalizable.txt";
|
||||
|
||||
@Test
|
||||
public void whenSerializing_thenUseExternalizable() throws IOException, ClassNotFoundException {
|
||||
|
||||
Country c = new Country();
|
||||
c.setCapital("Yerevan");
|
||||
c.setCode(374);
|
||||
c.setName("Armenia");
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
c.writeExternal(objectOutputStream);
|
||||
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
fileOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
|
||||
Country c2 = new Country();
|
||||
c2.readExternal(objectInputStream);
|
||||
|
||||
objectInputStream.close();
|
||||
fileInputStream.close();
|
||||
|
||||
assertTrue(c2.getCode() == c.getCode());
|
||||
assertTrue(c2.getName().equals(c.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInheritanceSerialization_then_UseExternalizable() throws IOException, ClassNotFoundException {
|
||||
|
||||
Region r = new Region();
|
||||
r.setCapital("Yerevan");
|
||||
r.setCode(374);
|
||||
r.setName("Armenia");
|
||||
r.setClimate("Mediterranean");
|
||||
r.setPopulation(120.000);
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(OUTPUT_FILE);
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
r.writeExternal(objectOutputStream);
|
||||
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
fileOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream(OUTPUT_FILE);
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
|
||||
Region r2 = new Region();
|
||||
r2.readExternal(objectInputStream);
|
||||
|
||||
objectInputStream.close();
|
||||
fileInputStream.close();
|
||||
|
||||
assertTrue(r2.getPopulation() == null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BufferedReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileReaderUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FilesReadAllLinesUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerIntUnitTest {
|
||||
|
||||
protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
|
||||
List<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
|
||||
assertTrue("File does not has 2 lines", numbers.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.fileparser;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ScannerStringUnitTest {
|
||||
|
||||
protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
|
||||
|
||||
@Test
|
||||
public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
|
||||
List<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
|
||||
assertTrue("File does not has 2 lines", lines.size() == 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphTraversalUnitTest {
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
Graph createGraph() {
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex("Bob");
|
||||
graph.addVertex("Alice");
|
||||
graph.addVertex("Mark");
|
||||
graph.addVertex("Rob");
|
||||
graph.addVertex("Maria");
|
||||
graph.addEdge("Bob", "Alice");
|
||||
graph.addEdge("Bob", "Rob");
|
||||
graph.addEdge("Alice", "Mark");
|
||||
graph.addEdge("Rob", "Mark");
|
||||
graph.addEdge("Alice", "Maria");
|
||||
graph.addEdge("Rob", "Maria");
|
||||
return graph;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.grep;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.unix4j.Unix4j;
|
||||
import static org.unix4j.Unix4j.*;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.unix4j.line.Line;
|
||||
import static org.unix4j.unix.Grep.*;
|
||||
import static org.unix4j.unix.cut.CutOption.*;
|
||||
|
||||
public class GrepWithUnix4JIntegrationTest {
|
||||
|
||||
private File fileToGrep;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
final String separator = File.separator;
|
||||
final String filePath = String.join(separator, new String[] { "src", "test", "resources", "dictionary.in" });
|
||||
fileToGrep = new File(filePath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGrepWithSimpleString_thenCorrect() {
|
||||
int expectedLineCount = 4;
|
||||
|
||||
// grep "NINETEEN" dictionary.txt
|
||||
List<Line> lines = Unix4j.grep("NINETEEN", fileToGrep).toLineList();
|
||||
|
||||
assertEquals(expectedLineCount, lines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInverseGrepWithSimpleString_thenCorrect() {
|
||||
int expectedLineCount = 178687;
|
||||
|
||||
// grep -v "NINETEEN" dictionary.txt
|
||||
List<Line> lines = grep(Options.v, "NINETEEN", fileToGrep).toLineList();
|
||||
|
||||
assertEquals(expectedLineCount, lines.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGrepWithRegex_thenCorrect() {
|
||||
int expectedLineCount = 151;
|
||||
|
||||
// grep -c ".*?NINE.*?" dictionary.txt
|
||||
String patternCount = grep(Options.c, ".*?NINE.*?", fileToGrep).cut(fields, ":", 1).toStringResult();
|
||||
|
||||
assertEquals(expectedLineCount, Integer.parseInt(patternCount));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.hexToAscii;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class HexToAsciiUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenHexToAscii() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(asciiString, hexToAscii(hexEquivalent));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAsciiToHex() {
|
||||
String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
|
||||
String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
|
||||
|
||||
assertEquals(hexEquivalent, asciiToHex(asciiString));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static String asciiToHex(String asciiStr) {
|
||||
char[] chars = asciiStr.toCharArray();
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (char ch : chars) {
|
||||
hex.append(Integer.toHexString((int) ch));
|
||||
}
|
||||
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
private static String hexToAscii(String hexStr) {
|
||||
StringBuilder output = new StringBuilder("");
|
||||
for (int i = 0; i < hexStr.length(); i += 2) {
|
||||
String str = hexStr.substring(i, i + 2);
|
||||
output.append((char) Integer.parseInt(str, 16));
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
### Relevant Articles:
|
||||
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.baeldung.java.clock;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class ClockUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemUTC_retrievesInstant() {
|
||||
|
||||
Clock clockUTC = Clock.systemUTC();
|
||||
|
||||
assertEquals(clockUTC.getZone(), ZoneOffset.UTC);
|
||||
assertEquals(clockUTC.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("UTC instant :: " + clockUTC.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytem_retrievesInstant() {
|
||||
|
||||
Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta"));
|
||||
|
||||
assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta"));
|
||||
assertEquals(clockSystem.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("System zone :: " + clockSystem.getZone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemDefaultZone_retrievesInstant() {
|
||||
|
||||
Clock clockSystemDefault = Clock.systemDefaultZone();
|
||||
|
||||
assertEquals(clockSystemDefault.getZone().equals(null), false);
|
||||
assertEquals(clockSystemDefault.instant().equals(null), false);
|
||||
|
||||
LOGGER.debug("System Default instant :: " + clockSystemDefault.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_withSytemUTC_retrievesTimeInMillis() {
|
||||
|
||||
Clock clockMillis = Clock.systemDefaultZone();
|
||||
|
||||
assertEquals(clockMillis.instant().equals(null), false);
|
||||
assertTrue(clockMillis.millis() > 0);
|
||||
|
||||
LOGGER.debug("System Default millis :: " + clockMillis.millis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingOffset_retrievesFutureDate() {
|
||||
|
||||
Clock baseClock = Clock.systemDefaultZone();
|
||||
|
||||
// result clock will be later than baseClock
|
||||
Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72));
|
||||
|
||||
assertEquals(futureClock.instant().equals(null), false);
|
||||
assertTrue(futureClock.millis() > baseClock.millis());
|
||||
|
||||
LOGGER.debug("Future Clock instant :: " + futureClock.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingOffset_retrievesPastDate() {
|
||||
Clock baseClock = Clock.systemDefaultZone();
|
||||
|
||||
// result clock will be later than baseClock
|
||||
Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72));
|
||||
|
||||
assertEquals(pastClock.instant().equals(null), false);
|
||||
assertTrue(pastClock.millis() < baseClock.millis());
|
||||
|
||||
LOGGER.debug("Past Clock instant :: " + pastClock.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTick_retrievesInstant() {
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300));
|
||||
|
||||
assertEquals(clockDefaultZone.instant().equals(null), false);
|
||||
assertEquals(clocktick.instant().equals(null), false);
|
||||
assertTrue(clockDefaultZone.millis() > clocktick.millis());
|
||||
|
||||
LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant());
|
||||
LOGGER.debug("Clock tick instant: " + clocktick.instant());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void givenClock_usingTickDurationNegative_throwsException() {
|
||||
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
Clock.tick(clockDefaultZone, Duration.ofSeconds(-300));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTickSeconds_retrievesInstant() {
|
||||
ZoneId zoneId = ZoneId.of("Asia/Calcutta");
|
||||
Clock tickSeconds = Clock.tickSeconds(zoneId);
|
||||
|
||||
assertEquals(tickSeconds.instant().equals(null), false);
|
||||
LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant());
|
||||
|
||||
tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100));
|
||||
assertEquals(tickSeconds.instant().equals(null), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingTickMinutes_retrievesInstant() {
|
||||
|
||||
Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta"));
|
||||
|
||||
assertEquals(tickMinutes.instant().equals(null), false);
|
||||
LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant());
|
||||
|
||||
tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5));
|
||||
assertEquals(tickMinutes.instant().equals(null), false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingWithZone_retrievesInstant() {
|
||||
|
||||
ZoneId zoneSingapore = ZoneId.of("Asia/Singapore");
|
||||
Clock clockSingapore = Clock.system(zoneSingapore);
|
||||
|
||||
assertEquals(clockSingapore.instant().equals(null), false);
|
||||
LOGGER.debug("clockSingapore instant : " + clockSingapore.instant());
|
||||
|
||||
ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta");
|
||||
Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta);
|
||||
assertEquals(clockCalcutta.instant().equals(null), false);
|
||||
LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClock_usingGetZone_retrievesZoneId() {
|
||||
|
||||
Clock clockDefaultZone = Clock.systemDefaultZone();
|
||||
ZoneId zone = clockDefaultZone.getZone();
|
||||
|
||||
assertEquals(zone.getId().equals(null), false);
|
||||
LOGGER.debug("Default zone instant : " + clockDefaultZone.instant());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.java.currentmethod;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* The class presents various ways of finding the name of currently executed method.
|
||||
*/
|
||||
public class CurrentlyExecutedMethodFinderUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
|
||||
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
||||
assertEquals("givenCurrentThread_whenGetStackTrace_thenFindMethod", stackTrace[1].getMethodName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenException_whenGetStackTrace_thenFindMethod() {
|
||||
String methodName = new Exception().getStackTrace()[0].getMethodName();
|
||||
assertEquals("givenException_whenGetStackTrace_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
|
||||
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
|
||||
assertEquals("givenThrowable_whenGetStacktrace_thenFindMethod", stackTrace[0].getMethodName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
|
||||
String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
|
||||
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocal_whenGetEnclosingMethod_thenFindMethod() {
|
||||
class Local {};
|
||||
String methodName = Local.class.getEnclosingMethod().getName();
|
||||
assertEquals("givenLocal_whenGetEnclosingMethod_thenFindMethod", methodName);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.baeldung.java.properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PropertiesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
String catalogConfigPath = rootPath + "catalog";
|
||||
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
Properties catalogProps = new Properties();
|
||||
catalogProps.load(new FileInputStream(catalogConfigPath));
|
||||
|
||||
String appVersion = appProps.getProperty("version");
|
||||
assertEquals("1.0", appVersion);
|
||||
|
||||
assertEquals("files", catalogProps.getProperty("c1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String iconConfigPath = rootPath + "icons.xml";
|
||||
Properties iconProps = new Properties();
|
||||
iconProps.loadFromXML(new FileInputStream(iconConfigPath));
|
||||
|
||||
assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String appVersion = appProps.getProperty("version");
|
||||
String appName = appProps.getProperty("name", "defaultName");
|
||||
String appGroup = appProps.getProperty("group", "baeldung");
|
||||
String appDownloadAddr = appProps.getProperty("downloadAddr");
|
||||
|
||||
assertEquals("1.0", appVersion);
|
||||
assertEquals("TestApp", appName);
|
||||
assertEquals("baeldung", appGroup);
|
||||
assertNull(appDownloadAddr);
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
float appVerFloat = (float) appProps.get("version");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
appProps.setProperty("name", "NewAppName");
|
||||
appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
|
||||
|
||||
String newAppName = appProps.getProperty("name");
|
||||
assertEquals("NewAppName", newAppName);
|
||||
|
||||
String newAppDownloadAddr = appProps.getProperty("downloadAddr");
|
||||
assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String versionBeforeRemoval = appProps.getProperty("version");
|
||||
assertEquals("1.0", versionBeforeRemoval);
|
||||
|
||||
appProps.remove("version");
|
||||
String versionAfterRemoval = appProps.getProperty("version");
|
||||
assertNull(versionAfterRemoval);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String newAppConfigPropertiesFile = rootPath + "newApp.properties";
|
||||
appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
|
||||
|
||||
String newAppConfigXmlFile = rootPath + "newApp.xml";
|
||||
appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
|
||||
String defaultConfigPath = rootPath + "default.properties";
|
||||
Properties defaultProps = new Properties();
|
||||
defaultProps.load(new FileInputStream(defaultConfigPath));
|
||||
|
||||
String appConfigPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties(defaultProps);
|
||||
appProps.load(new FileInputStream(appConfigPath));
|
||||
|
||||
String appName = appProps.getProperty("name");
|
||||
String appVersion = appProps.getProperty("version");
|
||||
String defaultSite = appProps.getProperty("site");
|
||||
|
||||
assertEquals("1.0", appVersion);
|
||||
assertEquals("TestApp", appName);
|
||||
assertEquals("www.google.com", defaultSite);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
|
||||
|
||||
String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
|
||||
String appPropsPath = rootPath + "app.properties";
|
||||
Properties appProps = new Properties();
|
||||
appProps.load(new FileInputStream(appPropsPath));
|
||||
|
||||
appProps.list(System.out); // list all key-value pairs
|
||||
|
||||
Enumeration<Object> valueEnumeration = appProps.elements();
|
||||
while (valueEnumeration.hasMoreElements()) {
|
||||
System.out.println(valueEnumeration.nextElement());
|
||||
}
|
||||
|
||||
Enumeration<Object> keyEnumeration = appProps.keys();
|
||||
while (keyEnumeration.hasMoreElements()) {
|
||||
System.out.println(keyEnumeration.nextElement());
|
||||
}
|
||||
|
||||
int size = appProps.size();
|
||||
assertEquals(3, size);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
package com.baeldung.java.regex;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegexUnitTest {
|
||||
private static Pattern pattern;
|
||||
private static Matcher matcher;
|
||||
|
||||
@Test
|
||||
public void givenText_whenSimpleRegexMatches_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("foo");
|
||||
Matcher matcher = pattern.matcher("foo");
|
||||
assertTrue(matcher.find());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("foo");
|
||||
Matcher matcher = pattern.matcher("foofoo");
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
matches++;
|
||||
assertEquals(matches, 2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
|
||||
int matches = runTest(".", "foo");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
|
||||
int matches = runTest("foo.", "foofoo");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAny_thenCorrect() {
|
||||
int matches = runTest("[abc]", "b");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
|
||||
int matches = runTest("[abc]", "cab");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
|
||||
int matches = runTest("[bcr]at", "bat cat rat");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNORSet_whenMatchesNon_thenCorrect() {
|
||||
int matches = runTest("[^abc]", "g");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
|
||||
int matches = runTest("[^bcr]at", "sat mat eat");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
|
||||
int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
|
||||
int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
|
||||
int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 28);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
|
||||
int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
|
||||
int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
|
||||
int matches = runTest("[1-3[7-9]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
|
||||
int matches = runTest("[1-6&&[3-9]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
|
||||
int matches = runTest("[0-9&&[^2468]]", "123456789");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDigits_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\d", "123");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonDigits_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\D", "a6c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhiteSpace_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\s", "a c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\S", "a c");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWordCharacter_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\w", "hi!");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonWordCharacter_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\W", "hi!");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\a?", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
|
||||
int matches = runTest("\\a{0,1}", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\a*", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||
int matches = runTest("\\a{0,}", "hi");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
|
||||
int matches = runTest("\\a+", "hi");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
|
||||
int matches = runTest("\\a{1,}", "hi");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifier_whenMatches_thenCorrect() {
|
||||
int matches = runTest("a{3}", "aaaaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
|
||||
int matches = runTest("a{3}", "aa");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
|
||||
int matches = runTest("a{2,3}", "aaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
|
||||
int matches = runTest("a{2,3}?", "aaaa");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect() {
|
||||
int matches = runTest("(\\d\\d)", "12");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect2() {
|
||||
int matches = runTest("(\\d\\d)", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatches_thenCorrect3() {
|
||||
int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
|
||||
int matches = runTest("(\\d\\d)\\1", "1212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
|
||||
int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
|
||||
assertTrue(matches > 0);
|
||||
assertEquals(matches, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
|
||||
int matches = runTest("(\\d\\d)\\1", "1213");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtBeginning_thenCorrect() {
|
||||
int matches = runTest("^dog", "dogs are friendly");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
|
||||
int matches = runTest("^dog", "are dogs are friendly?");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtEnd_thenCorrect() {
|
||||
int matches = runTest("dog$", "Man's best friend is a dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
|
||||
int matches = runTest("dog$", "is a dog man's best friend?");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
|
||||
int matches = runTest("\\bdog\\b", "a dog is friendly");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
|
||||
int matches = runTest("\\bdog\\b", "dog is man's best friend");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
|
||||
int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
|
||||
int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
|
||||
int matches = runTest("\u00E9", "\u0065\u0301");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
|
||||
int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
|
||||
int matches = runTest("dog", "This is a Dog");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||
int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
|
||||
int matches = runTest("(?i)dog", "This is a Dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
|
||||
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
|
||||
int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
|
||||
int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("(.*)");
|
||||
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||
matcher.find();
|
||||
assertEquals("this is a text", matcher.group(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||
matcher.find();
|
||||
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("(?s)(.*)");
|
||||
Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
|
||||
matcher.find();
|
||||
assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
|
||||
int matches = runTest("(.*)", "text");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
|
||||
int matches = runTest("(.*)", "text", Pattern.LITERAL);
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
|
||||
int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
|
||||
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertFalse(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
|
||||
int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
|
||||
int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
|
||||
assertTrue(matches > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMatch_whenGetsIndices_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("dog");
|
||||
Matcher matcher = pattern.matcher("This dog is mine");
|
||||
matcher.find();
|
||||
assertEquals(5, matcher.start());
|
||||
assertEquals(8, matcher.end());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStudyMethodsWork_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("dog");
|
||||
Matcher matcher = pattern.matcher("dogs are friendly");
|
||||
assertTrue(matcher.lookingAt());
|
||||
assertFalse(matcher.matches());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMatchesStudyMethodWorks_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("dog");
|
||||
Matcher matcher = pattern.matcher("dog");
|
||||
assertTrue(matcher.matches());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceFirstWorks_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("dog");
|
||||
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
|
||||
String newStr = matcher.replaceFirst("cat");
|
||||
assertEquals("cats are domestic animals, dogs are friendly", newStr);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceAllWorks_thenCorrect() {
|
||||
Pattern pattern = Pattern.compile("dog");
|
||||
Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
|
||||
String newStr = matcher.replaceAll("cat");
|
||||
assertEquals("cats are domestic animals, cats are friendly", newStr);
|
||||
|
||||
}
|
||||
|
||||
public synchronized static int runTest(String regex, String text) {
|
||||
pattern = Pattern.compile(regex);
|
||||
matcher = pattern.matcher(text);
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
matches++;
|
||||
return matches;
|
||||
}
|
||||
|
||||
public synchronized static int runTest(String regex, String text, int flags) {
|
||||
pattern = Pattern.compile(regex, flags);
|
||||
matcher = pattern.matcher(text);
|
||||
int matches = 0;
|
||||
while (matcher.find())
|
||||
matches++;
|
||||
return matches;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MapAndFlatMap {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenCalledMap_thenProduceList() {
|
||||
List<String> myList = Stream.of("a", "b")
|
||||
.map(String::toUpperCase)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(asList("A", "B"), myList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception {
|
||||
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
|
||||
System.out.println(list);
|
||||
|
||||
System.out.println(list.stream()
|
||||
.flatMap(Collection::stream)
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenCalledMap_thenProduceOptional() {
|
||||
Optional<String> s = Optional.of("test");
|
||||
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
|
||||
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
|
||||
.map(s -> Optional.of("STRING")));
|
||||
|
||||
assertEquals(Optional.of("STRING"), Optional.of("string")
|
||||
.flatMap(s -> Optional.of("STRING")));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DivisibilityUnitTest {
|
||||
|
||||
private static int number;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
number = 40;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumber_whenDivisibleByTwo_thenCorrect() {
|
||||
assertEquals(number % 2, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
@RunWith(value = Parameterized.class)
|
||||
public class ParametrizedUnitTest {
|
||||
|
||||
private int value;
|
||||
private boolean isEven;
|
||||
|
||||
public ParametrizedUnitTest(int value, boolean isEven) {
|
||||
this.value = value;
|
||||
this.isEven = isEven;
|
||||
}
|
||||
|
||||
@Parameters
|
||||
public static Collection<Object[]> data() {
|
||||
Object[][] data = new Object[][]{{1, false}, {2, true}, {4, true}};
|
||||
return Arrays.asList(data);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParametrizedNumber_ifEvenCheckOK_thenCorrect() {
|
||||
Assert.assertEquals(isEven, value % 2 == 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
public class RegistrationUnitTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("Registration successful");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SignInUnitTest {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SignInUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void whenCalledFromSuite_thanOK() {
|
||||
LOGGER.info("SignIn successful");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringCaseUnitTest {
|
||||
|
||||
private static String data;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
data = "HELLO BAELDUNG";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenAllCaps_thenCorrect() {
|
||||
assertEquals(data.toUpperCase(), data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.junit4vstestng;
|
||||
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class })
|
||||
public class SuiteUnitTest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.leapyear;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Year;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeapYearUnitTest {
|
||||
|
||||
//Before Java8
|
||||
@Test
|
||||
public void testLeapYearUsingGregorianCalendar () {
|
||||
Assert.assertFalse(new GregorianCalendar().isLeapYear(2018));
|
||||
}
|
||||
|
||||
//Java 8 and above
|
||||
@Test
|
||||
public void testLeapYearUsingJavaTimeYear () {
|
||||
Assert.assertTrue(Year.isLeap(2012));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBCYearUsingJavaTimeYear () {
|
||||
Assert.assertTrue(Year.isLeap(-4));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWrongLeapYearUsingJavaTimeYear () {
|
||||
Assert.assertFalse(Year.isLeap(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLeapYearInDateUsingJavaTimeYear () {
|
||||
LocalDate date = LocalDate.parse("2020-01-05", DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
Assert.assertTrue(Year.from(date).isLeap());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.manifest;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ExecuteJarFileUnitTest {
|
||||
|
||||
private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n";
|
||||
private static final String SUCCESS_MESSAGE = "AppExample executed!\n";
|
||||
|
||||
@Test
|
||||
public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() {
|
||||
String output = ExecuteJarFile.executeJarWithoutManifestAttribute();
|
||||
assertEquals(ERROR_MESSAGE, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() {
|
||||
String output = ExecuteJarFile.executeJarWithManifestAttribute();
|
||||
assertEquals(SUCCESS_MESSAGE, output);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package com.baeldung.money;
|
||||
|
||||
import org.javamoney.moneta.FastMoney;
|
||||
import org.javamoney.moneta.Money;
|
||||
import org.javamoney.moneta.format.CurrencyStyle;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.money.CurrencyUnit;
|
||||
import javax.money.Monetary;
|
||||
import javax.money.MonetaryAmount;
|
||||
import javax.money.UnknownCurrencyException;
|
||||
import javax.money.convert.CurrencyConversion;
|
||||
import javax.money.convert.MonetaryConversions;
|
||||
import javax.money.format.AmountFormatQueryBuilder;
|
||||
import javax.money.format.MonetaryAmountFormat;
|
||||
import javax.money.format.MonetaryFormats;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class JavaMoneyUnitManualTest {
|
||||
|
||||
@Test
|
||||
public void givenCurrencyCode_whenString_thanExist() {
|
||||
CurrencyUnit usd = Monetary.getCurrency("USD");
|
||||
|
||||
assertNotNull(usd);
|
||||
assertEquals(usd.getCurrencyCode(), "USD");
|
||||
assertEquals(usd.getNumericCode(), 840);
|
||||
assertEquals(usd.getDefaultFractionDigits(), 2);
|
||||
}
|
||||
|
||||
@Test(expected = UnknownCurrencyException.class)
|
||||
public void givenCurrencyCode_whenNoExist_thanThrowsError() {
|
||||
Monetary.getCurrency("AAA");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmounts_whenStringified_thanEquals() {
|
||||
CurrencyUnit usd = Monetary.getCurrency("USD");
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200)
|
||||
.create();
|
||||
Money moneyof = Money.of(12, usd);
|
||||
FastMoney fastmoneyof = FastMoney.of(2, usd);
|
||||
|
||||
assertEquals("USD", usd.toString());
|
||||
assertEquals("USD 200", fstAmtUSD.toString());
|
||||
assertEquals("USD 12", moneyof.toString());
|
||||
assertEquals("USD 2.00000", fastmoneyof.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCurrencies_whenCompared_thanNotequal() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money oneEuro = Money.of(1, "EUR");
|
||||
|
||||
assertFalse(oneEuro.equals(FastMoney.of(1, "EUR")));
|
||||
assertTrue(oneDolar.equals(Money.of(1, "USD")));
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void givenAmount_whenDivided_thanThrowsException() {
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
oneDolar.divide(3);
|
||||
fail(); // if no exception
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmounts_whenSummed_thanCorrect() {
|
||||
List<MonetaryAmount> monetaryAmounts = Arrays.asList(Money.of(100, "CHF"), Money.of(10.20, "CHF"), Money.of(1.15, "CHF"));
|
||||
|
||||
Money sumAmtCHF = (Money) monetaryAmounts
|
||||
.stream()
|
||||
.reduce(Money.of(0, "CHF"), MonetaryAmount::add);
|
||||
|
||||
assertEquals("CHF 111.35", sumAmtCHF.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArithmetic_whenStringified_thanEqualsAmount() {
|
||||
CurrencyUnit usd = Monetary.getCurrency("USD");
|
||||
|
||||
Money moneyof = Money.of(12, usd);
|
||||
MonetaryAmount fstAmtUSD = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency(usd)
|
||||
.setNumber(200.50)
|
||||
.create();
|
||||
MonetaryAmount oneDolar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
Money subtractedAmount = Money
|
||||
.of(1, "USD")
|
||||
.subtract(fstAmtUSD);
|
||||
MonetaryAmount multiplyAmount = oneDolar.multiply(0.25);
|
||||
MonetaryAmount divideAmount = oneDolar.divide(0.25);
|
||||
|
||||
assertEquals("USD", usd.toString());
|
||||
assertEquals("USD 1", oneDolar.toString());
|
||||
assertEquals("USD 200.5", fstAmtUSD.toString());
|
||||
assertEquals("USD 12", moneyof.toString());
|
||||
assertEquals("USD -199.5", subtractedAmount.toString());
|
||||
assertEquals("USD 0.25", multiplyAmount.toString());
|
||||
assertEquals("USD 4", divideAmount.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmount_whenRounded_thanEquals() {
|
||||
MonetaryAmount fstAmtEUR = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("EUR")
|
||||
.setNumber(1.30473908)
|
||||
.create();
|
||||
MonetaryAmount roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
|
||||
assertEquals("EUR 1.30473908", fstAmtEUR.toString());
|
||||
assertEquals("EUR 1.3", roundEUR.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore("Currency providers are not always available")
|
||||
public void givenAmount_whenConversion_thenNotNull() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
CurrencyConversion conversionEUR = MonetaryConversions.getConversion("EUR");
|
||||
|
||||
MonetaryAmount convertedAmountUSDtoEUR = oneDollar.with(conversionEUR);
|
||||
|
||||
assertEquals("USD 1", oneDollar.toString());
|
||||
assertNotNull(convertedAmountUSDtoEUR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocale_whenFormatted_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
MonetaryAmountFormat formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
|
||||
String usFormatted = formatUSD.format(oneDollar);
|
||||
|
||||
assertEquals("USD 1", oneDollar.toString());
|
||||
assertNotNull(formatUSD);
|
||||
assertEquals("USD1.00", usFormatted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmount_whenCustomFormat_thanEquals() {
|
||||
MonetaryAmount oneDollar = Monetary
|
||||
.getDefaultAmountFactory()
|
||||
.setCurrency("USD")
|
||||
.setNumber(1)
|
||||
.create();
|
||||
|
||||
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
|
||||
.of(Locale.US)
|
||||
.set(CurrencyStyle.NAME)
|
||||
.set("pattern", "00000.00 US Dollar")
|
||||
.build());
|
||||
String customFormatted = customFormat.format(oneDollar);
|
||||
|
||||
assertNotNull(customFormat);
|
||||
assertEquals("USD 1", oneDollar.toString());
|
||||
assertEquals("00001.00 US Dollar", customFormatted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.printscreen;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ScreenshotLiveTest {
|
||||
|
||||
private Screenshot screenshot = new Screenshot("Screenshot.jpg");
|
||||
private File file = new File("Screenshot.jpg");
|
||||
|
||||
@Test
|
||||
public void testGetScreenshot() throws Exception {
|
||||
screenshot.getScreenshot(2000);
|
||||
assertTrue(file.exists());
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.baeldung.properties;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MergePropertiesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingIteration_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByIteratingKeySet(propertiesA(), propertiesB());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingPutAll_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByUsingPutAll(propertiesA(), propertiesB());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoProperties_whenMergedUsingStreamAPI_thenAllPropertiesInResult() {
|
||||
Properties globalProperties = mergePropertiesByUsingStreamApi(propertiesB(), propertiesA());
|
||||
|
||||
testMergedProperties(globalProperties);
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByIteratingKeySet(Properties... properties) {
|
||||
Properties mergedProperties = new Properties();
|
||||
for (Properties property : properties) {
|
||||
Set<String> propertyNames = property.stringPropertyNames();
|
||||
for (String name : propertyNames) {
|
||||
String propertyValue = property.getProperty(name);
|
||||
mergedProperties.setProperty(name, propertyValue);
|
||||
}
|
||||
}
|
||||
return mergedProperties;
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByUsingPutAll(Properties... properties) {
|
||||
Properties mergedProperties = new Properties();
|
||||
for (Properties property : properties) {
|
||||
mergedProperties.putAll(property);
|
||||
}
|
||||
return mergedProperties;
|
||||
}
|
||||
|
||||
private Properties mergePropertiesByUsingStreamApi(Properties... properties) {
|
||||
return Stream.of(properties)
|
||||
.collect(Properties::new, Map::putAll, Map::putAll);
|
||||
}
|
||||
|
||||
private Properties propertiesA() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("application.name", "my-app");
|
||||
properties.setProperty("application.version", "1.0");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private Properties propertiesB() {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("property-1", "sample property");
|
||||
properties.setProperty("property-2", "another sample property");
|
||||
return properties;
|
||||
}
|
||||
|
||||
private void testMergedProperties(Properties globalProperties) {
|
||||
assertThat("There should be 4 properties", globalProperties.size(), equalTo(4));
|
||||
assertEquals("Property should be", globalProperties.getProperty("application.name"), "my-app");
|
||||
assertEquals("Property should be", globalProperties.getProperty("application.version"), "1.0");
|
||||
assertEquals("Property should be", globalProperties.getProperty("property-1"), "sample property");
|
||||
assertEquals("Property should be", globalProperties.getProperty("property-2"), "another sample property");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BaeldungReflectionUtilsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
|
||||
Customer customer = new Customer(1, "Himanshu", null, null);
|
||||
|
||||
List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
|
||||
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
|
||||
|
||||
assertTrue(result.size() == expectedFieldNames.size());
|
||||
assertTrue(result.containsAll(expectedFieldNames));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.baeldung.reflection;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PersonAndEmployeeReflectionUnitTest {
|
||||
|
||||
// Fields names
|
||||
private static final String LAST_NAME_FIELD = "lastName";
|
||||
private static final String FIRST_NAME_FIELD = "firstName";
|
||||
private static final String EMPLOYEE_ID_FIELD = "employeeId";
|
||||
private static final String MONTH_EMPLOYEE_REWARD_FIELD = "reward";
|
||||
|
||||
@Test
|
||||
public void givenPersonClass_whenGetDeclaredFields_thenTwoFields() {
|
||||
// When
|
||||
Field[] allFields = Person.class.getDeclaredFields();
|
||||
|
||||
// Then
|
||||
assertEquals(2, allFields.length);
|
||||
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(LAST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(FIRST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeClass_whenGetDeclaredFields_thenOneField() {
|
||||
// When
|
||||
Field[] allFields = Employee.class.getDeclaredFields();
|
||||
|
||||
// Then
|
||||
assertEquals(1, allFields.length);
|
||||
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(EMPLOYEE_ID_FIELD)
|
||||
&& field.getType().equals(int.class))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() {
|
||||
// When
|
||||
Field[] allFields = Employee.class.getSuperclass().getDeclaredFields();
|
||||
|
||||
// Then
|
||||
assertEquals(2, allFields.length);
|
||||
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(LAST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(FIRST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeClass_whenGetDeclaredFieldsOnBothClasses_thenThreeFields() {
|
||||
// When
|
||||
Field[] personFields = Employee.class.getSuperclass().getDeclaredFields();
|
||||
Field[] employeeFields = Employee.class.getDeclaredFields();
|
||||
Field[] allFields = new Field[employeeFields.length + personFields.length];
|
||||
Arrays.setAll(allFields, i -> (i < personFields.length ? personFields[i] : employeeFields[i - personFields.length]));
|
||||
|
||||
// Then
|
||||
assertEquals(3, allFields.length);
|
||||
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(LAST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(FIRST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
assertTrue(Arrays.stream(allFields).anyMatch(field ->
|
||||
field.getName().equals(EMPLOYEE_ID_FIELD)
|
||||
&& field.getType().equals(int.class))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmployeeClass_whenGetDeclaredFieldsOnEmployeeSuperclassWithModifiersFilter_thenOneFields() {
|
||||
// When
|
||||
List<Field> personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields())
|
||||
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Then
|
||||
assertEquals(1, personFields.size());
|
||||
|
||||
assertTrue(personFields.stream().anyMatch(field ->
|
||||
field.getName().equals(LAST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMonthEmployeeClass_whenGetAllFields_thenThreeFields() {
|
||||
// When
|
||||
List<Field> allFields = getAllFields(MonthEmployee.class);
|
||||
|
||||
// Then
|
||||
assertEquals(3, allFields.size());
|
||||
|
||||
assertTrue(allFields.stream().anyMatch(field ->
|
||||
field.getName().equals(LAST_NAME_FIELD)
|
||||
&& field.getType().equals(String.class))
|
||||
);
|
||||
assertTrue(allFields.stream().anyMatch(field ->
|
||||
field.getName().equals(EMPLOYEE_ID_FIELD)
|
||||
&& field.getType().equals(int.class))
|
||||
);
|
||||
assertTrue(allFields.stream().anyMatch(field ->
|
||||
field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD)
|
||||
&& field.getType().equals(double.class))
|
||||
);
|
||||
}
|
||||
|
||||
public List<Field> getAllFields(Class clazz) {
|
||||
if (clazz == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<Field> result = new ArrayList<>(getAllFields(clazz.getSuperclass()));
|
||||
List<Field> filteredFields = Arrays.stream(clazz.getDeclaredFields())
|
||||
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
|
||||
.collect(Collectors.toList());
|
||||
result.addAll(filteredFields);
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.regexp;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class EscapingCharsUnitTest {
|
||||
@Test
|
||||
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo.";
|
||||
|
||||
assertEquals(true, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
|
||||
String strInput = "foof";
|
||||
String strRegex = "foo\\.";
|
||||
|
||||
assertEquals(false, strInput.matches(strRegex));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "\\Q|\\E";
|
||||
|
||||
assertEquals(4, strInput.split(strRegex).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
|
||||
String strInput = "foo|bar|hello|world";
|
||||
String strRegex = "|";
|
||||
|
||||
assertEquals(4, strInput.split(Pattern.quote(strRegex)).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
|
||||
String strInput = "I gave $50 to my brother."
|
||||
+ "He bought candy for $35. Now he has $15 left.";
|
||||
String strRegex = "\\$";
|
||||
String strReplacement = "£";
|
||||
String output = "I gave £50 to my brother."
|
||||
+ "He bought candy for £35. Now he has £15 left.";
|
||||
Pattern p = Pattern.compile(strRegex);
|
||||
Matcher m = p.matcher(strInput);
|
||||
|
||||
assertEquals(output, m.replaceAll(strReplacement));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.baeldung.regexp.optmization;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OptimizedMatcherManualTest {
|
||||
|
||||
private String action;
|
||||
|
||||
private List<String> items;
|
||||
|
||||
private class TimeWrapper {
|
||||
private long time;
|
||||
private long mstimePreCompiled;
|
||||
private long mstimeNotPreCompiled;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
Random random = new Random();
|
||||
items = new ArrayList<String>();
|
||||
long average = 0;
|
||||
|
||||
for (int i = 0; i < 100000; ++i) {
|
||||
StringBuilder s = new StringBuilder();
|
||||
int characters = random.nextInt(7) + 1;
|
||||
for (int k = 0; k < characters; ++ k) {
|
||||
char c = (char)(random.nextInt('Z' - 'A') + 'A');
|
||||
int rep = random.nextInt(95) + 5;
|
||||
for (int j = 0; j < rep; ++ j)
|
||||
s.append(c);
|
||||
average += rep;
|
||||
}
|
||||
items.add(s.toString());
|
||||
}
|
||||
|
||||
average /= 100000;
|
||||
System.out.println("generated data, average length: " + average);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("A*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("A*B*C*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
|
||||
TimeWrapper timeObj = new TimeWrapper();
|
||||
testPatterns("E*C*W*F*", timeObj);
|
||||
assertTrue(timeObj.mstimePreCompiled < timeObj.mstimeNotPreCompiled);
|
||||
}
|
||||
|
||||
private void testPatterns(String regex, TimeWrapper timeObj) {
|
||||
timeObj.time = System.nanoTime();
|
||||
int matched = 0;
|
||||
int unmatched = 0;
|
||||
|
||||
for (String item : this.items) {
|
||||
if (item.matches(regex)) {
|
||||
++matched;
|
||||
}
|
||||
else {
|
||||
++unmatched;
|
||||
}
|
||||
}
|
||||
|
||||
this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
|
||||
|
||||
timeObj.mstimeNotPreCompiled = (System.nanoTime() - timeObj.time) / 1000000;
|
||||
System.out.println(this.action + ": " + timeObj.mstimeNotPreCompiled + "ms");
|
||||
|
||||
timeObj.time = System.nanoTime();
|
||||
|
||||
Matcher matcher = Pattern.compile(regex).matcher("");
|
||||
matched = 0;
|
||||
unmatched = 0;
|
||||
|
||||
for (String item : this.items) {
|
||||
if (matcher.reset(item).matches()) {
|
||||
++matched;
|
||||
}
|
||||
else {
|
||||
++unmatched;
|
||||
}
|
||||
}
|
||||
|
||||
this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
|
||||
|
||||
timeObj.mstimePreCompiled = (System.nanoTime() - timeObj.time) / 1000000;
|
||||
System.out.println(this.action + ": " + timeObj.mstimePreCompiled + "ms");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ExampleResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenGetBundleExampleResourceForLocalePlPl_thenItShouldInheritPropertiesGreetingAndLanguage() {
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
|
||||
ResourceBundle exampleBundle = ResourceBundle.getBundle("com.baeldung.resourcebundle.ExampleResource", plLocale);
|
||||
|
||||
assertTrue(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("toUsdRate", "cities", "greeting", "currency", "language")));
|
||||
assertEquals(exampleBundle.getString("greeting"), "cześć");
|
||||
assertEquals(exampleBundle.getObject("toUsdRate"), new BigDecimal("3.401"));
|
||||
assertArrayEquals(exampleBundle.getStringArray("cities"), new String[] { "Warsaw", "Cracow" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetBundleExampleResourceForLocaleUs_thenItShouldContainOnlyGreeting() {
|
||||
Locale usLocale = Locale.US;
|
||||
|
||||
ResourceBundle exampleBundle = ResourceBundle.getBundle("com.baeldung.resourcebundle.ExampleResource", usLocale);
|
||||
|
||||
assertFalse(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("toUsdRate", "cities", "currency", "language")));
|
||||
assertTrue(exampleBundle.keySet()
|
||||
.containsAll(Arrays.asList("greeting")));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.resourcebundle;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.ResourceBundle;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PropertyResourceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLocaleUsAsDefualt_whenGetBundleForLocalePlPl_thenItShouldContain3ButtonsAnd1Label() {
|
||||
Locale.setDefault(Locale.US);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("pl", "PL"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("backButton", "helloLabel", "cancelButton", "continueButton", "helloLabelNoEncoding")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleUsAsDefualt_whenGetBundleForLocaleFrFr_thenItShouldContainKeys1To3AndKey4() {
|
||||
Locale.setDefault(Locale.US);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("deleteButton", "helloLabel", "cancelButton", "continueButton")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleChinaAsDefualt_whenGetBundleForLocaleFrFr_thenItShouldOnlyContainKeys1To3() {
|
||||
Locale.setDefault(Locale.CHINA);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"));
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("continueButton", "helloLabel", "cancelButton")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleChinaAsDefualt_whenGetBundleForLocaleFrFrAndExampleControl_thenItShouldOnlyContainKey5() {
|
||||
Locale.setDefault(Locale.CHINA);
|
||||
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("fr", "FR"), new ExampleControl());
|
||||
|
||||
assertTrue(bundle.keySet()
|
||||
.containsAll(Arrays.asList("backButton", "helloLabel")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValuesDifferentlyEncoded_whenGetBundleForLocalePlPl_thenItShouldContain3ButtonsAnd1Label() {
|
||||
ResourceBundle bundle = ResourceBundle.getBundle("resourcebundle.resource", new Locale("pl", "PL"));
|
||||
|
||||
assertEquals(bundle.getString("helloLabel"), "cześć");
|
||||
assertEquals(bundle.getString("helloLabelNoEncoding"), "czeÅ\u009BÄ\u0087");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.baeldung.scripting;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.Bindings;
|
||||
import javax.script.Invocable;
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptEngineManager;
|
||||
import javax.script.ScriptException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class NashornUnitTest {
|
||||
|
||||
private ScriptEngine engine;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
engine = new ScriptEngineManager().getEngineByName("nashorn");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void trim() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/trim.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void locations() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/locations.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindProperties() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/bind.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void magicMethods() throws ScriptException {
|
||||
engine.eval("var demo = load('classpath:js/no_such.js');" + "var tmp = demo.doesNotExist;" + "var none = demo.callNonExistingMethod()");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void typedArrays() throws ScriptException {
|
||||
engine.eval(new InputStreamReader(NashornUnitTest.class.getResourceAsStream("/js/typed_arrays.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void basicUsage() throws ScriptException {
|
||||
Object result = engine.eval("var greeting='hello world';" + "print(greeting);" + "greeting");
|
||||
|
||||
Assert.assertEquals("hello world", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsonObjectExample() throws ScriptException {
|
||||
Object obj = engine.eval("Java.asJSONCompatible({ number: 42, greet: 'hello', primes: [2,3,5,7,11,13] })");
|
||||
Map<String, Object> map = (Map<String, Object>) obj;
|
||||
|
||||
Assert.assertEquals("hello", map.get("greet"));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tryCatchGuard() throws ScriptException {
|
||||
engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.failFunc();");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void extensionsExamples() throws ScriptException {
|
||||
String script = "var list = [1, 2, 3, 4, 5];" + "var result = '';" + "for each (var i in list) {" + "result+=i+'-';" + "};" + "print(result);";
|
||||
engine.eval(script);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bindingsExamples() throws ScriptException {
|
||||
Bindings bindings = engine.createBindings();
|
||||
bindings.put("count", 3);
|
||||
bindings.put("name", "baeldung");
|
||||
|
||||
String script = "var greeting='Hello ';" + "for(var i=count;i>0;i--) { " + "greeting+=name + ' '" + "}" + "greeting";
|
||||
|
||||
Object bindingsResult = engine.eval(script, bindings);
|
||||
Assert.assertEquals("Hello baeldung baeldung baeldung ", bindingsResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jvmBoundaryExamples() throws ScriptException, NoSuchMethodException {
|
||||
engine.eval("function composeGreeting(name) {" + "return 'Hello ' + name" + "}");
|
||||
|
||||
Invocable invocable = (Invocable) engine;
|
||||
|
||||
Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung");
|
||||
Assert.assertEquals("Hello baeldung", funcResult);
|
||||
|
||||
Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + "var map = new HashMap();" + "map.put('hello', 'world');" + "map");
|
||||
|
||||
Assert.assertTrue(Map.class.isAssignableFrom(map.getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadExamples() throws ScriptException {
|
||||
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
|
||||
|
||||
Assert.assertEquals(6, ((Double) loadResult).intValue());
|
||||
|
||||
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");
|
||||
|
||||
Assert.assertEquals(6.0, math);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.serialization;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PersonUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(p);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Person p2 = (Person) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(p2.getAge() == p.getAge());
|
||||
assertTrue(p2.getName().equals(p.getName()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomSerializingAndDeserializing_ThenObjectIsTheSame() throws IOException, ClassNotFoundException {
|
||||
Person p = new Person();
|
||||
p.setAge(20);
|
||||
p.setName("Joe");
|
||||
|
||||
Address a = new Address();
|
||||
a.setHouseNumber(1);
|
||||
|
||||
Employee e = new Employee();
|
||||
e.setPerson(p);
|
||||
e.setAddress(a);
|
||||
|
||||
FileOutputStream fileOutputStream = new FileOutputStream("yofile2.txt");
|
||||
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
|
||||
objectOutputStream.writeObject(e);
|
||||
objectOutputStream.flush();
|
||||
objectOutputStream.close();
|
||||
|
||||
FileInputStream fileInputStream = new FileInputStream("yofile2.txt");
|
||||
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
|
||||
Employee e2 = (Employee) objectInputStream.readObject();
|
||||
objectInputStream.close();
|
||||
|
||||
assertTrue(e2.getPerson().getAge() == e.getPerson().getAge());
|
||||
assertTrue(e2.getAddress().getHouseNumber() == (e.getAddress().getHouseNumber()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.baeldung.stack;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Stack;
|
||||
|
||||
import org.junit.Test;
|
||||
public class StackUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenStackIsCreated_thenItHasSize0() {
|
||||
Stack intStack = new Stack();
|
||||
assertEquals(0, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStack_whenElementIsPushed_thenStackSizeisIncreased() {
|
||||
Stack intStack = new Stack();
|
||||
intStack.push(1);
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyStack_whenMultipleElementsArePushed_thenStackSizeisIncreased() {
|
||||
Stack intStack = new Stack();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
boolean result = intStack.addAll(intList);
|
||||
assertTrue(result);
|
||||
assertEquals(7, intList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.pop();
|
||||
assertTrue(intStack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.peek();
|
||||
assertEquals(1, intStack.search(5));
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
assertEquals(1, intStack.search(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenElementIsOnStack_thenIndexOfReturnsItsIndex() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
int indexOf = intStack.indexOf(5);
|
||||
assertEquals(0, indexOf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleElementsAreOnStack_thenIndexOfReturnsLastElementIndex() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
int lastIndexOf = intStack.lastIndexOf(5);
|
||||
assertEquals(2, lastIndexOf);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementOnStack_whenRemoveElementIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.push(5);
|
||||
intStack.removeElement(5);
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementOnStack_whenRemoveElementAtIsInvoked_thenElementIsRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.push(7);
|
||||
intStack.removeElementAt(1);
|
||||
assertEquals(-1, intStack.search(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveAllElementsIsInvoked_thenAllElementsAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
intStack.push(5);
|
||||
intStack.push(7);
|
||||
intStack.removeAllElements();
|
||||
assertTrue(intStack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveAllIsInvoked_thenAllElementsFromCollectionAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
intStack.add(500);
|
||||
intStack.removeAll(intList);
|
||||
assertEquals(1, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElementsOnStack_whenRemoveIfIsInvoked_thenAllElementsSatysfyingConditionAreRemoved() {
|
||||
Stack<Integer> intStack = new Stack();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
intStack.removeIf(element -> element < 6);
|
||||
assertEquals(2, intStack.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAnotherStackCreatedWhileTraversingStack_thenStacksAreEqual() {
|
||||
Stack<Integer> intStack = new Stack<>();
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
|
||||
intStack.addAll(intList);
|
||||
ListIterator<Integer> it = intStack.listIterator();
|
||||
Stack<Integer> result = new Stack();
|
||||
while(it.hasNext()) {
|
||||
result.push(it.next());
|
||||
}
|
||||
|
||||
assertThat(result, equalTo(intStack));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.system;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
@Ignore
|
||||
public class WhenDetectingOSUnitTest {
|
||||
|
||||
private DetectOS os = new DetectOS();
|
||||
|
||||
@Test
|
||||
public void whenUsingSystemProperty_shouldReturnOS() {
|
||||
String expected = "Windows 10";
|
||||
String actual = os.getOperatingSystem();
|
||||
Assert.assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSystemUtils_shouldReturnOS() {
|
||||
String expected = "Windows 10";
|
||||
String actual = os.getOperatingSystemSystemUtils();
|
||||
Assert.assertEquals(expected, actual);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.util;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PropertiesLoaderUnitTest {
|
||||
|
||||
@Test
|
||||
public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException {
|
||||
//given
|
||||
final String RESOURCE_FILE_NAME = "configuration.properties";
|
||||
|
||||
final String SAMPLE_CONF_ENTRY = "sampleConfEntry";
|
||||
final String COLON_SEPARATED_CONF_ENTRY = "colonSeparatedEntry";
|
||||
|
||||
final String GIVEN_CONF_ENTRY_VALUE = "sample String value";
|
||||
final String COLON_SEPARATED_CONF_ENTRY_VALUE = "colon separated entry value";
|
||||
|
||||
//when
|
||||
Properties config = PropertiesLoader.loadProperties(RESOURCE_FILE_NAME);
|
||||
|
||||
String sampleConfEntryValue = config.getProperty(SAMPLE_CONF_ENTRY);
|
||||
String colonSeparatedConfEntryValue = config.getProperty(COLON_SEPARATED_CONF_ENTRY);
|
||||
|
||||
//then
|
||||
assertEquals(GIVEN_CONF_ENTRY_VALUE, sampleConfEntryValue);
|
||||
assertEquals(COLON_SEPARATED_CONF_ENTRY_VALUE, colonSeparatedConfEntryValue);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.LineIterator;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.io.Files;
|
||||
|
||||
@Ignore("need large file for testing")
|
||||
public class JavaIoUnitTest {
|
||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
// tests - iterate lines in a file
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenIteratingAFile_thenCorrect() throws IOException {
|
||||
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
|
||||
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
|
||||
|
||||
logMemory();
|
||||
Files.readLines(new File(path), Charsets.UTF_8);
|
||||
logMemory();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIo_whenIteratingAFileInMemory_thenCorrect() throws IOException {
|
||||
// final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
|
||||
final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
|
||||
|
||||
logMemory();
|
||||
FileUtils.readLines(new File(path));
|
||||
logMemory();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenStreamingThroughAFile_thenCorrect() throws IOException {
|
||||
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
|
||||
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
|
||||
|
||||
logMemory();
|
||||
|
||||
FileInputStream inputStream = null;
|
||||
Scanner sc = null;
|
||||
try {
|
||||
inputStream = new FileInputStream(path);
|
||||
sc = new Scanner(inputStream, "UTF-8");
|
||||
while (sc.hasNextLine()) {
|
||||
final String line = sc.nextLine();
|
||||
// System.out.println(line);
|
||||
}
|
||||
// note that Scanner suppresses exceptions
|
||||
if (sc.ioException() != null) {
|
||||
throw sc.ioException();
|
||||
}
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
if (sc != null) {
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
|
||||
logMemory();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingApacheIo_whenStreamingThroughAFile_thenCorrect() throws IOException {
|
||||
final String path = "G:\\full\\train\\input\\" + "trainDataNegative.csv";
|
||||
// final String path = "G:\\full\\train\\input\\" + "trainDataPositive.csv";
|
||||
|
||||
logMemory();
|
||||
|
||||
final LineIterator it = FileUtils.lineIterator(new File(path), "UTF-8");
|
||||
try {
|
||||
while (it.hasNext()) {
|
||||
final String line = it.nextLine();
|
||||
// do something with line
|
||||
}
|
||||
} finally {
|
||||
LineIterator.closeQuietly(it);
|
||||
}
|
||||
|
||||
logMemory();
|
||||
}
|
||||
|
||||
// utils
|
||||
|
||||
private final void logMemory() {
|
||||
logger.info("Max Memory: {} Mb", Runtime.getRuntime()
|
||||
.maxMemory() / 1048576);
|
||||
logger.info("Total Memory: {} Mb", Runtime.getRuntime()
|
||||
.totalMemory() / 1048576);
|
||||
logger.info("Free Memory: {} Mb", Runtime.getRuntime()
|
||||
.freeMemory() / 1048576);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class JavaTimerLongRunningUnitTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaTimerLongRunningUnitTest.class);
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingTaskOnce_thenCorrect() throws InterruptedException {
|
||||
final TimerTask timerTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on: " + new Date() + "\n" + "Thread's name: " + Thread.currentThread()
|
||||
.getName());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
final long delay = 1000L;
|
||||
timer.schedule(timerTask, delay);
|
||||
|
||||
Thread.sleep(delay * 2);
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingRepeatedTask_thenCorrect() throws InterruptedException {
|
||||
final TimerTask repeatedTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
final long delay = 1000L;
|
||||
final long period = 1000L;
|
||||
timer.scheduleAtFixedRate(repeatedTask, delay, period);
|
||||
|
||||
Thread.sleep(delay * 2);
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingDailyTask_thenCorrect() throws InterruptedException {
|
||||
final TimerTask repeatedTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
final long delay = 1000L;
|
||||
final long period = 1000L * 60L * 60L * 24L;
|
||||
timer.scheduleAtFixedRate(repeatedTask, delay, period);
|
||||
|
||||
Thread.sleep(delay * 2);
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenCancelingTimerTask_thenCorrect() throws InterruptedException {
|
||||
final TimerTask task = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
cancel();
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
final long delay = 1000L;
|
||||
final long period = 1000L;
|
||||
timer.scheduleAtFixedRate(task, delay, period);
|
||||
|
||||
Thread.sleep(delay * 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenStoppingThread_thenTimerTaskIsCancelled() throws InterruptedException {
|
||||
final TimerTask task = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
timer.scheduleAtFixedRate(task, 1000L, 1000L);
|
||||
|
||||
Thread.sleep(1000L * 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenCancelingTimer_thenCorrect() throws InterruptedException {
|
||||
final TimerTask task = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer");
|
||||
|
||||
timer.scheduleAtFixedRate(task, 1000L, 1000L);
|
||||
|
||||
Thread.sleep(1000L * 2);
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingExecutorService_whenSchedulingRepeatedTask_thenCorrect() throws InterruptedException {
|
||||
final TimerTask repeatedTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Task performed on " + new Date());
|
||||
}
|
||||
};
|
||||
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
|
||||
final long delay = 1000L;
|
||||
final long period = 1000L;
|
||||
executor.scheduleAtFixedRate(repeatedTask, delay, period, TimeUnit.MILLISECONDS);
|
||||
Thread.sleep(delay + period * 3);
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.baeldung.java.arrays;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ArraysJoinAndSplitJUnitTest {
|
||||
|
||||
private final String[] sauces = { "Marinara", "Olive Oil" };
|
||||
private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" };
|
||||
private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" };
|
||||
|
||||
private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" };
|
||||
|
||||
@Test
|
||||
public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
|
||||
String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
|
||||
|
||||
System.arraycopy(sauces, 0, toppings, 0, sauces.length);
|
||||
int AddedSoFar = sauces.length;
|
||||
|
||||
System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
|
||||
AddedSoFar += cheeses.length;
|
||||
|
||||
System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
|
||||
|
||||
Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
|
||||
int ordersHalved = (customers.length / 2) + (customers.length % 2);
|
||||
|
||||
String[] driverOne = Arrays.copyOf(customers, ordersHalved);
|
||||
String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
|
||||
|
||||
Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" });
|
||||
Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.baeldung.java.rawtypes;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RawTypesUnitTest {
|
||||
@Test
|
||||
public void shouldCreateListUsingRawTypes() {
|
||||
@SuppressWarnings("rawtypes")
|
||||
List myList = new ArrayList();
|
||||
myList.add(new Object());
|
||||
myList.add("2");
|
||||
myList.add(new Integer(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package org.baeldung.java.sandbox;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class SandboxJavaManualTest {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SandboxJavaManualTest.class);
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingTimerTaskOnce_thenCorrect() throws InterruptedException {
|
||||
final TimerTask timerTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
LOG.debug("Time when was task performed" + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Thread's name");
|
||||
LOG.debug("Current time:" + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
final long delay = 2L * 1000L;
|
||||
timer.schedule(timerTask, delay);
|
||||
Thread.sleep(delay);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingRepeatedTask_thenCorrect() throws InterruptedException {
|
||||
final TimerTask repeatedTask = new TimerTask() {
|
||||
int count = 0;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
count++;
|
||||
LOG.debug("Time when task was performed: " + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
if (count >= 5) {
|
||||
cancel();
|
||||
}
|
||||
}
|
||||
};
|
||||
final Timer timer = new Timer("Timer thread");
|
||||
LOG.debug("Current time: " + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
final long delay = 2L * 1000L;
|
||||
final long period = 1L * 1000L;
|
||||
timer.scheduleAtFixedRate(repeatedTask, delay, period);
|
||||
Thread.sleep(delay + period * 5L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingTimer_whenSchedulingRepeatedCustomTimerTask_thenCorrect() throws InterruptedException {
|
||||
class MyTask extends TimerTask {
|
||||
long timesToRun = 0;
|
||||
long timesRunned = 0;
|
||||
|
||||
public void setTimesToRun(final int timesToRun) {
|
||||
this.timesToRun = timesToRun;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
timesRunned++;
|
||||
LOG.debug("Task performed on: " + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
if (timesRunned >= timesToRun) {
|
||||
cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
final MyTask repeatedTask = new MyTask();
|
||||
repeatedTask.setTimesToRun(5);
|
||||
final long delay = 2L * 1000L;
|
||||
final long period = 1000L;
|
||||
final Timer timer = new Timer("Timer");
|
||||
LOG.debug("Current time: " + new Date());
|
||||
LOG.debug("Thread's name: " + Thread.currentThread().getName());
|
||||
timer.scheduleAtFixedRate(repeatedTask, delay, period);
|
||||
Thread.sleep(delay + period * repeatedTask.timesToRun);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.baeldung.java.shell;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class JavaProcessUnitIntegrationTest {
|
||||
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
|
||||
|
||||
private static class StreamGobbler implements Runnable {
|
||||
private InputStream inputStream;
|
||||
private Consumer<String> consumer;
|
||||
|
||||
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
|
||||
this.inputStream = inputStream;
|
||||
this.consumer = consumer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer);
|
||||
}
|
||||
}
|
||||
|
||||
private Consumer<String> consumer = Assert::assertNotNull;
|
||||
|
||||
private String homeDirectory = System.getProperty("user.home");
|
||||
|
||||
@Test
|
||||
public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception {
|
||||
Process process;
|
||||
if (IS_WINDOWS) {
|
||||
process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory));
|
||||
} else {
|
||||
process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory));
|
||||
}
|
||||
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
|
||||
Executors.newSingleThreadExecutor().submit(streamGobbler);
|
||||
int exitCode = process.waitFor();
|
||||
Assert.assertEquals(0, exitCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception {
|
||||
ProcessBuilder builder = new ProcessBuilder();
|
||||
if (IS_WINDOWS) {
|
||||
builder.command("cmd.exe", "/c", "dir");
|
||||
} else {
|
||||
builder.command("sh", "-c", "ls");
|
||||
}
|
||||
builder.directory(new File(homeDirectory));
|
||||
Process process = builder.start();
|
||||
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
|
||||
Executors.newSingleThreadExecutor().submit(streamGobbler);
|
||||
int exitCode = process.waitFor();
|
||||
Assert.assertEquals(0, exitCode);
|
||||
}
|
||||
}
|
||||
13
core-java-modules/core-java/src/test/resources/.gitignore
vendored
Normal file
13
core-java-modules/core-java/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -0,0 +1,3 @@
|
||||
version=1.0
|
||||
name=TestApp
|
||||
date=2016-11-12
|
||||
3
core-java-modules/core-java/src/test/resources/catalog
Normal file
3
core-java-modules/core-java/src/test/resources/catalog
Normal file
@@ -0,0 +1,3 @@
|
||||
c1=files
|
||||
c2=images
|
||||
c3=videos
|
||||
@@ -0,0 +1,4 @@
|
||||
# this is sample property file for PropertiesLoaderTest configuration needs
|
||||
! this is also a comment
|
||||
sampleConfEntry = sample String value
|
||||
colonSeparatedEntry : colon separated entry value
|
||||
@@ -0,0 +1,4 @@
|
||||
site=www.google.com
|
||||
name=DefaultAppName
|
||||
topic=Properties
|
||||
category=core-java
|
||||
178691
core-java-modules/core-java/src/test/resources/dictionary.in
Normal file
178691
core-java-modules/core-java/src/test/resources/dictionary.in
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
The façade pattern is a software-design pattern commonly used with object-oriented programming.
|
||||
8
core-java-modules/core-java/src/test/resources/icons.xml
Normal file
8
core-java-modules/core-java/src/test/resources/icons.xml
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
|
||||
<properties>
|
||||
<comment>xml example</comment>
|
||||
<entry key="fileIcon">icon1.jpg</entry>
|
||||
<entry key="imageIcon">icon2.jpg</entry>
|
||||
<entry key="videoIcon">icon3.jpg</entry>
|
||||
</properties>
|
||||
@@ -0,0 +1,2 @@
|
||||
#Copy a File with Java (www.Baeldung.com)
|
||||
Copying Files with Java is Fun!
|
||||
@@ -0,0 +1,2 @@
|
||||
111
|
||||
222
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello
|
||||
World
|
||||
1
core-java-modules/core-java/src/test/resources/test.find
Normal file
1
core-java-modules/core-java/src/test/resources/test.find
Normal file
@@ -0,0 +1 @@
|
||||
Test of JNDI on file.
|
||||
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
@@ -0,0 +1 @@
|
||||
Hello world 1
|
||||
@@ -0,0 +1 @@
|
||||
2,3 4
|
||||
@@ -0,0 +1 @@
|
||||
Hello 1
|
||||
BIN
core-java-modules/core-java/src/test/resources/test_read4.in
Normal file
BIN
core-java-modules/core-java/src/test/resources/test_read4.in
Normal file
Binary file not shown.
@@ -0,0 +1 @@
|
||||
青空
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Test line
|
||||
@@ -0,0 +1 @@
|
||||
John,Adam-Tom
|
||||
@@ -0,0 +1,2 @@
|
||||
Hello world
|
||||
Hi, John
|
||||
Reference in New Issue
Block a user