JAVA-1522 Split core-java-modules/core-java module

This commit is contained in:
mikr
2020-06-07 16:52:25 +02:00
parent 4cb07819f3
commit aece4e5216
28 changed files with 10 additions and 86 deletions

View File

@@ -1,47 +0,0 @@
package com.baeldung.graph;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class GraphUnitTest {
@Test
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
Graph graph = createGraph();
assertEquals("[Bob, Rob, Maria, Alice, Mark]",
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
}
@Test
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
Graph graph = createGraph();
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
}
@Test
public void givenAGraph_whenRemoveVertex_thenVertedNotFound() {
Graph graph = createGraph();
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
graph.removeVertex("Maria");
assertEquals("[Bob, Alice, Rob, Mark]",
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;
}
}

View File

@@ -1,46 +0,0 @@
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();
}
}

View File

@@ -1,2 +0,0 @@
### Relevant Articles:
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)

View File

@@ -1,43 +0,0 @@
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);
}
}

View File

@@ -1,41 +0,0 @@
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());
}
}

View File

@@ -1,183 +0,0 @@
package com.baeldung.stack;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
import java.util.Stack;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class StackUnitTest {
@Test
public void whenStackIsCreated_thenItHasSizeZero() {
Stack<Integer> intStack = new Stack<>();
assertEquals(0, intStack.size());
}
@Test
public void whenElementIsPushed_thenStackSizeIsIncreased() {
Stack<Integer> intStack = new Stack<>();
intStack.push(1);
assertEquals(1, intStack.size());
}
@Test
public void whenMultipleElementsArePushed_thenStackSizeIsIncreased() {
Stack<Integer> 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);
Integer element = intStack.pop();
assertEquals(Integer.valueOf(5), element);
assertTrue(intStack.isEmpty());
}
@Test
public void whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() {
Stack<Integer> intStack = new Stack<>();
intStack.push(5);
Integer element = intStack.peek();
assertEquals(Integer.valueOf(5), element);
assertEquals(1, intStack.search(5));
assertEquals(1, intStack.size());
}
@Test
public void whenElementIsOnStack_thenSearchReturnsItsDistanceFromTheTop() {
Stack<Integer> intStack = new Stack<>();
intStack.push(5);
intStack.push(8);
assertEquals(2, 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 whenRemoveElementIsInvoked_thenElementIsRemoved() {
Stack<Integer> intStack = new Stack<>();
intStack.push(5);
intStack.push(5);
intStack.removeElement(5);
assertEquals(1, intStack.size());
}
@Test
public void whenRemoveElementAtIsInvoked_thenElementIsRemoved() {
Stack<Integer> intStack = new Stack<>();
intStack.push(5);
intStack.push(7);
intStack.removeElementAt(1);
assertEquals(-1, intStack.search(7));
}
@Test
public void 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());
assertEquals(1, intStack.search(500));
}
@Test
public void 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));
}
@Test
public void whenStackIsFiltered_allElementsNotSatisfyingFilterConditionAreDiscarded() {
Stack<Integer> intStack = new Stack<>();
List<Integer> inputIntList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9, 10);
intStack.addAll(inputIntList);
List<Integer> filtered = intStack
.stream()
.filter(element -> element <= 3)
.collect(Collectors.toList());
assertEquals(3, filtered.size());
}
}

View File

@@ -1,44 +0,0 @@
package com.baeldung.timer;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
class DatabaseMigrationTaskUnitTest {
@Test
void givenDatabaseMigrationTask_whenTimerScheduledForNowPlusTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception {
List<String> oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill");
List<String> newDatabase = new ArrayList<>();
LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2);
Date twoSecondsLaterAsDate = Date.from(twoSecondsLater.atZone(ZoneId.systemDefault()).toInstant());
new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), twoSecondsLaterAsDate);
while (LocalDateTime.now().isBefore(twoSecondsLater)) {
assertThat(newDatabase).isEmpty();
Thread.sleep(500);
}
assertThat(newDatabase).containsExactlyElementsOf(oldDatabase);
}
@Test
void givenDatabaseMigrationTask_whenTimerScheduledInTwoSeconds_thenDataMigratedAfterTwoSeconds() throws Exception {
List<String> oldDatabase = Arrays.asList("Harrison Ford", "Carrie Fisher", "Mark Hamill");
List<String> newDatabase = new ArrayList<>();
new Timer().schedule(new DatabaseMigrationTask(oldDatabase, newDatabase), 2000);
LocalDateTime twoSecondsLater = LocalDateTime.now().plusSeconds(2);
while (LocalDateTime.now().isBefore(twoSecondsLater)) {
assertThat(newDatabase).isEmpty();
Thread.sleep(500);
}
assertThat(newDatabase).containsExactlyElementsOf(oldDatabase);
}
}

View File

@@ -1,139 +0,0 @@
package com.baeldung.timer;
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();
}
}

View File

@@ -1,33 +0,0 @@
package com.baeldung.timer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.Timer;
class NewsletterTaskUnitTest {
private final Timer timer = new Timer();
@AfterEach
void afterEach() {
timer.cancel();
}
@Test
void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception {
timer.schedule(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
}
@Test
void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception {
timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000);
for (int i = 0; i < 3; i++) {
Thread.sleep(1000);
}
}
}