JAVA-1522 Split core-java-modules/core-java module
This commit is contained in:
@@ -1,44 +1,6 @@
|
||||
## Core Java Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [Guide to the Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
|
||||
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
|
||||
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
- [Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
- [Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
|
||||
- [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields)
|
||||
- [Using Curl in Java](https://www.baeldung.com/java-curl)
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
|
||||
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
|
||||
|
||||
#New module structure
|
||||
###########################
|
||||
|
||||
#Leave in core-java:
|
||||
[Getting Started with Java Properties](http://www.baeldung.com/java-properties)
|
||||
[Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
[Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
@@ -49,47 +11,3 @@
|
||||
[What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
[A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
[Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
|
||||
|
||||
#Move to language interop (Done)
|
||||
[Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
|
||||
#Move to new new package: core-java-console (Done)
|
||||
[Read and Write User Input in Java](http://www.baeldung.com/java-console-input-output)
|
||||
[Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf)
|
||||
[ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
|
||||
|
||||
#Move to core-java-string-operations-2
|
||||
[Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
|
||||
[Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii) #remove additional readme file
|
||||
|
||||
#Move to core-javadatetime-operations-2
|
||||
[Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
|
||||
#Move to core-java-time-measurements
|
||||
[Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||
|
||||
#Move to core-java-reflection
|
||||
[How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
|
||||
#Move to core-java-streams
|
||||
[How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
|
||||
#Move to core-java-jvm
|
||||
[How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
|
||||
|
||||
#Move to data-structures module
|
||||
[Graphs in Java](https://www.baeldung.com/java-graphs)
|
||||
|
||||
#Move to core-java-collections-3
|
||||
[Quick Guide to the Java Stack](https://www.baeldung.com/java-stack)
|
||||
|
||||
#These are already in another module
|
||||
[Using Curl in Java](https://www.baeldung.com/java-curl) #Core Java Networking (Part 2)
|
||||
[Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) # Core Java Sun
|
||||
[Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler) #Core Java Exceptions
|
||||
[Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) #Core Java Exceptions
|
||||
[How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) #Core Java Exceptions
|
||||
[JVM Log Forging](http://www.baeldung.com/jvm-log-forging) #Core Java JVM
|
||||
[Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) #Core Java Networking (Part 2)
|
||||
[Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) #Core Java Exceptions
|
||||
[Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) #Core Java Reflection
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.baeldung.encoding;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
|
||||
public class CharacterEncodingExamples {
|
||||
|
||||
static String readFile(String filePath, String encoding) throws IOException {
|
||||
File file = new File(filePath);
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
|
||||
int data;
|
||||
while ((data = isr.read()) != -1) {
|
||||
buffer.append((char) data);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
static String convertToBinary(String input, String encoding) throws UnsupportedEncodingException {
|
||||
byte[] bytes = input.getBytes(encoding);
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
for (int b : bytes) {
|
||||
buffer.append(Integer.toBinaryString((b + 256) % 256));
|
||||
buffer.append(" ");
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
static String decodeText(String input, Charset charset, CodingErrorAction codingErrorAction) throws IOException {
|
||||
CharsetDecoder charsetDecoder = charset.newDecoder();
|
||||
charsetDecoder.onMalformedInput(codingErrorAction);
|
||||
return new BufferedReader(
|
||||
new InputStreamReader(
|
||||
new ByteArrayInputStream(input.getBytes()), charsetDecoder)).readLine();
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Graph {
|
||||
private Map<Vertex, List<Vertex>> adjVertices;
|
||||
|
||||
Graph() {
|
||||
this.adjVertices = new HashMap<Vertex, List<Vertex>>();
|
||||
}
|
||||
|
||||
void addVertex(String label) {
|
||||
adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
|
||||
}
|
||||
|
||||
void removeVertex(String label) {
|
||||
Vertex v = new Vertex(label);
|
||||
adjVertices.values().stream().forEach(e -> e.remove(v));
|
||||
adjVertices.remove(new Vertex(label));
|
||||
}
|
||||
|
||||
void addEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
adjVertices.get(v1).add(v2);
|
||||
adjVertices.get(v2).add(v1);
|
||||
}
|
||||
|
||||
void removeEdge(String label1, String label2) {
|
||||
Vertex v1 = new Vertex(label1);
|
||||
Vertex v2 = new Vertex(label2);
|
||||
List<Vertex> eV1 = adjVertices.get(v1);
|
||||
List<Vertex> eV2 = adjVertices.get(v2);
|
||||
if (eV1 != null)
|
||||
eV1.remove(v2);
|
||||
if (eV2 != null)
|
||||
eV2.remove(v1);
|
||||
}
|
||||
|
||||
List<Vertex> getAdjVertices(String label) {
|
||||
return adjVertices.get(new Vertex(label));
|
||||
}
|
||||
|
||||
String printGraph() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for(Vertex v : adjVertices.keySet()) {
|
||||
sb.append(v);
|
||||
sb.append(adjVertices.get(v));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
class Vertex {
|
||||
String label;
|
||||
Vertex(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + getOuterType().hashCode();
|
||||
result = prime * result + ((label == null) ? 0 : label.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Vertex other = (Vertex) obj;
|
||||
if (!getOuterType().equals(other.getOuterType()))
|
||||
return false;
|
||||
if (label == null) {
|
||||
if (other.label != null)
|
||||
return false;
|
||||
} else if (!label.equals(other.label))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return label;
|
||||
}
|
||||
|
||||
|
||||
private Graph getOuterType() {
|
||||
return Graph.this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.graph;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
import java.util.Stack;
|
||||
|
||||
import com.baeldung.graph.Graph.Vertex;
|
||||
|
||||
public class GraphTraversal {
|
||||
static Set<String> depthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Stack<String> stack = new Stack<String>();
|
||||
stack.push(root);
|
||||
while (!stack.isEmpty()) {
|
||||
String vertex = stack.pop();
|
||||
if (!visited.contains(vertex)) {
|
||||
visited.add(vertex);
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
stack.push(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
static Set<String> breadthFirstTraversal(Graph graph, String root) {
|
||||
Set<String> visited = new LinkedHashSet<String>();
|
||||
Queue<String> queue = new LinkedList<String>();
|
||||
queue.add(root);
|
||||
visited.add(root);
|
||||
while (!queue.isEmpty()) {
|
||||
String vertex = queue.poll();
|
||||
for (Vertex v : graph.getAdjVertices(vertex)) {
|
||||
if (!visited.contains(v.label)) {
|
||||
visited.add(v.label);
|
||||
queue.add(v.label);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.objectsize;
|
||||
|
||||
import java.lang.instrument.Instrumentation;
|
||||
|
||||
public class InstrumentationAgent {
|
||||
private static volatile Instrumentation globalInstrumentation;
|
||||
|
||||
public static void premain(final String agentArgs, final Instrumentation inst) {
|
||||
globalInstrumentation = inst;
|
||||
}
|
||||
|
||||
public static long getObjectSize(final Object object) {
|
||||
if (globalInstrumentation == null) {
|
||||
throw new IllegalStateException("Agent not initialized.");
|
||||
}
|
||||
return globalInstrumentation.getObjectSize(object);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.objectsize;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class InstrumentationExample {
|
||||
|
||||
public static void printObjectSize(Object object) {
|
||||
System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes");
|
||||
}
|
||||
|
||||
public static void main(String[] arguments) {
|
||||
String emptyString = "";
|
||||
String string = "Estimating Object Size Using Instrumentation";
|
||||
String[] stringArray = { emptyString, string, "com.baeldung" };
|
||||
String[] anotherStringArray = new String[100];
|
||||
List<String> stringList = new ArrayList<>();
|
||||
StringBuilder stringBuilder = new StringBuilder(100);
|
||||
int maxIntPrimitive = Integer.MAX_VALUE;
|
||||
int minIntPrimitive = Integer.MIN_VALUE;
|
||||
Integer maxInteger = Integer.MAX_VALUE;
|
||||
Integer minInteger = Integer.MIN_VALUE;
|
||||
long zeroLong = 0L;
|
||||
double zeroDouble = 0.0;
|
||||
boolean falseBoolean = false;
|
||||
Object object = new Object();
|
||||
|
||||
class EmptyClass {
|
||||
}
|
||||
EmptyClass emptyClass = new EmptyClass();
|
||||
|
||||
class StringClass {
|
||||
public String s;
|
||||
}
|
||||
StringClass stringClass = new StringClass();
|
||||
|
||||
printObjectSize(emptyString);
|
||||
printObjectSize(string);
|
||||
printObjectSize(stringArray);
|
||||
printObjectSize(anotherStringArray);
|
||||
printObjectSize(stringList);
|
||||
printObjectSize(stringBuilder);
|
||||
printObjectSize(maxIntPrimitive);
|
||||
printObjectSize(minIntPrimitive);
|
||||
printObjectSize(maxInteger);
|
||||
printObjectSize(minInteger);
|
||||
printObjectSize(zeroLong);
|
||||
printObjectSize(zeroDouble);
|
||||
printObjectSize(falseBoolean);
|
||||
printObjectSize(Day.TUESDAY);
|
||||
printObjectSize(object);
|
||||
printObjectSize(emptyClass);
|
||||
printObjectSize(stringClass);
|
||||
}
|
||||
|
||||
public enum Day {
|
||||
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
Premain-class: com.baeldung.objectsize.InstrumentationAgent
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class DatabaseMigrationTask extends TimerTask {
|
||||
private List<String> oldDatabase;
|
||||
private List<String> newDatabase;
|
||||
|
||||
public DatabaseMigrationTask(List<String> oldDatabase, List<String> newDatabase) {
|
||||
this.oldDatabase = oldDatabase;
|
||||
this.newDatabase = newDatabase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
newDatabase.addAll(oldDatabase);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.baeldung.timer;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class NewsletterTask extends TimerTask {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Email sent at: "
|
||||
+ LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault()));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii)
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user