diff --git a/.gitignore b/.gitignore
index 784627b616..f3fa30f3e3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+*/bin/*
+
*.class
# Package Files #
diff --git a/.travis.yml b/.travis.yml
index c2a369a1b3..bcff16f5f1 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,11 +1,13 @@
language: java
-install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
+install: travis_wait 60 mvn -q test
+
+before_script:
+ - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
jdk:
- oraclejdk8
-sudo: false
addons:
apt:
packages:
@@ -14,4 +16,6 @@ addons:
cache:
directories:
- .autoconf
- - $HOME/.m2
\ No newline at end of file
+ - $HOME/.m2
+
+
diff --git a/Twitter4J/README.md b/Twitter4J/README.md
new file mode 100644
index 0000000000..3057c1c4b2
--- /dev/null
+++ b/Twitter4J/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml
new file mode 100644
index 0000000000..7e41d8de76
--- /dev/null
+++ b/Twitter4J/pom.xml
@@ -0,0 +1,53 @@
+
+ 4.0.0
+ com.mabsisa
+ Twitter4J
+ jar
+ 1.0-SNAPSHOT
+ Twitter4J
+ http://maven.apache.org
+
+
+ UTF-8
+ UTF-8
+ 1.8
+ 1.8
+ 1.8
+
+
+
+
+ org.twitter4j
+ twitter4j-stream
+ 4.0.6
+
+
+ junit
+ junit
+ 4.12
+
+
+
+
+ ${project.artifactId}
+
+
+ src/main/resources
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.19.1
+
+
+ **/ApplicationTest.java
+
+
+
+
+
+
+
diff --git a/Twitter4J/src/main/java/com/baeldung/Application.java b/Twitter4J/src/main/java/com/baeldung/Application.java
new file mode 100644
index 0000000000..3f961ccb4f
--- /dev/null
+++ b/Twitter4J/src/main/java/com/baeldung/Application.java
@@ -0,0 +1,116 @@
+/**
+ *
+ */
+package com.baeldung;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import twitter4j.DirectMessage;
+import twitter4j.Query;
+import twitter4j.QueryResult;
+import twitter4j.StallWarning;
+import twitter4j.Status;
+import twitter4j.StatusDeletionNotice;
+import twitter4j.StatusListener;
+import twitter4j.Twitter;
+import twitter4j.TwitterException;
+import twitter4j.TwitterFactory;
+import twitter4j.TwitterStream;
+import twitter4j.TwitterStreamFactory;
+import twitter4j.conf.ConfigurationBuilder;
+
+public class Application {
+
+ public static Twitter getTwitterinstance() {
+ /**
+ * if not using properties file, we can set access token by following way
+ */
+// ConfigurationBuilder cb = new ConfigurationBuilder();
+// cb.setDebugEnabled(true)
+// .setOAuthConsumerKey("//TODO")
+// .setOAuthConsumerSecret("//TODO")
+// .setOAuthAccessToken("//TODO")
+// .setOAuthAccessTokenSecret("//TODO");
+// TwitterFactory tf = new TwitterFactory(cb.build());
+// Twitter twitter = tf.getSingleton();
+
+ Twitter twitter = TwitterFactory.getSingleton();
+ return twitter;
+
+ }
+
+ public static String createTweet(String tweet) throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ Status status = twitter.updateStatus("creating baeldung API");
+ return status.getText();
+ }
+
+ public static List getTimeLine() throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ List statuses = twitter.getHomeTimeline();
+ return statuses.stream().map(
+ item -> item.getText()).collect(
+ Collectors.toList());
+ }
+
+ public static String sendDirectMessage(String recipientName, String msg) throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
+ return message.getText();
+ }
+
+ public static List searchtweets() throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ Query query = new Query("source:twitter4j baeldung");
+ QueryResult result = twitter.search(query);
+ List statuses = result.getTweets();
+ return statuses.stream().map(
+ item -> item.getText()).collect(
+ Collectors.toList());
+ }
+
+ public static void streamFeed() {
+
+ StatusListener listener = new StatusListener(){
+
+ @Override
+ public void onException(Exception e) {
+ e.printStackTrace();
+ }
+
+ @Override
+ public void onDeletionNotice(StatusDeletionNotice arg) {
+ System.out.println("Got a status deletion notice id:" + arg.getStatusId());
+ }
+
+ @Override
+ public void onScrubGeo(long userId, long upToStatusId) {
+ System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
+ }
+
+ @Override
+ public void onStallWarning(StallWarning warning) {
+ System.out.println("Got stall warning:" + warning);
+ }
+
+ @Override
+ public void onStatus(Status status) {
+ System.out.println(status.getUser().getName() + " : " + status.getText());
+ }
+
+ @Override
+ public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
+ System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
+ }
+ };
+
+ TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
+
+ twitterStream.addListener(listener);
+
+ twitterStream.sample();
+
+ }
+
+}
diff --git a/Twitter4J/src/main/resources/twitter4j.properties b/Twitter4J/src/main/resources/twitter4j.properties
new file mode 100644
index 0000000000..ee11dc62a1
--- /dev/null
+++ b/Twitter4J/src/main/resources/twitter4j.properties
@@ -0,0 +1,4 @@
+oauth.consumerKey=//TODO
+oauth.consumerSecret=//TODO
+oauth.accessToken=//TODO
+oauth.accessTokenSecret=//TODO
diff --git a/Twitter4J/src/test/java/com/baeldung/ApplicationTest.java b/Twitter4J/src/test/java/com/baeldung/ApplicationTest.java
new file mode 100644
index 0000000000..a1c778679c
--- /dev/null
+++ b/Twitter4J/src/test/java/com/baeldung/ApplicationTest.java
@@ -0,0 +1,40 @@
+package com.baeldung;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+import twitter4j.TwitterException;
+
+public class ApplicationTest {
+
+ /**
+ * In order run this jUnit test you need to configure your API details in the twitter4j.properties
+ */
+
+ String tweet = "baeldung is awsome";
+
+ @Test
+ public void givenText_updateStatus() throws TwitterException {
+ String text = Application.createTweet(tweet);
+ assertEquals(tweet, text);
+ }
+
+ @Test
+ public void givenCredential_fetchStatus() throws TwitterException {
+ List statuses = Application.getTimeLine();
+ List expectedStatuses = new ArrayList();
+ expectedStatuses.add(tweet);
+ assertEquals(expectedStatuses, statuses);
+ }
+
+ @Test
+ public void givenRecipientNameAndMessage_sendDirectMessage() throws TwitterException {
+ String msg = Application.sendDirectMessage("YOUR_RECCIPIENT_ID", tweet);
+ assertEquals(msg, tweet);
+ }
+
+}
diff --git a/algorithms/.gitignore b/algorithms/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/algorithms/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/algorithms/README.md b/algorithms/README.md
index 42f696d9be..00e0646f47 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -2,3 +2,6 @@
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
+- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
+- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
+- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
diff --git a/algorithms/pom.xml b/algorithms/pom.xml
index f72457650a..884c804d13 100644
--- a/algorithms/pom.xml
+++ b/algorithms/pom.xml
@@ -9,15 +9,33 @@
4.12
3.6.0
1.5.0
+ 1.16.12
+ 3.6.1
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
junit
junit
${junit.version}
test
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+ io.jenetics
+ jenetics
+ 3.7.0
+
diff --git a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
similarity index 84%
rename from core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
rename to algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
index 22c5776293..6ab7dbb4e5 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -9,13 +9,14 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
- public static void main(String[] args) {
+ public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One");
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
+ System.out.println("5 - Dijkstra");
int decision = in.nextInt();
switch (decision) {
case 1:
@@ -33,6 +34,9 @@ public class RunAlgorithm {
AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization();
break;
+ case 5:
+ System.out.println("Please run the DijkstraAlgorithmTest.");
+ break;
default:
System.out.println("Unknown option");
break;
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/annealing/City.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
new file mode 100644
index 0000000000..62e124d3f3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
@@ -0,0 +1,203 @@
+package com.baeldung.algorithms.ga.ant_colony;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.OptionalInt;
+import java.util.Random;
+import java.util.stream.IntStream;
+
+public class AntColonyOptimization {
+
+ private double c = 1.0;
+ private double alpha = 1;
+ private double beta = 5;
+ private double evaporation = 0.5;
+ private double Q = 500;
+ private double antFactor = 0.8;
+ private double randomFactor = 0.01;
+
+ private int maxIterations = 1000;
+
+ private int numberOfCities;
+ private int numberOfAnts;
+ private double graph[][];
+ private double trails[][];
+ private List ants = new ArrayList<>();
+ private Random random = new Random();
+ private double probabilities[];
+
+ private int currentIndex;
+
+ private int[] bestTourOrder;
+ private double bestTourLength;
+
+ public AntColonyOptimization(int noOfCities) {
+ graph = generateRandomMatrix(noOfCities);
+ numberOfCities = graph.length;
+ numberOfAnts = (int) (numberOfCities * antFactor);
+
+ trails = new double[numberOfCities][numberOfCities];
+ probabilities = new double[numberOfCities];
+ IntStream.range(0, numberOfAnts)
+ .forEach(i -> ants.add(new Ant(numberOfCities)));
+ }
+
+ /**
+ * Generate initial solution
+ */
+ public double[][] generateRandomMatrix(int n) {
+ double[][] randomMatrix = new double[n][n];
+ IntStream.range(0, n)
+ .forEach(i -> IntStream.range(0, n)
+ .forEach(j -> randomMatrix[i][j] = Math.abs(random.nextInt(100) + 1)));
+ return randomMatrix;
+ }
+
+ /**
+ * Perform ant optimization
+ */
+ public void startAntOptimization() {
+ IntStream.rangeClosed(1, 3)
+ .forEach(i -> {
+ System.out.println("Attempt #" + i);
+ solve();
+ });
+ }
+
+ /**
+ * Use this method to run the main logic
+ */
+ public int[] solve() {
+ setupAnts();
+ clearTrails();
+ IntStream.range(0, maxIterations)
+ .forEach(i -> {
+ moveAnts();
+ updateTrails();
+ updateBest();
+ });
+ System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
+ System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
+ return bestTourOrder.clone();
+ }
+
+ /**
+ * Prepare ants for the simulation
+ */
+ private void setupAnts() {
+ IntStream.range(0, numberOfAnts)
+ .forEach(i -> {
+ ants.forEach(ant -> {
+ ant.clear();
+ ant.visitCity(-1, random.nextInt(numberOfCities));
+ });
+ });
+ currentIndex = 0;
+ }
+
+ /**
+ * At each iteration, move ants
+ */
+ private void moveAnts() {
+ IntStream.range(currentIndex, numberOfCities - 1)
+ .forEach(i -> {
+ ants.forEach(ant -> ant.visitCity(currentIndex, selectNextCity(ant)));
+ currentIndex++;
+ });
+ }
+
+ /**
+ * Select next city for each ant
+ */
+ private int selectNextCity(Ant ant) {
+ int t = random.nextInt(numberOfCities - currentIndex);
+ if (random.nextDouble() < randomFactor) {
+ OptionalInt cityIndex = IntStream.range(0, numberOfCities)
+ .filter(i -> i == t && !ant.visited(i))
+ .findFirst();
+ if (cityIndex.isPresent()) {
+ return cityIndex.getAsInt();
+ }
+ }
+ calculateProbabilities(ant);
+ double r = random.nextDouble();
+ double total = 0;
+ for (int i = 0; i < numberOfCities; i++) {
+ total += probabilities[i];
+ if (total >= r) {
+ return i;
+ }
+ }
+
+ throw new RuntimeException("There are no other cities");
+ }
+
+ /**
+ * Calculate the next city picks probabilites
+ */
+ public void calculateProbabilities(Ant ant) {
+ int i = ant.trail[currentIndex];
+ double pheromone = 0.0;
+ for (int l = 0; l < numberOfCities; l++) {
+ if (!ant.visited(l)) {
+ pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
+ }
+ }
+ for (int j = 0; j < numberOfCities; j++) {
+ if (ant.visited(j)) {
+ probabilities[j] = 0.0;
+ } else {
+ double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
+ probabilities[j] = numerator / pheromone;
+ }
+ }
+ }
+
+ /**
+ * Update trails that ants used
+ */
+ private void updateTrails() {
+ for (int i = 0; i < numberOfCities; i++) {
+ for (int j = 0; j < numberOfCities; j++) {
+ trails[i][j] *= evaporation;
+ }
+ }
+ for (Ant a : ants) {
+ double contribution = Q / a.trailLength(graph);
+ for (int i = 0; i < numberOfCities - 1; i++) {
+ trails[a.trail[i]][a.trail[i + 1]] += contribution;
+ }
+ trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
+ }
+ }
+
+ /**
+ * Update the best solution
+ */
+ private void updateBest() {
+ if (bestTourOrder == null) {
+ bestTourOrder = ants.get(0).trail;
+ bestTourLength = ants.get(0)
+ .trailLength(graph);
+ }
+ for (Ant a : ants) {
+ if (a.trailLength(graph) < bestTourLength) {
+ bestTourLength = a.trailLength(graph);
+ bestTourOrder = a.trail.clone();
+ }
+ }
+ }
+
+ /**
+ * Clear trails after simulation
+ */
+ private void clearTrails() {
+ IntStream.range(0, numberOfCities)
+ .forEach(i -> {
+ IntStream.range(0, numberOfCities)
+ .forEach(j -> trails[i][j] = c);
+ });
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
similarity index 95%
rename from algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
index 1d41f46adb..0b01e9b48b 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
@@ -1,57 +1,57 @@
-package com.baeldung.algorithms.dijkstra;
-
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map.Entry;
-import java.util.Set;
-
-public class Dijkstra {
-
- public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
-
- source.setDistance(0);
-
- Set settledNodes = new HashSet<>();
- Set unsettledNodes = new HashSet<>();
- unsettledNodes.add(source);
-
- while (unsettledNodes.size() != 0) {
- Node currentNode = getLowestDistanceNode(unsettledNodes);
- unsettledNodes.remove(currentNode);
- for (Entry adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
- Node adjacentNode = adjacencyPair.getKey();
- Integer edgeWeigh = adjacencyPair.getValue();
-
- if (!settledNodes.contains(adjacentNode)) {
- CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
- unsettledNodes.add(adjacentNode);
- }
- }
- settledNodes.add(currentNode);
- }
- return graph;
- }
-
- private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
- Integer sourceDistance = sourceNode.getDistance();
- if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
- evaluationNode.setDistance(sourceDistance + edgeWeigh);
- LinkedList shortestPath = new LinkedList<>(sourceNode.getShortestPath());
- shortestPath.add(sourceNode);
- evaluationNode.setShortestPath(shortestPath);
- }
- }
-
- private static Node getLowestDistanceNode(Set unsettledNodes) {
- Node lowestDistanceNode = null;
- int lowestDistance = Integer.MAX_VALUE;
- for (Node node : unsettledNodes) {
- int nodeDistance = node.getDistance();
- if (nodeDistance < lowestDistance) {
- lowestDistance = nodeDistance;
- lowestDistanceNode = node;
- }
- }
- return lowestDistanceNode;
- }
-}
+package com.baeldung.algorithms.ga.dijkstra;
+
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Map.Entry;
+import java.util.Set;
+
+public class Dijkstra {
+
+ public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
+
+ source.setDistance(0);
+
+ Set settledNodes = new HashSet<>();
+ Set unsettledNodes = new HashSet<>();
+ unsettledNodes.add(source);
+
+ while (unsettledNodes.size() != 0) {
+ Node currentNode = getLowestDistanceNode(unsettledNodes);
+ unsettledNodes.remove(currentNode);
+ for (Entry adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
+ Node adjacentNode = adjacencyPair.getKey();
+ Integer edgeWeigh = adjacencyPair.getValue();
+
+ if (!settledNodes.contains(adjacentNode)) {
+ CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
+ unsettledNodes.add(adjacentNode);
+ }
+ }
+ settledNodes.add(currentNode);
+ }
+ return graph;
+ }
+
+ private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
+ Integer sourceDistance = sourceNode.getDistance();
+ if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
+ evaluationNode.setDistance(sourceDistance + edgeWeigh);
+ LinkedList shortestPath = new LinkedList<>(sourceNode.getShortestPath());
+ shortestPath.add(sourceNode);
+ evaluationNode.setShortestPath(shortestPath);
+ }
+ }
+
+ private static Node getLowestDistanceNode(Set unsettledNodes) {
+ Node lowestDistanceNode = null;
+ int lowestDistance = Integer.MAX_VALUE;
+ for (Node node : unsettledNodes) {
+ int nodeDistance = node.getDistance();
+ if (nodeDistance < lowestDistance) {
+ lowestDistance = nodeDistance;
+ lowestDistanceNode = node;
+ }
+ }
+ return lowestDistanceNode;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
similarity index 84%
rename from algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
index f24d6ae60e..76694ed76e 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
@@ -1,21 +1,21 @@
-package com.baeldung.algorithms.dijkstra;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class Graph {
-
- private Set nodes = new HashSet<>();
-
- public void addNode(Node nodeA) {
- nodes.add(nodeA);
- }
-
- public Set getNodes() {
- return nodes;
- }
-
- public void setNodes(Set nodes) {
- this.nodes = nodes;
- }
-}
+package com.baeldung.algorithms.ga.dijkstra;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class Graph {
+
+ private Set nodes = new HashSet<>();
+
+ public void addNode(Node nodeA) {
+ nodes.add(nodeA);
+ }
+
+ public Set getNodes() {
+ return nodes;
+ }
+
+ public void setNodes(Set nodes) {
+ this.nodes = nodes;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
similarity index 92%
rename from algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
index b00127a259..ac34bfadd1 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
@@ -1,58 +1,58 @@
-package com.baeldung.algorithms.dijkstra;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-public class Node {
-
- private String name;
-
- private LinkedList shortestPath = new LinkedList<>();
-
- private Integer distance = Integer.MAX_VALUE;
-
- private Map adjacentNodes = new HashMap<>();
-
- public Node(String name) {
- this.name = name;
- }
-
- public void addDestination(Node destination, int distance) {
- adjacentNodes.put(destination, distance);
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Map getAdjacentNodes() {
- return adjacentNodes;
- }
-
- public void setAdjacentNodes(Map adjacentNodes) {
- this.adjacentNodes = adjacentNodes;
- }
-
- public Integer getDistance() {
- return distance;
- }
-
- public void setDistance(Integer distance) {
- this.distance = distance;
- }
-
- public List getShortestPath() {
- return shortestPath;
- }
-
- public void setShortestPath(LinkedList shortestPath) {
- this.shortestPath = shortestPath;
- }
-
-}
+package com.baeldung.algorithms.ga.dijkstra;
+
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+public class Node {
+
+ private String name;
+
+ private LinkedList shortestPath = new LinkedList<>();
+
+ private Integer distance = Integer.MAX_VALUE;
+
+ private Map adjacentNodes = new HashMap<>();
+
+ public Node(String name) {
+ this.name = name;
+ }
+
+ public void addDestination(Node destination, int distance) {
+ adjacentNodes.put(destination, distance);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Map getAdjacentNodes() {
+ return adjacentNodes;
+ }
+
+ public void setAdjacentNodes(Map adjacentNodes) {
+ this.adjacentNodes = adjacentNodes;
+ }
+
+ public Integer getDistance() {
+ return distance;
+ }
+
+ public void setDistance(Integer distance) {
+ this.distance = distance;
+ }
+
+ public List getShortestPath() {
+ return shortestPath;
+ }
+
+ public void setShortestPath(LinkedList shortestPath) {
+ this.shortestPath = shortestPath;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
new file mode 100644
index 0000000000..cc99ccf204
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
@@ -0,0 +1,47 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
+import static org.jenetics.engine.limit.bySteadyFitness;
+
+import java.util.stream.Stream;
+
+import org.jenetics.BitChromosome;
+import org.jenetics.BitGene;
+import org.jenetics.Mutator;
+import org.jenetics.Phenotype;
+import org.jenetics.RouletteWheelSelector;
+import org.jenetics.SinglePointCrossover;
+import org.jenetics.TournamentSelector;
+import org.jenetics.engine.Engine;
+import org.jenetics.engine.EvolutionStatistics;
+
+//The main class.
+public class Knapsack {
+
+ public static void main(String[] args) {
+ int nItems = 15;
+ double ksSize = nItems * 100.0 / 3.0;
+
+ KnapsackFF ff = new KnapsackFF(Stream.generate(KnapsackItem::random)
+ .limit(nItems)
+ .toArray(KnapsackItem[]::new), ksSize);
+
+ Engine engine = Engine.builder(ff, BitChromosome.of(nItems, 0.5))
+ .populationSize(500)
+ .survivorsSelector(new TournamentSelector<>(5))
+ .offspringSelector(new RouletteWheelSelector<>())
+ .alterers(new Mutator<>(0.115), new SinglePointCrossover<>(0.16))
+ .build();
+
+ EvolutionStatistics statistics = EvolutionStatistics.ofNumber();
+
+ Phenotype best = engine.stream()
+ .limit(bySteadyFitness(7))
+ .limit(100)
+ .peek(statistics)
+ .collect(toBestPhenotype());
+
+ System.out.println(statistics);
+ System.out.println(best);
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
new file mode 100644
index 0000000000..e3e06d301a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
@@ -0,0 +1,25 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import java.util.function.Function;
+
+import org.jenetics.BitChromosome;
+import org.jenetics.BitGene;
+import org.jenetics.Genotype;
+
+public class KnapsackFF implements Function, Double> {
+ private KnapsackItem[] items;
+ private double size;
+
+ public KnapsackFF(KnapsackItem[] items, double size) {
+ this.items = items;
+ this.size = size;
+ }
+
+ @Override
+ public Double apply(Genotype gt) {
+ KnapsackItem sum = ((BitChromosome) gt.getChromosome()).ones()
+ .mapToObj(i -> items[i])
+ .collect(KnapsackItem.toSum());
+ return sum.size <= this.size ? sum.value : 0;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
new file mode 100644
index 0000000000..876df0ba25
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
@@ -0,0 +1,34 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import java.util.Random;
+import java.util.stream.Collector;
+
+import org.jenetics.util.RandomRegistry;
+
+public class KnapsackItem {
+
+ public double size;
+ public double value;
+
+ public KnapsackItem(double size, double value) {
+ this.size = size;
+ this.value = value;
+ }
+
+ protected static KnapsackItem random() {
+ Random r = RandomRegistry.getRandom();
+ return new KnapsackItem(r.nextDouble() * 100, r.nextDouble() * 100);
+ }
+
+ protected static Collector toSum() {
+ return Collector.of(() -> new double[2], (a, b) -> {
+ a[0] += b.size;
+ a[1] += b.value;
+ } , (a, b) -> {
+ a[0] += b[0];
+ a[1] += b[1];
+ return a;
+ } , r -> new KnapsackItem(r[0], r[1]));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
new file mode 100644
index 0000000000..845e11b349
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
@@ -0,0 +1,33 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import org.jenetics.BitChromosome;
+import org.jenetics.BitGene;
+import org.jenetics.Genotype;
+import org.jenetics.engine.Engine;
+import org.jenetics.engine.EvolutionResult;
+import org.jenetics.util.Factory;
+
+public class SimpleGeneticAlgorithm {
+
+ private static Integer eval(Genotype gt) {
+ return gt.getChromosome()
+ .as(BitChromosome.class)
+ .bitCount();
+ }
+
+ public static void main(String[] args) {
+ Factory> gtf = Genotype.of(BitChromosome.of(10, 0.5));
+ System.out.println("Before the evolution:\n" + gtf);
+
+ Engine engine = Engine.builder(SimpleGeneticAlgorithm::eval, gtf)
+ .build();
+
+ Genotype result = engine.stream()
+ .limit(500)
+ .collect(EvolutionResult.toBestGenotype());
+
+ System.out.println("After the evolution:\n" + result);
+
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
new file mode 100644
index 0000000000..55f2f7af0a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
@@ -0,0 +1,86 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.jenetics.BitGene;
+import org.jenetics.engine.Codec;
+import org.jenetics.engine.Engine;
+import org.jenetics.engine.EvolutionResult;
+import org.jenetics.engine.Problem;
+import org.jenetics.engine.codecs;
+import org.jenetics.util.ISeq;
+
+public class SpringsteenProblem implements Problem, BitGene, Double> {
+
+ private ISeq records;
+ private double maxPricePerUniqueSong;
+
+ public SpringsteenProblem(ISeq records, double maxPricePerUniqueSong) {
+ this.records = requireNonNull(records);
+ this.maxPricePerUniqueSong = maxPricePerUniqueSong;
+ }
+
+ @Override
+ public Function, Double> fitness() {
+ return SpringsteenRecords -> {
+ double cost = SpringsteenRecords.stream()
+ .mapToDouble(r -> r.price)
+ .sum();
+
+ int uniqueSongCount = SpringsteenRecords.stream()
+ .flatMap(r -> r.songs.stream())
+ .collect(Collectors.toSet())
+ .size();
+
+ double pricePerUniqueSong = cost / uniqueSongCount;
+
+ return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0;
+ };
+ }
+
+ @Override
+ public Codec, BitGene> codec() {
+ return codecs.ofSubSet(records);
+ }
+
+ public static void main(String[] args) {
+ double maxPricePerUniqueSong = 2.5;
+
+ SpringsteenProblem springsteen = new SpringsteenProblem(
+ ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")),
+ new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")),
+ new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))),
+ maxPricePerUniqueSong);
+
+ Engine engine = Engine.builder(springsteen)
+ .build();
+
+ ISeq result = springsteen.codec()
+ .decoder()
+ .apply(engine.stream()
+ .limit(10)
+ .collect(EvolutionResult.toBestGenotype()));
+
+ double cost = result.stream()
+ .mapToDouble(r -> r.price)
+ .sum();
+
+ int uniqueSongCount = result.stream()
+ .flatMap(r -> r.songs.stream())
+ .collect(Collectors.toSet())
+ .size();
+
+ double pricePerUniqueSong = cost / uniqueSongCount;
+
+ System.out.println("Overall cost: " + cost);
+ System.out.println("Unique songs: " + uniqueSongCount);
+ System.out.println("Cost per song: " + pricePerUniqueSong);
+ System.out.println("Records: " + result.map(r -> r.name)
+ .toString(", "));
+
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
new file mode 100644
index 0000000000..b49709e7f5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
@@ -0,0 +1,24 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import static java.util.Objects.requireNonNull;
+
+import org.jenetics.util.ISeq;
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Data
+@NoArgsConstructor
+public class SpringsteenRecord {
+
+ String name;
+ double price;
+ ISeq songs;
+
+ public SpringsteenRecord(String name, double price, ISeq songs) {
+ this.name = requireNonNull(name);
+ this.price = price;
+ this.songs = requireNonNull(songs);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
new file mode 100644
index 0000000000..db1e11239f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
@@ -0,0 +1,66 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import static java.util.Objects.requireNonNull;
+
+import java.util.Random;
+import java.util.function.Function;
+
+import org.jenetics.EnumGene;
+import org.jenetics.Mutator;
+import org.jenetics.PartiallyMatchedCrossover;
+import org.jenetics.Phenotype;
+import org.jenetics.engine.Codec;
+import org.jenetics.engine.Engine;
+import org.jenetics.engine.EvolutionResult;
+import org.jenetics.engine.Problem;
+import org.jenetics.engine.codecs;
+import org.jenetics.engine.limit;
+import org.jenetics.util.ISeq;
+import org.jenetics.util.LCG64ShiftRandom;
+
+public class SubsetSum implements Problem, EnumGene, Integer> {
+
+ private ISeq basicSet;
+ private int size;
+
+ public SubsetSum(ISeq basicSet, int size) {
+ this.basicSet = requireNonNull(basicSet);
+ this.size = size;
+ }
+
+ @Override
+ public Function, Integer> fitness() {
+ return subset -> Math.abs(subset.stream()
+ .mapToInt(Integer::intValue)
+ .sum());
+ }
+
+ @Override
+ public Codec, EnumGene> codec() {
+ return codecs.ofSubSet(basicSet, size);
+ }
+
+ public static SubsetSum of(int n, int k, Random random) {
+ return new SubsetSum(random.doubles()
+ .limit(n)
+ .mapToObj(d -> (int) ((d - 0.5) * n))
+ .collect(ISeq.toISeq()), k);
+ }
+
+ public static void main(String[] args) {
+ SubsetSum problem = of(500, 15, new LCG64ShiftRandom(101010));
+
+ Engine, Integer> engine = Engine.builder(problem)
+ .minimizing()
+ .maximalPhenotypeAge(5)
+ .alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3))
+ .build();
+
+ Phenotype, Integer> result = engine.stream()
+ .limit(limit.bySteadyFitness(55))
+ .collect(EvolutionResult.toBestPhenotype());
+
+ System.out.print(result);
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
new file mode 100644
index 0000000000..80ede0f8c5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
@@ -0,0 +1,67 @@
+package com.baeldung.algorithms.ga.jenetics;
+
+import static java.lang.Math.PI;
+import static java.lang.Math.abs;
+import static java.lang.Math.sin;
+import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
+import static org.jenetics.engine.limit.bySteadyFitness;
+
+import java.util.stream.IntStream;
+
+import org.jenetics.EnumGene;
+import org.jenetics.Optimize;
+import org.jenetics.PartiallyMatchedCrossover;
+import org.jenetics.Phenotype;
+import org.jenetics.SwapMutator;
+import org.jenetics.engine.Engine;
+import org.jenetics.engine.EvolutionStatistics;
+import org.jenetics.engine.codecs;
+
+public class TravelingSalesman {
+
+ private static final int STOPS = 50;
+ private static final double[][] ADJACENCE = matrix(STOPS);
+
+ private static double[][] matrix(int stops) {
+ final double radius = 100.0;
+ double[][] matrix = new double[stops][stops];
+
+ for (int i = 0; i < stops; ++i) {
+ for (int j = 0; j < stops; ++j) {
+ matrix[i][j] = chord(stops, abs(i - j), radius);
+ }
+ }
+ return matrix;
+ }
+
+ private static double chord(int stops, int i, double r) {
+ return 2.0 * r * abs(sin(PI * i / stops));
+ }
+
+ private static double dist(final int[] path) {
+ return IntStream.range(0, STOPS)
+ .mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]])
+ .sum();
+ }
+
+ public static void main(String[] args) {
+ final Engine, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS))
+ .optimize(Optimize.MINIMUM)
+ .maximalPhenotypeAge(11)
+ .populationSize(500)
+ .alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35))
+ .build();
+
+ final EvolutionStatistics statistics = EvolutionStatistics.ofNumber();
+
+ final Phenotype, Double> best = engine.stream()
+ .limit(bySteadyFitness(15))
+ .limit(250)
+ .peek(statistics)
+ .collect(toBestPhenotype());
+
+ System.out.println(statistics);
+ System.out.println(best);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java
new file mode 100644
index 0000000000..752e659fa3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java
@@ -0,0 +1,13 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.math.BigInteger;
+
+public class BigIntegerPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Long number) {
+ BigInteger bigInt = BigInteger.valueOf(number);
+ return bigInt.isProbablePrime(100);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java
new file mode 100644
index 0000000000..47ffb3e224
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java
@@ -0,0 +1,16 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+public class BruteForcePrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+
+ return number > 2 ? IntStream.range(2, number)
+ .noneMatch(n -> (number % n == 0)) : false;
+ }
+
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java
new file mode 100644
index 0000000000..06ae4acc7f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java
@@ -0,0 +1,15 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+public class OptimisedPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+ return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number))
+ .noneMatch(n -> (number % n == 0)) : false;
+ }
+
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java
new file mode 100644
index 0000000000..5f7a15a939
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java
@@ -0,0 +1,6 @@
+package com.baeldung.algorithms.primechecker;
+
+public interface PrimeChecker {
+
+ public boolean isPrime( T number );
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java
new file mode 100644
index 0000000000..08b095cb79
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java
@@ -0,0 +1,12 @@
+package com.baeldung.algorithms.primechecker;
+
+import org.apache.commons.math3.primes.Primes;
+
+public class PrimesPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+ return Primes.isPrime(number);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java
diff --git a/algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java
new file mode 100644
index 0000000000..943b44fe05
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/FiniteStateMachine.java
@@ -0,0 +1,20 @@
+package com.baeldung.automata;
+
+/**
+ * Finite state machine.
+ */
+public interface FiniteStateMachine {
+
+ /**
+ * Follow a transition, switch the state of the machine.
+ * @param c Char.
+ * @return A new finite state machine with the new state.
+ */
+ FiniteStateMachine switchState(final CharSequence c);
+
+ /**
+ * Is the current state a final one?
+ * @return true or false.
+ */
+ boolean canStop();
+}
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java
new file mode 100644
index 0000000000..090e00c73c
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/RtFiniteStateMachine.java
@@ -0,0 +1,30 @@
+package com.baeldung.automata;
+
+/**
+ * Default implementation of a finite state machine.
+ * This class is immutable and thread-safe.
+ */
+public final class RtFiniteStateMachine implements FiniteStateMachine {
+
+ /**
+ * Current state.
+ */
+ private State current;
+
+ /**
+ * Ctor.
+ * @param initial Initial state of this machine.
+ */
+ public RtFiniteStateMachine(final State initial) {
+ this.current = initial;
+ }
+
+ public FiniteStateMachine switchState(final CharSequence c) {
+ return new RtFiniteStateMachine(this.current.transit(c));
+ }
+
+ public boolean canStop() {
+ return this.current.isFinal();
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtState.java b/algorithms/src/main/java/com/baeldung/automata/RtState.java
new file mode 100644
index 0000000000..b4a5df7961
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/RtState.java
@@ -0,0 +1,42 @@
+package com.baeldung.automata;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * State in a finite state machine.
+ */
+public final class RtState implements State {
+
+ private List transitions;
+ private boolean isFinal;
+
+ public RtState() {
+ this(false);
+ }
+
+ public RtState(final boolean isFinal) {
+ this.transitions = new ArrayList<>();
+ this.isFinal = isFinal;
+ }
+
+ public State transit(final CharSequence c) {
+ return transitions
+ .stream()
+ .filter(t -> t.isPossible(c))
+ .map(Transition::state)
+ .findAny()
+ .orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
+ }
+
+ public boolean isFinal() {
+ return this.isFinal;
+ }
+
+ @Override
+ public State with(Transition tr) {
+ this.transitions.add(tr);
+ return this;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/automata/RtTransition.java b/algorithms/src/main/java/com/baeldung/automata/RtTransition.java
new file mode 100644
index 0000000000..560011e42a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/RtTransition.java
@@ -0,0 +1,31 @@
+package com.baeldung.automata;
+
+
+/**
+ * Transition in finite state machine.
+ */
+public final class RtTransition implements Transition {
+
+ private String rule;
+ private State next;
+
+ /**
+ * Ctor.
+ * @param rule Rule that a character has to meet
+ * in order to get to the next state.
+ * @param next Next state.
+ */
+ public RtTransition (String rule, State next) {
+ this.rule = rule;
+ this.next = next;
+ }
+
+ public State state() {
+ return this.next;
+ }
+
+ public boolean isPossible(CharSequence c) {
+ return this.rule.equalsIgnoreCase(String.valueOf(c));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/automata/State.java b/algorithms/src/main/java/com/baeldung/automata/State.java
new file mode 100644
index 0000000000..a25af9d03a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/State.java
@@ -0,0 +1,29 @@
+package com.baeldung.automata;
+
+/**
+ * State. Part of a finite state machine.
+ */
+public interface State {
+
+ /**
+ * Add a Transition to this state.
+ * @param tr Given transition.
+ * @return Modified State.
+ */
+ State with(final Transition tr);
+
+ /**
+ * Follow one of the transitions, to get
+ * to the next state.
+ * @param c Character.
+ * @return State.
+ * @throws IllegalStateException if the char is not accepted.
+ */
+ State transit(final CharSequence c);
+
+ /**
+ * Can the automaton stop on this state?
+ * @return true or false
+ */
+ boolean isFinal();
+}
diff --git a/algorithms/src/main/java/com/baeldung/automata/Transition.java b/algorithms/src/main/java/com/baeldung/automata/Transition.java
new file mode 100644
index 0000000000..d57620f911
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/automata/Transition.java
@@ -0,0 +1,20 @@
+package com.baeldung.automata;
+
+/**
+ * Transition in a finite State machine.
+ */
+public interface Transition {
+
+ /**
+ * Is the transition possible with the given character?
+ * @param c char.
+ * @return true or false.
+ */
+ boolean isPossible(final CharSequence c);
+
+ /**
+ * The state to which this transition leads.
+ * @return State.
+ */
+ State state();
+}
diff --git a/core-java/src/test/java/com/baeldung/algorithms/AntColonyOptimizationTest.java b/algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java
similarity index 83%
rename from core-java/src/test/java/com/baeldung/algorithms/AntColonyOptimizationTest.java
rename to algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java
index cd8efaa106..a11f5db698 100644
--- a/core-java/src/test/java/com/baeldung/algorithms/AntColonyOptimizationTest.java
+++ b/algorithms/src/test/java/algorithms/AntColonyOptimizationTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms;
+package algorithms;
import org.junit.Assert;
import org.junit.Test;
@@ -16,7 +16,7 @@ public class AntColonyOptimizationTest {
@Test
public void testStartAntOptimization() {
AntColonyOptimization antTSP = new AntColonyOptimization(5);
- Assert.assertNotNull(antTSP.startAntOptimization());
+ Assert.assertNotNull(antTSP.solve());
}
}
diff --git a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java
similarity index 91%
rename from core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java
rename to algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java
index 2e92177c8c..2ba516d310 100644
--- a/core-java/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmUnitTest.java
+++ b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms;
+package algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
index 07606bde4b..4d8cebed25 100644
--- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
+++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
@@ -1,10 +1,11 @@
package algorithms;
-import com.baeldung.algorithms.dijkstra.Dijkstra;
-import com.baeldung.algorithms.dijkstra.Graph;
-import com.baeldung.algorithms.dijkstra.Node;
import org.junit.Test;
+import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
+import com.baeldung.algorithms.ga.dijkstra.Graph;
+import com.baeldung.algorithms.ga.dijkstra.Node;
+
import java.util.Arrays;
import java.util.List;
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java b/algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java
new file mode 100644
index 0000000000..089b38ec3f
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/RtFiniteStateMachineTest.java
@@ -0,0 +1,82 @@
+package algorithms;
+
+import static org.junit.Assert.*;
+import org.junit.Test;
+import com.baeldung.automata.*;
+
+/**
+ * Tests for {@link RtFiniteStateMachine}
+ */
+public final class RtFiniteStateMachineTest {
+
+ @Test
+ public void acceptsSimplePair() {
+ String json = "{\"key\":\"value\"}";
+ FiniteStateMachine machine = this.buildJsonStateMachine();
+ for (int i=0;i
org.dbdoclet
herold
- 6.1.0
- system
- ${basedir}/src/test/resources/jars/herold.jar
+ 8.0.4
@@ -140,6 +138,8 @@
maven-surefire-plugin
${maven-surefire-plugin.version}
+ 3
+ true
**/*IntegrationTest.java
**/*LiveTest.java
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
index 99487c8fdf..5e2da6fd1e 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
@@ -19,21 +19,21 @@ import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;
-import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
+import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
import org.dbdoclet.trafo.script.Script;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
public class ApacheFOPConvertHTMLIntegrationTest {
- private String inputFile = "src/test/resources/input.html";
- private String style = "src/test/resources/xhtml2fo.xsl";
- private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
- private String output_jtidy = "src/test/resources/output_jtidy.pdf";
- private String output_html2fo = "src/test/resources/output_html2fo.pdf";
- private String output_herold = "src/test/resources/output_herold.pdf";
- private String foFile = "src/test/resources/input.fo";
- private String xmlFile = "src/test/resources/input.xml";
+ private final String inputFile = "src/test/resources/input.html";
+ private final String style = "src/test/resources/xhtml2fo.xsl";
+ private final String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
+ private final String output_jtidy = "src/test/resources/output_jtidy.pdf";
+ private final String output_html2fo = "src/test/resources/output_html2fo.pdf";
+ private final String output_herold = "src/test/resources/output_herold.pdf";
+ private final String foFile = "src/test/resources/input.fo";
+ private final String xmlFile = "src/test/resources/input.xml";
@Test
public void whenTransformHTMLToPDFUsingJTidy_thenCorrect() throws Exception {
@@ -114,8 +114,9 @@ public class ApacheFOPConvertHTMLIntegrationTest {
private void fromHTMLTOXMLUsingHerold() throws Exception {
final Script script = new Script();
- final DocBookTransformer transformer = new DocBookTransformer();
- transformer.setScript(script);
- transformer.convert(new FileInputStream(inputFile), new FileOutputStream(xmlFile));
+ final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
+ transformer.setInputStream(new FileInputStream(inputFile));
+ transformer.setOutputStream(new FileOutputStream(xmlFile));
+ transformer.transform(script);
}
}
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
index 9e71cd9c16..8496222394 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
@@ -10,6 +10,7 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.transform.Result;
@@ -25,19 +26,15 @@ import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;
import org.dbdoclet.trafo.TrafoScriptManager;
-import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
+import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
import org.dbdoclet.trafo.script.Script;
import org.junit.Test;
import org.w3c.dom.Document;
public class ApacheFOPHeroldLiveTest {
- private String[] inputUrls = {// @formatter:off
- "http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
- "http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
- "http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/",
- "http://www.baeldung.com/spring-security-basic-authentication",
- "http://www.baeldung.com/spring-security-digest-authentication",
- "http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/",
+ private final String[] inputUrls = {// @formatter:off
+ // "http://www.baeldung.com/spring-security-basic-authentication",
+ "http://www.baeldung.com/spring-security-digest-authentication"
//"http://www.baeldung.com/spring-httpmessageconverter-rest",
//"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/",
//"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/",
@@ -49,10 +46,10 @@ public class ApacheFOPHeroldLiveTest {
//"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/"
}; // @formatter:on
- private String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
- private String output_file = "src/test/resources/final_output.pdf";
- private String xmlInput = "src/test/resources/input.xml";
- private String xmlOutput = "src/test/resources/output.xml";
+ private final String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
+ private final String output_file = "src/test/resources/final_output.pdf";
+ private final String xmlInput = "src/test/resources/input.xml";
+ private final String xmlOutput = "src/test/resources/output.xml";
// tests
@@ -75,10 +72,11 @@ public class ApacheFOPHeroldLiveTest {
final TrafoScriptManager mgr = new TrafoScriptManager();
final File profileFile = new File("src/test/resources/default.her");
script = mgr.parseScript(profileFile);
- final DocBookTransformer transformer = new DocBookTransformer();
- transformer.setScript(script);
+ final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
+ transformer.setInputStream(getInputStream(input));
+ transformer.setOutputStream(new FileOutputStream(xmlInput, append));
- transformer.convert(getInputStream(input), new FileOutputStream(xmlInput, append));
+ transformer.transform(script);
}
private Document fromXMLFileToFO() throws Exception {
@@ -112,7 +110,9 @@ public class ApacheFOPHeroldLiveTest {
private InputStream getInputStream(final String input) throws IOException {
final URL url = new URL(input);
- return url.openStream();
+ final HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
+ httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
+ return httpcon.getInputStream();
}
private void fixXML(final String input, final String output) throws IOException {
@@ -127,7 +127,7 @@ public class ApacheFOPHeroldLiveTest {
if (line.contains("info>")) {
writer.write(line.replace("info>", "section>"));
- } else if (!((line.startsWith(" 4)) {
+ } else if (!((line.startsWith(" 4))) {
writer.write(line.replaceAll("xml:id=\"", "xml:id=\"" + count));
}
writer.write("\n");
diff --git a/apache-fop/src/test/resources/jars/herold.jar b/apache-fop/src/test/resources/jars/herold.jar
deleted file mode 100644
index ef5d052f36..0000000000
Binary files a/apache-fop/src/test/resources/jars/herold.jar and /dev/null differ
diff --git a/apache-poi/.gitignore b/apache-poi/.gitignore
index e05054868c..9552c1e63d 100644
--- a/apache-poi/.gitignore
+++ b/apache-poi/.gitignore
@@ -1 +1,3 @@
*.docx
+temp.xls
+temp.xlsx
diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx
index 5281b2c4de..431a8a662c 100644
Binary files a/apache-poi/temp.xlsx and b/apache-poi/temp.xlsx differ
diff --git a/apache-solrj/README.md b/apache-solrj/README.md
new file mode 100644
index 0000000000..7a32becb64
--- /dev/null
+++ b/apache-solrj/README.md
@@ -0,0 +1,4 @@
+## Apache Solrj Tutorials Project
+
+### Relevant Articles
+- [Guide to Solr in Java with Apache Solrj](http://www.baeldung.com/apache-solrj)
diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java b/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java
new file mode 100644
index 0000000000..14eea8f2f9
--- /dev/null
+++ b/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java
@@ -0,0 +1,44 @@
+package com.baeldung.solrjava;
+
+import org.apache.solr.client.solrj.beans.Field;
+
+public class ProductBean {
+
+ String id;
+ String name;
+ String price;
+
+ public ProductBean(String id, String name, String price) {
+ super();
+ this.id = id;
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ @Field("id")
+ protected void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Field("name")
+ protected void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ @Field("price")
+ protected void setPrice(String price) {
+ this.price = price;
+ }
+}
diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java
index f2d21f0993..c55e1c9ada 100644
--- a/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java
+++ b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java
@@ -17,6 +17,12 @@ public class SolrJavaIntegration {
solrClient.setParser(new XMLResponseParser());
}
+ public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
+
+ solrClient.addBean(pBean);
+ solrClient.commit();
+ }
+
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
SolrInputDocument document = new SolrInputDocument();
@@ -27,12 +33,18 @@ public class SolrJavaIntegration {
solrClient.commit();
}
- public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
+ public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
solrClient.deleteById(documentId);
solrClient.commit();
}
+ public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
+
+ solrClient.deleteByQuery(query);
+ solrClient.commit();
+ }
+
protected HttpSolrClient getSolrClient() {
return solrClient;
}
@@ -40,4 +52,5 @@ public class SolrJavaIntegration {
protected void setSolrClient(HttpSolrClient solrClient) {
this.solrClient = solrClient;
}
+
}
diff --git a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java
index 22f9eae8ee..8b5fe77c6f 100644
--- a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java
+++ b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java
@@ -24,7 +24,7 @@ public class SolrJavaIntegrationTest {
}
@Test
- public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
+ public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
@@ -33,18 +33,68 @@ public class SolrJavaIntegrationTest {
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
- assertEquals(docList.getNumFound(), 1);
+ assertEquals(1, docList.getNumFound());
for (SolrDocument doc : docList) {
- assertEquals((String) doc.getFieldValue("id"), "123456");
- assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99);
+ assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
}
}
@Test
- public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
+ public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
- solrJavaIntegration.deleteSolrDocument("123456");
+ SolrQuery query = new SolrQuery();
+ query.set("q", "price:599.99");
+ QueryResponse response = null;
+
+ response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(1, docList.getNumFound());
+
+ for (SolrDocument doc : docList) {
+ assertEquals("123456", (String) doc.getFieldValue("id"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
+ }
+ }
+
+ @Test
+ public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
+
+ SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
+ assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
+ }
+
+ @Test
+ public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
+
+ ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
+ solrJavaIntegration.addProductBean(pBean);
+
+ SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
+ assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
+ }
+
+ @Test
+ public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
+
+ solrJavaIntegration.deleteSolrDocumentById("123456");
+
+ SolrQuery query = new SolrQuery();
+ query.set("q", "id:123456");
+ QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(0, docList.getNumFound());
+ }
+
+ @Test
+ public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
+
+ solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
SolrQuery query = new SolrQuery();
query.set("q", "id:123456");
@@ -53,6 +103,6 @@ public class SolrJavaIntegrationTest {
response = solrJavaIntegration.getSolrClient().query(query);
SolrDocumentList docList = response.getResults();
- assertEquals(docList.getNumFound(), 0);
+ assertEquals(0, docList.getNumFound());
}
}
diff --git a/aws/README.md b/aws/README.md
new file mode 100644
index 0000000000..10db004765
--- /dev/null
+++ b/aws/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
diff --git a/axon/README.md b/axon/README.md
new file mode 100644
index 0000000000..f1ae5d00d8
--- /dev/null
+++ b/axon/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [A Guide to the Axon Framework](http://www.baeldung.com/axon-cqrs-event-sourcing)
diff --git a/axon/pom.xml b/axon/pom.xml
new file mode 100644
index 0000000000..2bffa53bb8
--- /dev/null
+++ b/axon/pom.xml
@@ -0,0 +1,52 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+
+ axon
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+ org.axonframework
+ axon-test
+ ${axon.version}
+ test
+
+
+ org.axonframework
+ axon-core
+ ${axon.version}
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+
+ 3.0.2
+ 4.12
+
+
+
+
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/MessagesRunner.java b/axon/src/main/java/com/baeldung/axon/MessagesRunner.java
new file mode 100644
index 0000000000..77b50d09bd
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/MessagesRunner.java
@@ -0,0 +1,54 @@
+package com.baeldung.axon;
+
+import com.baeldung.axon.aggregates.MessagesAggregate;
+import com.baeldung.axon.commands.CreateMessageCommand;
+import com.baeldung.axon.commands.MarkReadMessageCommand;
+import com.baeldung.axon.eventhandlers.MessagesEventHandler;
+import org.axonframework.commandhandling.AggregateAnnotationCommandHandler;
+import org.axonframework.commandhandling.CommandBus;
+import org.axonframework.commandhandling.SimpleCommandBus;
+import org.axonframework.commandhandling.gateway.CommandGateway;
+import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
+import org.axonframework.eventhandling.AnnotationEventListenerAdapter;
+import org.axonframework.eventsourcing.EventSourcingRepository;
+import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
+import org.axonframework.eventsourcing.eventstore.EventStore;
+import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
+
+import java.util.UUID;
+
+public class MessagesRunner {
+
+ public static void main(String[] args) {
+ CommandBus commandBus = new SimpleCommandBus();
+
+ CommandGateway commandGateway = new DefaultCommandGateway(commandBus);
+
+ EventStore eventStore = new EmbeddedEventStore(new InMemoryEventStorageEngine());
+
+ EventSourcingRepository repository =
+ new EventSourcingRepository<>(MessagesAggregate.class, eventStore);
+
+
+ AggregateAnnotationCommandHandler messagesAggregateAggregateAnnotationCommandHandler =
+ new AggregateAnnotationCommandHandler(MessagesAggregate.class, repository);
+ messagesAggregateAggregateAnnotationCommandHandler.subscribe(commandBus);
+
+ final AnnotationEventListenerAdapter annotationEventListenerAdapter =
+ new AnnotationEventListenerAdapter(new MessagesEventHandler());
+ eventStore.subscribe(eventMessages -> eventMessages.forEach(e -> {
+ try {
+ annotationEventListenerAdapter.handle(e);
+ } catch (Exception e1) {
+ throw new RuntimeException(e1);
+
+ }
+ }
+
+ ));
+
+ final String itemId = UUID.randomUUID().toString();
+ commandGateway.send(new CreateMessageCommand(itemId, "Hello, how is your day? :-)"));
+ commandGateway.send(new MarkReadMessageCommand(itemId));
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java b/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java
new file mode 100644
index 0000000000..e762604b74
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java
@@ -0,0 +1,36 @@
+package com.baeldung.axon.aggregates;
+
+import com.baeldung.axon.commands.CreateMessageCommand;
+import com.baeldung.axon.commands.MarkReadMessageCommand;
+import com.baeldung.axon.events.MessageCreatedEvent;
+import com.baeldung.axon.events.MessageReadEvent;
+import org.axonframework.commandhandling.CommandHandler;
+import org.axonframework.commandhandling.model.AggregateIdentifier;
+import org.axonframework.eventhandling.EventHandler;
+
+import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
+
+
+public class MessagesAggregate {
+
+ @AggregateIdentifier
+ private String id;
+
+ public MessagesAggregate() {
+ }
+
+ @CommandHandler
+ public MessagesAggregate(CreateMessageCommand command) {
+ apply(new MessageCreatedEvent(command.getId(), command.getText()));
+ }
+
+ @EventHandler
+ public void on(MessageCreatedEvent event) {
+ this.id = event.getId();
+ }
+
+ @CommandHandler
+ public void markRead(MarkReadMessageCommand command) {
+ apply(new MessageReadEvent(id));
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java b/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java
new file mode 100644
index 0000000000..d0651bf12e
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java
@@ -0,0 +1,24 @@
+package com.baeldung.axon.commands;
+
+
+import org.axonframework.commandhandling.TargetAggregateIdentifier;
+
+public class CreateMessageCommand {
+
+ @TargetAggregateIdentifier
+ private final String id;
+ private final String text;
+
+ public CreateMessageCommand(String id, String text) {
+ this.id = id;
+ this.text = text;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getText() {
+ return text;
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java b/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java
new file mode 100644
index 0000000000..e66582d9ec
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java
@@ -0,0 +1,18 @@
+package com.baeldung.axon.commands;
+
+
+import org.axonframework.commandhandling.TargetAggregateIdentifier;
+
+public class MarkReadMessageCommand {
+
+ @TargetAggregateIdentifier
+ private final String id;
+
+ public MarkReadMessageCommand(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java b/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java
new file mode 100644
index 0000000000..3e51e19c4e
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java
@@ -0,0 +1,19 @@
+package com.baeldung.axon.eventhandlers;
+
+import com.baeldung.axon.events.MessageReadEvent;
+import com.baeldung.axon.events.MessageCreatedEvent;
+import org.axonframework.eventhandling.EventHandler;
+
+
+public class MessagesEventHandler {
+
+ @EventHandler
+ public void handle(MessageCreatedEvent event) {
+ System.out.println("Message received: " + event.getText() + " (" + event.getId() + ")");
+ }
+
+ @EventHandler
+ public void handle(MessageReadEvent event) {
+ System.out.println("Message read: " + event.getId());
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java b/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java
new file mode 100644
index 0000000000..3c9aac5ed8
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java
@@ -0,0 +1,20 @@
+package com.baeldung.axon.events;
+
+public class MessageCreatedEvent {
+
+ private final String id;
+ private final String text;
+
+ public MessageCreatedEvent(String id, String text) {
+ this.id = id;
+ this.text = text;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getText() {
+ return text;
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java b/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java
new file mode 100644
index 0000000000..57bfc8e19e
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java
@@ -0,0 +1,14 @@
+package com.baeldung.axon.events;
+
+public class MessageReadEvent {
+
+ private final String id;
+
+ public MessageReadEvent(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+}
\ No newline at end of file
diff --git a/axon/src/test/java/com/baeldung/axon/MessagesAggregateTest.java b/axon/src/test/java/com/baeldung/axon/MessagesAggregateTest.java
new file mode 100644
index 0000000000..bbeff18f27
--- /dev/null
+++ b/axon/src/test/java/com/baeldung/axon/MessagesAggregateTest.java
@@ -0,0 +1,42 @@
+package com.baeldung.axon;
+
+import com.baeldung.axon.aggregates.MessagesAggregate;
+import com.baeldung.axon.commands.CreateMessageCommand;
+import com.baeldung.axon.commands.MarkReadMessageCommand;
+import com.baeldung.axon.events.MessageCreatedEvent;
+import com.baeldung.axon.events.MessageReadEvent;
+import org.axonframework.test.aggregate.AggregateTestFixture;
+import org.axonframework.test.aggregate.FixtureConfiguration;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.UUID;
+
+public class MessagesAggregateTest {
+
+ private FixtureConfiguration fixture;
+
+ @Before
+ public void setUp() throws Exception {
+ fixture = new AggregateTestFixture(MessagesAggregate.class);
+
+ }
+
+ @Test
+ public void giveAggregateRoot_whenCreateMessageCommand_thenShouldProduceMessageCreatedEvent() throws Exception {
+ String eventText = "Hello, how is your day?";
+ String id = UUID.randomUUID().toString();
+ fixture.given()
+ .when(new CreateMessageCommand(id, eventText))
+ .expectEvents(new MessageCreatedEvent(id, eventText));
+ }
+
+ @Test
+ public void givenMessageCreatedEvent_whenReadMessageCommand_thenShouldProduceMessageReadEvent() throws Exception {
+ String id = UUID.randomUUID().toString();
+
+ fixture.given(new MessageCreatedEvent(id, "Hello :-)"))
+ .when(new MarkReadMessageCommand(id))
+ .expectEvents(new MessageReadEvent(id));
+ }
+}
\ No newline at end of file
diff --git a/core-java/0.004102810554955205 b/book
similarity index 100%
rename from core-java/0.004102810554955205
rename to book
diff --git a/core-java-9/README.md b/core-java-9/README.md
index 53ad79e59c..a6cda8e883 100644
--- a/core-java-9/README.md
+++ b/core-java-9/README.md
@@ -8,3 +8,7 @@
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
+- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
+- [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
+- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
+- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
diff --git a/core-java-9/compile-modules.sh b/core-java-9/compile-modules.sh
new file mode 100644
index 0000000000..4c9521de75
--- /dev/null
+++ b/core-java-9/compile-modules.sh
@@ -0,0 +1 @@
+javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")
\ No newline at end of file
diff --git a/core-java-9/compile-student-client.bat b/core-java-9/compile-student-client.bat
new file mode 100644
index 0000000000..72b2774480
--- /dev/null
+++ b/core-java-9/compile-student-client.bat
@@ -0,0 +1,3 @@
+javac --module-path mods -d mods/com.baeldung.student.client^
+ src/modules/com.baeldung.student.client/module-info.java^
+ src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java
\ No newline at end of file
diff --git a/core-java-9/compile-student-model.bat b/core-java-9/compile-student-model.bat
new file mode 100644
index 0000000000..902756c274
--- /dev/null
+++ b/core-java-9/compile-student-model.bat
@@ -0,0 +1,2 @@
+javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
+ src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java
\ No newline at end of file
diff --git a/core-java-9/compile-student-service-dbimpl.bat b/core-java-9/compile-student-service-dbimpl.bat
new file mode 100644
index 0000000000..bd1cfb7cfe
--- /dev/null
+++ b/core-java-9/compile-student-service-dbimpl.bat
@@ -0,0 +1,3 @@
+javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
+ src/modules/com.baeldung.student.service.dbimpl/module-info.java^
+ src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java
\ No newline at end of file
diff --git a/core-java-9/compile-student-service.bat b/core-java-9/compile-student-service.bat
new file mode 100644
index 0000000000..2892b237d1
--- /dev/null
+++ b/core-java-9/compile-student-service.bat
@@ -0,0 +1,3 @@
+javac --module-path mods -d mods/com.baeldung.student.service^
+ src/modules/com.baeldung.student.service/module-info.java^
+ src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java
\ No newline at end of file
diff --git a/core-java-9/run-student-client.bat b/core-java-9/run-student-client.bat
new file mode 100644
index 0000000000..2b78a26ec4
--- /dev/null
+++ b/core-java-9/run-student-client.bat
@@ -0,0 +1 @@
+java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
\ No newline at end of file
diff --git a/core-java-9/run-student-client.sh b/core-java-9/run-student-client.sh
new file mode 100644
index 0000000000..2b78a26ec4
--- /dev/null
+++ b/core-java-9/run-student-client.sh
@@ -0,0 +1 @@
+java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
\ No newline at end of file
diff --git a/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java b/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java
new file mode 100644
index 0000000000..46eee4883a
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungBatchSubscriberImpl.java
@@ -0,0 +1,82 @@
+package com.baeldung.java9.reactive;
+
+import java.util.ArrayList;
+import java.util.concurrent.Flow.Subscriber;
+import java.util.concurrent.Flow.Subscription;
+
+public class BaeldungBatchSubscriberImpl implements Subscriber {
+ private Subscription subscription;
+ private boolean completed = false;
+ private int counter;
+ private ArrayList buffer;
+ public static final int BUFFER_SIZE = 5;
+
+ public BaeldungBatchSubscriberImpl() {
+ buffer = new ArrayList();
+ }
+
+ public boolean isCompleted() {
+ return completed;
+ }
+
+ public void setCompleted(boolean completed) {
+ this.completed = completed;
+ }
+
+ public int getCounter() {
+ return counter;
+ }
+
+ public void setCounter(int counter) {
+ this.counter = counter;
+ }
+
+ @Override
+ public void onSubscribe(Subscription subscription) {
+ this.subscription = subscription;
+ subscription.request(BUFFER_SIZE);
+ }
+
+ @Override
+ public void onNext(String item) {
+ buffer.add(item);
+ // if buffer is full, process the items.
+ if (buffer.size() >= BUFFER_SIZE) {
+ processBuffer();
+ }
+ //request more items.
+ subscription.request(1);
+ }
+
+ private void processBuffer() {
+ if (buffer.isEmpty())
+ return;
+ // Process all items in the buffer. Here, we just print it and sleep for 1 second.
+ System.out.print("Processed items: ");
+ buffer.stream()
+ .forEach(item -> {
+ System.out.print(" " + item);
+ });
+ System.out.println();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ counter = counter + buffer.size();
+ buffer.clear();
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void onComplete() {
+ completed = true;
+ // process any remaining items in buffer before
+ processBuffer();
+ subscription.cancel();
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java b/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java
new file mode 100644
index 0000000000..bacd777255
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/reactive/BaeldungSubscriberImpl.java
@@ -0,0 +1,55 @@
+package com.baeldung.java9.reactive;
+
+import java.util.concurrent.Flow.Subscriber;
+import java.util.concurrent.Flow.Subscription;
+
+public class BaeldungSubscriberImpl implements Subscriber {
+ private Subscription subscription;
+ private boolean completed = false;
+ private int counter;
+
+ public boolean isCompleted() {
+ return completed;
+ }
+
+ public void setCompleted(boolean completed) {
+ this.completed = completed;
+ }
+
+ public int getCounter() {
+ return counter;
+ }
+
+ public void setCounter(int counter) {
+ this.counter = counter;
+ }
+
+ @Override
+ public void onSubscribe(Subscription subscription) {
+ this.subscription = subscription;
+ subscription.request(1);
+ }
+
+ @Override
+ public void onNext(String item) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ counter++;
+ System.out.println("Processed item : " + item);
+ subscription.request(1);
+ }
+
+ @Override
+ public void onError(Throwable t) {
+ t.printStackTrace();
+ }
+
+ @Override
+ public void onComplete() {
+ completed = true;
+ subscription.cancel();
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java b/core-java-9/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java
new file mode 100644
index 0000000000..a0e632d569
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/stackwalker/StackWalkerDemo.java
@@ -0,0 +1,84 @@
+package com.baeldung.java9.stackwalker;
+
+import java.lang.StackWalker.StackFrame;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class StackWalkerDemo {
+
+ public void methodOne() {
+ this.methodTwo();
+ }
+
+ public void methodTwo() {
+ this.methodThree();
+ }
+
+ public void methodThree() {
+ List stackTrace = StackWalker.getInstance()
+ .walk(this::walkExample);
+
+ printStackTrace(stackTrace);
+
+ System.out.println("---------------------------------------------");
+
+ stackTrace = StackWalker.getInstance()
+ .walk(this::walkExample2);
+
+ printStackTrace(stackTrace);
+
+ System.out.println("---------------------------------------------");
+
+ String line = StackWalker.getInstance().walk(this::walkExample3);
+ System.out.println(line);
+
+ System.out.println("---------------------------------------------");
+
+ stackTrace = StackWalker.getInstance(StackWalker.Option.SHOW_REFLECT_FRAMES)
+ .walk(this::walkExample);
+
+ printStackTrace(stackTrace);
+
+ System.out.println("---------------------------------------------");
+
+ Runnable r = () -> {
+ List stackTrace2 = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES)
+ .walk(this::walkExample);
+ printStackTrace(stackTrace2);
+ };
+ r.run();
+ }
+
+ public List walkExample(Stream stackFrameStream) {
+ return stackFrameStream.collect(Collectors.toList());
+ }
+
+ public List walkExample2(Stream stackFrameStream) {
+ return stackFrameStream.filter(frame -> frame.getClassName()
+ .contains("com.baeldung"))
+ .collect(Collectors.toList());
+ }
+
+ public String walkExample3(Stream stackFrameStream) {
+ return stackFrameStream.filter(frame -> frame.getClassName()
+ .contains("com.baeldung")
+ && frame.getClassName()
+ .endsWith("Test"))
+ .findFirst()
+ .map(frame -> frame.getClassName() + "#" + frame.getMethodName() + ", Line " + frame.getLineNumber())
+ .orElse("Unknown caller");
+ }
+
+ public void findCaller() {
+ Class> caller = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
+ System.out.println(caller.getCanonicalName());
+ }
+
+ public void printStackTrace(List stackTrace) {
+ for (StackFrame stackFrame : stackTrace) {
+ System.out.println(stackFrame.getClassName()
+ .toString() + "#" + stackFrame.getMethodName() + ", Line " + stackFrame.getLineNumber());
+ }
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java b/core-java-9/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java
new file mode 100644
index 0000000000..e6fce9163f
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java
@@ -0,0 +1,16 @@
+package com.baeldung.student.client;
+
+import com.baeldung.student.service.StudentService;
+import com.baeldung.student.service.dbimpl.StudentDbService;
+import com.baeldung.student.model.Student;
+
+public class StudentClient {
+
+ public static void main(String[] args) {
+ StudentService service = new StudentDbService();
+ service.create(new Student());
+ service.read("17SS0001");
+ service.update(new Student());
+ service.delete("17SS0001");
+ }
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.client/module-info.java b/core-java-9/src/modules/com.baeldung.student.client/module-info.java
new file mode 100644
index 0000000000..7ef7b430fc
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.client/module-info.java
@@ -0,0 +1,3 @@
+module com.baeldung.student.client{
+ requires com.baeldung.student.service.dbimpl;
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java b/core-java-9/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java
new file mode 100644
index 0000000000..d7f8f69107
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java
@@ -0,0 +1,15 @@
+package com.baeldung.student.model;
+
+import java.util.Date;
+
+public class Student {
+ private String registrationId;
+
+ public String getRegistrationId() {
+ return registrationId;
+ }
+
+ public void setRegistrationId(String registrationId) {
+ this.registrationId = registrationId;
+ }
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.model/module-info.java b/core-java-9/src/modules/com.baeldung.student.model/module-info.java
new file mode 100644
index 0000000000..3bdab058d4
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.model/module-info.java
@@ -0,0 +1,3 @@
+module com.baeldung.student.model{
+ exports com.baeldung.student.model;
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java b/core-java-9/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java
new file mode 100644
index 0000000000..2519da085b
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java
@@ -0,0 +1,30 @@
+package com.baeldung.student.service.dbimpl;
+
+import com.baeldung.student.service.StudentService;
+import com.baeldung.student.model.Student;
+import java.util.logging.*;
+
+public class StudentDbService implements StudentService {
+
+ private static Logger logger = Logger.getLogger("StudentDbService");
+
+ public String create(Student student) {
+ logger.log(Level.INFO, "Creating student in DB...");
+ return student.getRegistrationId();
+ }
+
+ public Student read(String registrationId) {
+ logger.log(Level.INFO, "Reading student from DB...");
+ return new Student();
+ }
+
+ public Student update(Student student) {
+ logger.log(Level.INFO, "Updating sutdent in DB...");
+ return student;
+ }
+
+ public String delete(String registrationId) {
+ logger.log(Level.INFO, "Deleteing sutdent in DB...");
+ return registrationId;
+ }
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.service.dbimpl/module-info.java b/core-java-9/src/modules/com.baeldung.student.service.dbimpl/module-info.java
new file mode 100644
index 0000000000..96a453ea6b
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.service.dbimpl/module-info.java
@@ -0,0 +1,5 @@
+module com.baeldung.student.service.dbimpl{
+ requires transitive com.baeldung.student.service;
+ exports com.baeldung.student.service.dbimpl;
+ requires java.logging;
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java b/core-java-9/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java
new file mode 100644
index 0000000000..6076bf12e3
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java
@@ -0,0 +1,14 @@
+package com.baeldung.student.service;
+
+import com.baeldung.student.model.Student;
+
+public interface StudentService {
+
+ public String create(Student student);
+
+ public Student read(String registrationId);
+
+ public Student update(Student student);
+
+ public String delete(String registrationId);
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.student.service/module-info.java b/core-java-9/src/modules/com.baeldung.student.service/module-info.java
new file mode 100644
index 0000000000..5de9e58348
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.student.service/module-info.java
@@ -0,0 +1,4 @@
+module com.baeldung.student.service{
+ requires transitive com.baeldung.student.model;
+ exports com.baeldung.student.service;
+}
\ No newline at end of file
diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
index 121c17a860..a6060b1a9d 100644
--- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
+++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.java8;
+package com.baeldung.java9;
import static org.junit.Assert.assertEquals;
@@ -8,7 +8,6 @@ import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import org.junit.Before;
import org.junit.Test;
public class Java9OptionalsStreamTest {
diff --git a/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureTest.java b/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureTest.java
new file mode 100644
index 0000000000..b71c211177
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.java9.concurrent.future;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+
+public class CompletableFutureTest {
+ @Test
+ public void testDelay () throws Exception {
+ Object input = new Object();
+ CompletableFuture
+
+
+ org.javamoney
+ moneta
+ 1.1
+
@@ -192,7 +198,6 @@
org.apache.maven.plugins
maven-surefire-plugin
- ${maven-surefire-plugin.version}
**/*IntegrationTest.java
@@ -244,6 +249,7 @@
single
+ ${project.basedir}
org.baeldung.executable.ExecutableMavenJar
diff --git a/core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java b/core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
deleted file mode 100644
index e46ac77e84..0000000000
--- a/core-java/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package com.baeldung.algorithms.ga.ant_colony;
-
-import java.util.Arrays;
-import java.util.Random;
-
-public class AntColonyOptimization {
-
- private double c = 1.0;
- private double alpha = 1;
- private double beta = 5;
- private double evaporation = 0.5;
- private double Q = 500;
- private double antFactor = 0.8;
- private double randomFactor = 0.01;
-
- private int maxIterations = 1000;
-
- public int numberOfCities;
- public int numberOfAnts;
- private double graph[][];
- private double trails[][];
- private Ant ants[];
- private Random random = new Random();
- private double probabilities[];
-
- private int currentIndex;
-
- public int[] bestTourOrder;
- public double bestTourLength;
-
- public AntColonyOptimization(int noOfCities) {
- graph = generateRandomMatrix(noOfCities);
- numberOfCities = graph.length;
- numberOfAnts = (int) (numberOfCities * antFactor);
-
- trails = new double[numberOfCities][numberOfCities];
- probabilities = new double[numberOfCities];
- ants = new Ant[numberOfAnts];
- for (int j = 0; j < numberOfAnts; j++) {
- ants[j] = new Ant(numberOfCities);
- }
- }
-
- /**
- * Generate initial solution
- * @param n
- * @return
- */
- public double[][] generateRandomMatrix(int n) {
- double[][] randomMatrix = new double[n][n];
- random.setSeed(System.currentTimeMillis());
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- Integer r = random.nextInt(100) + 1;
- randomMatrix[i][j] = Math.abs(r);
- }
- }
- return randomMatrix;
- }
-
- /**
- * Perform ant optimization
- * @return
- */
- public int[] startAntOptimization() {
- int[] finalResult = null;
- for (int i = 1; i <= 3; i++) {
- System.out.println("Attempt #" + i);
- finalResult = solve();
- }
- return finalResult;
- }
-
- /**
- * Use this method to run the main logic
- * @return
- */
- private int[] solve() {
- setupAnts();
- clearTrails();
- int iteration = 0;
- while (iteration < maxIterations) {
- moveAnts();
- updateTrails();
- updateBest();
- iteration++;
- }
- System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
- System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
- return bestTourOrder.clone();
- }
-
- /**
- * Prepare ants for the simulation
- */
- private void setupAnts() {
- currentIndex = -1;
- for (int i = 0; i < numberOfAnts; i++) {
- ants[i].clear();
- ants[i].visitCity(currentIndex, random.nextInt(numberOfCities));
- }
- currentIndex++;
- }
-
- /**
- * At each iteration, move ants
- */
- private void moveAnts() {
- while (currentIndex < numberOfCities - 1) {
- for (Ant a : ants)
- a.visitCity(currentIndex, selectNextCity(a));
- currentIndex++;
- }
- }
-
- /**
- * Select next city for each ant
- * @param ant
- * @return
- */
- private int selectNextCity(Ant ant) {
- if (random.nextDouble() < randomFactor) {
- int t = random.nextInt(numberOfCities - currentIndex);
- int j = -1;
- for (int i = 0; i < numberOfCities; i++) {
- if (!ant.visited(i)) {
- j++;
- }
- if (j == t) {
- return i;
- }
- }
- }
- calculateProbabilities(ant);
- double r = random.nextDouble();
- double total = 0;
- for (int i = 0; i < numberOfCities; i++) {
- total += probabilities[i];
- if (total >= r) {
- return i;
- }
- }
-
- throw new RuntimeException("There are no other cities");
- }
-
- /**
- * Calculate the next city picks probabilites
- * @param ant
- */
- private void calculateProbabilities(Ant ant) {
- int i = ant.trail[currentIndex];
- double pheromone = 0.0;
- for (int l = 0; l < numberOfCities; l++) {
- if (!ant.visited(l)) {
- pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
- }
- }
- for (int j = 0; j < numberOfCities; j++) {
- if (ant.visited(j)) {
- probabilities[j] = 0.0;
- } else {
- double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
- probabilities[j] = numerator / pheromone;
- }
- }
- }
-
- /**
- * Update trails that ants used
- */
- private void updateTrails() {
- for (int i = 0; i < numberOfCities; i++) {
- for (int j = 0; j < numberOfCities; j++) {
- trails[i][j] *= evaporation;
- }
- }
- for (Ant a : ants) {
- double contribution = Q / a.trailLength(graph);
- for (int i = 0; i < numberOfCities - 1; i++) {
- trails[a.trail[i]][a.trail[i + 1]] += contribution;
- }
- trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
- }
- }
-
- /**
- * Update the best solution
- */
- private void updateBest() {
- if (bestTourOrder == null) {
- bestTourOrder = ants[0].trail;
- bestTourLength = ants[0].trailLength(graph);
- }
- for (Ant a : ants) {
- if (a.trailLength(graph) < bestTourLength) {
- bestTourLength = a.trailLength(graph);
- bestTourOrder = a.trail.clone();
- }
- }
- }
-
- /**
- * Clear trails after simulation
- */
- private void clearTrails() {
- for (int i = 0; i < numberOfCities; i++)
- for (int j = 0; j < numberOfCities; j++)
- trails[i][j] = c;
- }
-
-}
diff --git a/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java b/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java
new file mode 100644
index 0000000000..43c6d77fe6
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/arraycopy/model/Address.java
@@ -0,0 +1,61 @@
+package com.baeldung.arraycopy.model;
+
+public class Address implements Cloneable {
+ private String country;
+ private String state;
+ private String city;
+ private String street;
+ private String zipcode;
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+
+ public String getZipcode() {
+ return zipcode;
+ }
+
+ public void setZipcode(String zipcode) {
+ this.zipcode = zipcode;
+ }
+
+ @Override
+ protected Object clone() throws CloneNotSupportedException {
+ super.clone();
+ Address address = new Address();
+ address.setCity(this.city);
+ address.setCountry(this.country);
+ address.setState(this.state);
+ address.setStreet(this.street);
+ address.setZipcode(this.zipcode);
+ return address;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java b/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java
new file mode 100644
index 0000000000..757a8f8ec1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/arraycopy/model/Employee.java
@@ -0,0 +1,25 @@
+package com.baeldung.arraycopy.model;
+
+import java.io.Serializable;
+
+public class Employee implements Serializable {
+ private static final long serialVersionUID = -2454619097207585825L;
+ private int id;
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/money/JavaMoney.java b/core-java/src/main/java/com/baeldung/money/JavaMoney.java
new file mode 100644
index 0000000000..3171d226ed
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/money/JavaMoney.java
@@ -0,0 +1,151 @@
+package com.baeldung.money;
+
+import java.util.Locale;
+import java.util.logging.Logger;
+
+import javax.money.CurrencyUnit;
+import javax.money.Monetary;
+import javax.money.MonetaryAmount;
+import javax.money.UnknownCurrencyException;
+import javax.money.convert.ConversionQueryBuilder;
+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 org.javamoney.moneta.FastMoney;
+import org.javamoney.moneta.Money;
+import org.javamoney.moneta.format.CurrencyStyle;
+
+public class JavaMoney {
+ final static Logger LOGGER = Logger.getLogger(JavaMoney.class.getName());
+ CurrencyUnit USD;
+ MonetaryAmount fstAmtUSD;
+ MonetaryAmount fstAmtEUR;
+ MonetaryAmount oneDolar;
+ MonetaryAmount moneyof;
+ MonetaryAmount fastmoneyof;
+ MonetaryAmount roundEUR;
+ MonetaryAmount calcAmtUSD;
+ MonetaryAmount[] monetaryAmounts;
+ MonetaryAmount sumAmtCHF;
+ MonetaryAmount calcMoneyFastMoney;
+ MonetaryAmount convertedAmountEURtoUSD;
+ MonetaryAmount convertedAmountEURtoUSD2;
+ MonetaryAmount convertedAmountUSDtoEUR;
+ MonetaryAmount convertedAmountUSDtoEUR2;
+ MonetaryAmount multiplyAmount;
+ MonetaryAmount divideAmount;
+ MonetaryAmount oneDivThree;
+ CurrencyConversion convEUR;
+ CurrencyConversion convUSD;
+ CurrencyConversion conversionUSD;
+ CurrencyConversion conversionEUR;
+ MonetaryAmount oneEuro;
+ MonetaryAmountFormat formatUSD;
+ MonetaryAmountFormat customFormat;
+ String usFormatted;
+ String customFormatted;
+
+ public JavaMoney() {
+ USD = Monetary.getCurrency("USD");
+ fstAmtUSD = Monetary.getDefaultAmountFactory().setCurrency(USD).setNumber(200.50).create();
+ fstAmtEUR = Monetary.getDefaultAmountFactory().setCurrency("EUR").setNumber(1.30473908).create();
+ oneDolar = Monetary.getDefaultAmountFactory().setCurrency("USD").setNumber(1).create();
+ moneyof = Money.of(12, USD);
+ fastmoneyof = FastMoney.of(2, USD);
+
+ LOGGER.info("First Amount in USD : " + fstAmtUSD);
+ LOGGER.info("First Amount in EUR : " + fstAmtEUR);
+ LOGGER.info("One Dolar : " + oneDolar);
+ LOGGER.info("MoneyOf : " + moneyof);
+ LOGGER.info("FastMoneyOf : " + fastmoneyof);
+
+ try{
+ @SuppressWarnings("unused")
+ CurrencyUnit AAA = Monetary.getCurrency("AAA");
+ } catch (UnknownCurrencyException e) {
+ LOGGER.severe("Unknown Currency");
+ }
+
+ roundEUR = fstAmtEUR.with(Monetary.getDefaultRounding());
+
+ LOGGER.info("Rounded EUR : " + roundEUR);
+
+ calcAmtUSD = Money.of(1, "USD").subtract(fstAmtUSD);
+
+ LOGGER.info("Substracting amounts : " + calcAmtUSD);
+
+ calcMoneyFastMoney = moneyof.subtract(fastmoneyof);
+
+ LOGGER.info("Money & FastMoney operations : " + calcMoneyFastMoney);
+
+ monetaryAmounts =
+ new MonetaryAmount[] {
+ Money.of(100, "CHF"),
+ Money.of(10.20, "CHF"),
+ Money.of(1.15, "CHF"), };
+ sumAmtCHF = Money.of(0, "CHF");
+ for (MonetaryAmount monetaryAmount : monetaryAmounts) {
+ sumAmtCHF = sumAmtCHF.add(monetaryAmount);
+ }
+
+ LOGGER.info("Adding amounts : " + sumAmtCHF);
+
+ multiplyAmount = oneDolar.multiply(0.25);
+ LOGGER.info("Multiply Amount : " + multiplyAmount);
+
+ divideAmount = oneDolar.divide(0.25);
+ LOGGER.info("Divide Amount : " + divideAmount);
+
+ try{
+ oneDivThree = oneDolar.divide(3);
+ }catch (ArithmeticException e) {
+ LOGGER.severe("One divide by Three is an infinite number");
+ }
+
+ convEUR = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency("EUR").build());
+ convUSD = MonetaryConversions.getConversion(ConversionQueryBuilder.of().setTermCurrency(USD).build());
+
+ conversionUSD = MonetaryConversions.getConversion("USD");
+ conversionEUR = MonetaryConversions.getConversion("EUR");
+
+ convertedAmountEURtoUSD = fstAmtEUR.with(conversionUSD);
+ convertedAmountEURtoUSD2 = fstAmtEUR.with(convUSD);
+ convertedAmountUSDtoEUR = oneDolar.with(conversionEUR);
+ convertedAmountUSDtoEUR2 = oneDolar.with(convEUR);
+ LOGGER.info("C1 - " + convertedAmountEURtoUSD);
+ LOGGER.info("C2 - " + convertedAmountEURtoUSD2);
+ LOGGER.info("One Euro -> " + convertedAmountUSDtoEUR);
+ LOGGER.info("One Euro2 -> " + convertedAmountUSDtoEUR2);
+
+ oneEuro = Money.of(1, "EUR");
+
+ if (oneEuro.equals(FastMoney.of(1, "EUR"))) {
+ LOGGER.info("Money == FastMoney");
+ } else {
+ LOGGER.info("Money != FastMoney");
+ }
+
+ if (oneDolar.equals(Money.of(1, "USD"))) {
+ LOGGER.info("Factory == Money");
+ } else {
+ LOGGER.info("Factory != Money");
+ }
+
+ formatUSD = MonetaryFormats.getAmountFormat(Locale.US);
+ usFormatted = formatUSD.format(oneDolar);
+ LOGGER.info("One dolar standard formatted : " + usFormatted);
+
+ customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.US).set(CurrencyStyle.NAME).set("pattern", "00000.00 ¤").build());
+ customFormatted = customFormat.format(oneDolar);
+ LOGGER.info("One dolar custom formatted : " + customFormatted);
+ }
+
+ public static void main(String[] args) {
+ @SuppressWarnings("unused")
+ JavaMoney java9Money = new JavaMoney();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/pow/PowerExample.java b/core-java/src/main/java/com/baeldung/pow/PowerExample.java
new file mode 100644
index 0000000000..5be5376e6a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/pow/PowerExample.java
@@ -0,0 +1,19 @@
+package com.baeldung.pow;
+
+import java.text.DecimalFormat;
+
+public class PowerExample {
+
+ public static void main(String[] args) {
+
+ int intResult = (int) Math.pow(2, 3);
+ System.out.println("Math.pow(2, 3) = " + intResult);
+
+ double dblResult = Math.pow(4.2, 3);
+ System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
+
+ DecimalFormat df = new DecimalFormat(".00");
+ System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java
new file mode 100644
index 0000000000..130218acc2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/stringtokenizer/MyTokenizer.java
@@ -0,0 +1,52 @@
+package com.baeldung.stringtokenizer;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.stream.Collectors;
+
+public class MyTokenizer {
+
+ public List getTokens(String str) {
+ List tokens = new ArrayList<>();
+ // StringTokenizer tokenizer = new StringTokenizer( str );
+ StringTokenizer tokenizer = new StringTokenizer(str, ",");
+ // StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
+ while (tokenizer.hasMoreElements()) {
+ tokens.add(tokenizer.nextToken());
+ // tokens.add( tokenizer.nextToken("e") );
+ }
+ int tokenLength = tokens.size();
+ return tokens;
+ }
+
+ public List getTokensWithCollection(String str) {
+ return Collections
+ .list(new StringTokenizer(str, ","))
+ .stream()
+ .map(token -> (String) token)
+ .collect(Collectors.toList());
+ }
+
+ public List getTokensFromFile(String path, String delim) {
+ List tokens = new ArrayList<>();
+ String currLine;
+ StringTokenizer tokenizer;
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(MyTokenizer.class.getResourceAsStream("/" + path)))) {
+ while ((currLine = br.readLine()) != null) {
+ tokenizer = new StringTokenizer(currLine, delim);
+ while (tokenizer.hasMoreElements()) {
+ tokens.add(tokenizer.nextToken());
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return tokens;
+ }
+
+}
diff --git a/core-java/src/main/resources/data.csv b/core-java/src/main/resources/data.csv
new file mode 100644
index 0000000000..ec4ac10443
--- /dev/null
+++ b/core-java/src/main/resources/data.csv
@@ -0,0 +1,3 @@
+1|IND|India
+2|MY|Malaysia
+3|AU|Australia
diff --git a/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java b/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java
new file mode 100644
index 0000000000..10ceaf85a4
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/PrimitiveConversionsJUnitTest.java
@@ -0,0 +1,125 @@
+package com.baeldung;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ * @author paulo.motta
+ */
+public class PrimitiveConversionsJUnitTest {
+
+ @Test
+ public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
+ int myInt = 127;
+
+ long myLong = myInt;
+ assertEquals(127L, myLong);
+
+ float myFloat = myLong;
+ assertEquals(127.0f, myFloat, 0.00001f);
+
+ double myDouble = myLong;
+ assertEquals(127.0, myDouble,0.00001);
+ }
+
+ @Test
+ public void givenDataWithMoreBits_whenAttributingToSmallerSizeVariable_thenCastOperatorNeeded() {
+
+ long myLong = 127L;
+ double myDouble = 127.0;
+
+ float myFloat = (float) myDouble;
+ assertEquals(127.0f, myFloat, 0.00001f);
+
+ int myInt = (int) myLong;
+ assertEquals(127, myInt);
+
+ byte myByte = (byte) myInt;
+ assertEquals( ((byte)127), myByte);
+ }
+
+ @Test
+ public void givenPrimitiveData_whenAssiginingToWrapper_thenAutomaticBoxingHappens(){
+ int myInt = 127;
+
+ Integer myIntegerReference = myInt;
+ assertEquals(new Integer("127"), myIntegerReference);
+
+ }
+
+ @Test
+ public void givenWrapperObjectData_whenAssiginingToPrimitive_thenAutomaticUnboxingHappens(){
+ Integer myIntegerReference = new Integer("127");
+
+ int myOtherInt = myIntegerReference;
+ assertEquals(127, myOtherInt);
+
+ }
+
+ @Test
+ public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
+ byte myLargeValueByte = (byte) 130; //0b10000010
+ System.out.println(myLargeValueByte); //0b10000010 -126
+ assertEquals( -126, myLargeValueByte);
+
+ int myLargeValueInt = myLargeValueByte;
+ System.out.println(myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
+ assertEquals( -126, myLargeValueInt);
+
+ char myLargeValueChar = (char) myLargeValueByte;
+ System.out.println(myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
+ assertEquals(0xFF82, myLargeValueChar);
+
+ myLargeValueInt = myLargeValueChar;
+ System.out.println(myLargeValueInt); //0b11111111 10000010 65410
+ assertEquals(65410, myLargeValueInt);
+
+ byte myOtherByte = (byte) myLargeValueInt;
+ System.out.println(myOtherByte); //0b10000010 -126
+ assertEquals( -126, myOtherByte);
+
+
+ char myLargeValueChar2 = 130; //This is an int not a byte!
+ System.out.println(myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082
+ assertEquals(0x0082, myLargeValueChar2);
+
+ int myLargeValueInt2 = myLargeValueChar2;
+ System.out.println(myLargeValueInt2); //0b00000000 10000010 130
+ assertEquals(130, myLargeValueInt2);
+
+ byte myOtherByte2 = (byte) myLargeValueInt2;
+ System.out.println(myOtherByte2); //0b10000010 -126
+ assertEquals( -126, myOtherByte2);
+ }
+
+ @Test
+ public void givenString_whenParsingWithWrappers_thenValuesAreReturned(){
+ String myString = "127";
+
+ byte myNewByte = Byte.parseByte(myString);
+ assertEquals( ((byte)127), myNewByte);
+
+ short myNewShort = Short.parseShort(myString);
+ assertEquals( ((short)127), myNewShort);
+
+ int myNewInt = Integer.parseInt(myString);
+ assertEquals( 127, myNewInt);
+
+ long myNewLong = Long.parseLong(myString);
+ assertEquals( 127L, myNewLong);
+
+ float myNewFloat = Float.parseFloat(myString);
+ assertEquals( 127.0f, myNewFloat, 0.00001f);
+
+ double myNewDouble = Double.parseDouble(myString);
+ assertEquals( 127.0, myNewDouble, 0.00001f);
+
+ boolean myNewBoolean = Boolean.parseBoolean(myString);
+ assertEquals( false, myNewBoolean); //numbers are not true!
+
+ char myNewChar = myString.charAt(0);
+ assertEquals( 49, myNewChar); //the value of '1'
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java
new file mode 100644
index 0000000000..2235e55338
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/arraycopy/ArrayCopyUtilTest.java
@@ -0,0 +1,168 @@
+package com.baeldung.arraycopy;
+
+import com.baeldung.arraycopy.model.Address;
+import com.baeldung.arraycopy.model.Employee;
+import org.apache.commons.lang3.SerializationUtils;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.Arrays;
+
+public class ArrayCopyUtilTest {
+ private static Employee[] employees;
+ private static final int MAX = 2;
+
+ @BeforeClass
+ public static void setup(){
+ createEmployeesArray();
+ }
+
+ private static void createEmployeesArray() {
+ employees = new Employee[MAX];
+ Employee employee;
+ for(int i = 0; i < MAX; i++) {
+ employee = new Employee();
+ employee.setName("Emp"+i);
+ employee.setId(i);
+ employees[i] = employee;
+ }
+ }
+
+ @Test
+ public void givenArrayOfPrimitiveType_whenCopiedViaSystemsArrayCopy_thenSuccessful(){
+ int[] array = {23, 43, 55};
+ int[] copiedArray = new int[3];
+
+ System.arraycopy(array, 0, copiedArray, 0, 3);
+
+ Assert.assertArrayEquals(copiedArray, array);
+ }
+
+ @Test
+ public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaSystemsArrayCopy_thenSuccessful(){
+ int[] array = {23, 43, 55, 12, 65, 88, 92};
+ int[] copiedArray = new int[3];
+
+ System.arraycopy(array, 2, copiedArray, 0, 3);
+
+ Assert.assertTrue(3 == copiedArray.length);
+ Assert.assertTrue(copiedArray[0] == array[2]);
+ Assert.assertTrue(copiedArray[1] == array[3]);
+ Assert.assertTrue(copiedArray[2] == array[4]);
+ }
+
+ @Test
+ public void givenArrayOfPrimitiveType_whenCopiedSubSequenceViaArraysCopyOfRange_thenSuccessful(){
+ int[] array = {23, 43, 55, 12, 65, 88, 92};
+
+ int[] copiedArray = Arrays.copyOfRange(array, 1, 4);
+
+ Assert.assertTrue(3 == copiedArray.length);
+ Assert.assertTrue(copiedArray[0] == array[1]);
+ Assert.assertTrue(copiedArray[1] == array[2]);
+ Assert.assertTrue(copiedArray[2] == array[3]);
+ }
+
+ @Test
+ public void givenArrayOfPrimitiveType_whenCopiedViaArraysCopyOf_thenValueChangeIsSuccessful(){
+ int[] array = {23, 43, 55, 12};
+ int newLength = array.length;
+
+ int[] copiedArray = Arrays.copyOf(array, newLength);
+
+ Assert.assertArrayEquals(copiedArray, array);
+ array[0] = 9;
+ Assert.assertTrue(copiedArray[0] != array[0]);
+ copiedArray[1] = 12;
+ Assert.assertTrue(copiedArray[1] != array[1]);
+ }
+
+ @Test
+ public void givenArrayOfNonPrimitiveType_whenCopiedViaArraysCopyOf_thenDoShallowCopy(){
+ Employee[] copiedArray = Arrays.copyOf(employees, employees.length);
+
+ Assert.assertArrayEquals(copiedArray, employees);
+ employees[0].setName(employees[0].getName()+"_Changed");
+ //change in employees' element caused change in the copied array
+ Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ }
+
+ @Test
+ public void givenArrayOfPrimitiveType_whenCopiedViaArrayClone_thenValueChangeIsSuccessful(){
+ int[] array = {23, 43, 55, 12};
+
+ int[] copiedArray = array.clone();
+
+ Assert.assertArrayEquals(copiedArray, array);
+ array[0] = 9;
+ Assert.assertTrue(copiedArray[0] != array[0]);
+ copiedArray[1] = 12;
+ Assert.assertTrue(copiedArray[1] != array[1]);
+ }
+
+ @Test
+ public void givenArraysOfNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
+ Employee[] copiedArray = employees.clone();
+
+ Assert.assertArrayEquals(copiedArray, employees);;
+ employees[0].setName(employees[0].getName()+"_Changed");
+ //change in employees' element changed the copied array
+ Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ }
+
+ @Test
+ public void givenArraysOfCloneableNonPrimitiveType_whenCopiedViaArrayClone_thenDoShallowCopy(){
+ Address[] addresses = createAddressArray();
+
+ Address[] copiedArray = addresses.clone();
+
+ addresses[0].setCity(addresses[0].getCity()+"_Changed");
+ Assert.assertArrayEquals(copiedArray, addresses);
+ }
+
+ @Test
+ public void givenArraysOfSerializableNonPrimitiveType_whenCopiedViaSerializationUtils_thenDoDeepCopy(){
+ Employee[] copiedArray = SerializationUtils.clone(employees);
+
+ employees[0].setName(employees[0].getName()+"_Changed");
+ //change in employees' element didn't change in the copied array
+ Assert.assertFalse(
+ copiedArray[0].getName().equals(employees[0].getName()));
+ }
+
+ @Test
+ public void givenArraysOfNonPrimitiveType_whenCopiedViaStream_thenDoShallowCopy(){
+ Employee[] copiedArray = Arrays.stream(employees).toArray(Employee[]::new);
+
+ Assert.assertArrayEquals(copiedArray, employees);
+ employees[0].setName(employees[0].getName()+"_Changed");
+ //change in employees' element didn't change in the copied array
+ Assert.assertTrue(copiedArray[0].getName().equals(employees[0].getName()));
+ }
+
+ @Test
+ public void givenArraysOfPrimitiveType_whenCopiedViaStream_thenSuccessful(){
+ String[] strArray = {"orange", "red", "green'"};
+
+ String[] copiedArray = Arrays.stream(strArray).toArray(String[]::new);
+
+ Assert.assertArrayEquals(copiedArray, strArray);
+ }
+
+ private Address[] createAddressArray(){
+ Address[] addresses = new Address[1];
+ addresses[0] = createAddress();
+ return addresses;
+ }
+
+ private Address createAddress() {
+ Address address = new Address();
+ address.setCountry("USA");
+ address.setState("CA");
+ address.setCity("San Francisco");
+ address.setStreet("Street 1");
+ address.setZipcode("59999");
+ return address;
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java
similarity index 98%
rename from core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java
rename to core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java
index 7bb2d4bb70..fc343e4cee 100644
--- a/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleTest.java
+++ b/core-java/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java
@@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
-public class CountdownLatchExampleTest {
+public class CountdownLatchExampleIntegrationTest {
@Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given
diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
index 6cf6ad3551..35aa07821c 100644
--- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
@@ -1,5 +1,6 @@
package com.baeldung.enums;
+import com.baeldung.enums.Pizza.PizzaStatusEnum;
import org.junit.Test;
import java.util.ArrayList;
@@ -69,11 +70,31 @@ public class PizzaUnitTest {
}
@Test
- public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
+ public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
+
+ @Test
+ public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
+ String pizzaEnumValue = "READY";
+ PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
+ assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void whenConvertedIntoEnum_thenThrowsException() {
+ String pizzaEnumValue = "rEAdY";
+ PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
+ String pizzaEnumValue = "invalid";
+ PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
+ }
+
}
diff --git a/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java b/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java
new file mode 100644
index 0000000000..100d25ab8d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/collections/ConcurrentModificationExceptionTest.java
@@ -0,0 +1,82 @@
+package com.baeldung.java.collections;
+
+import org.junit.Test;
+
+import java.util.*;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import static java.util.Arrays.asList;
+import static org.testng.Assert.assertEquals;
+
+public class ConcurrentModificationExceptionTest {
+ @Test
+ public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
+ ArrayList array = new ArrayList<>(asList(0, "one", 2, "three"));
+
+ for (Object item : array) {
+ array.set(3, 3);
+ }
+ }
+
+ @Test
+ public void removingElementUsingIteratorAPI() throws Exception {
+ List originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
+
+ Iterator iterator = originalList.iterator();
+
+ while (iterator.hasNext()) {
+ String next = iterator.next();
+ if (Objects.equals(next, "one")) iterator.remove();
+ }
+
+ assertEquals(originalList, asList("zero", "two", "three"));
+ }
+
+ @Test
+ public void modifyingContentAndIteratingUsingListIteratorAPI() throws Exception {
+ List originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
+
+ ListIterator iterator = originalList.listIterator();
+
+ while (iterator.hasNext()) {
+ String next = iterator.next();
+ if (Objects.equals(next, "one")) {
+ iterator.set("another");
+ }
+
+ if (Objects.equals(next, "two")) {
+ iterator.remove();
+ }
+
+ if (Objects.equals(next, "three")) {
+ iterator.add("four");
+ }
+ }
+
+ assertEquals(originalList, asList("zero", "another", "three", "four"));
+ }
+
+ @Test
+ public void removingElementUsingCopyAndListAPI() throws Exception {
+ List originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
+
+ List listCopy = new ArrayList<>(originalList);
+
+ for (String next : listCopy) {
+ if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
+ }
+
+ assertEquals(originalList, asList("one", "two", "three"));
+ }
+
+ @Test
+ public void copyOnWriteList() throws Exception {
+ List originalList = new CopyOnWriteArrayList<>(asList("zero", "one", "two", "three"));
+
+ for (String next : originalList) {
+ if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
+ }
+
+ assertEquals(originalList, asList("one", "two", "three"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java b/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java
new file mode 100644
index 0000000000..bbc4e3e320
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java8/comparator/Employee.java
@@ -0,0 +1,23 @@
+package com.baeldung.java8.comparator;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+
+@Data
+@AllArgsConstructor
+@ToString
+@EqualsAndHashCode
+public class Employee implements Comparable{
+ String name;
+ int age;
+ double salary;
+ long mobile;
+
+
+ @Override
+ public int compareTo(Employee argEmployee) {
+ return name.compareTo(argEmployee.getName());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java
new file mode 100644
index 0000000000..ebcbb7a3fc
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java8/comparator/Java8ComparatorTest.java
@@ -0,0 +1,167 @@
+package com.baeldung.java8.comparator;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import lombok.Data;
+import static org.junit.Assert.assertTrue;
+
+public class Java8ComparatorTest {
+
+ private Employee[] employees;
+ private Employee[] employeesArrayWithNulls;
+ private Employee[] sortedEmployeesByName;
+ private Employee[] sortedEmployeesByNameDesc;
+ private Employee[] sortedEmployeesByAge;
+ private Employee[] sortedEmployeesByMobile;
+ private Employee[] sortedEmployeesBySalary;
+ private Employee[] sortedEmployeesArray_WithNullsFirst;
+ private Employee[] sortedEmployeesArray_WithNullsLast;
+ private Employee[] sortedEmployeesByNameAge;
+ private Employee[] someMoreEmployees;
+ private Employee[] sortedEmployeesByAgeName;;
+
+ @Before
+ public void initData() {
+ employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001),
+ new Employee("Keith", 35, 4000, 3924401) };
+ employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001),
+ null, new Employee("Keith", 35, 4000, 3924401) };
+
+ sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
+ new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
+ sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001),
+ new Employee("Ace", 22, 2000, 5924001) };
+
+ sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
+ new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
+
+ sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001),
+ new Employee("John", 25, 3000, 9922001), };
+
+ sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001),
+ new Employee("Keith", 35, 4000, 3924401), };
+
+ sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001),
+ new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
+ sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001),
+ new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
+
+ someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001),
+ new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
+
+ sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
+ new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
+ sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001),
+ new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
+ }
+
+ @Test
+ public void whenComparing_thenSortedByName() {
+ Comparator employeeNameComparator = Comparator.comparing(Employee::getName);
+ Arrays.sort(employees, employeeNameComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByName));
+ }
+
+ @Test
+ public void whenComparingWithComparator_thenSortedByNameDesc() {
+ Comparator employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
+ return s2.compareTo(s1);
+ });
+ Arrays.sort(employees, employeeNameComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
+ }
+
+ @Test
+ public void whenReversed_thenSortedByNameDesc() {
+ Comparator employeeNameComparator = Comparator.comparing(Employee::getName);
+ Comparator employeeNameComparatorReversed = employeeNameComparator.reversed();
+ Arrays.sort(employees, employeeNameComparatorReversed);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
+ }
+
+ @Test
+ public void whenComparingInt_thenSortedByAge() {
+ Comparator employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
+ Arrays.sort(employees, employeeAgeComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
+ }
+
+ @Test
+ public void whenComparingLong_thenSortedByMobile() {
+ Comparator employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
+ Arrays.sort(employees, employeeMobileComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
+ }
+
+ @Test
+ public void whenComparingDouble_thenSortedBySalary() {
+ Comparator employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
+ Arrays.sort(employees, employeeSalaryComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
+ }
+
+ @Test
+ public void whenNaturalOrder_thenSortedByName() {
+ Comparator employeeNameComparator = Comparator. naturalOrder();
+ Arrays.sort(employees, employeeNameComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByName));
+ }
+
+ @Test
+ public void whenReverseOrder_thenSortedByNameDesc() {
+ Comparator employeeNameComparator = Comparator. reverseOrder();
+ Arrays.sort(employees, employeeNameComparator);
+// System.out.println(Arrays.toString(employees));
+ assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
+ }
+
+ @Test
+ public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
+ Comparator employeeNameComparator = Comparator.comparing(Employee::getName);
+ Comparator employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
+ Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
+// System.out.println(Arrays.toString(employeesArrayWithNulls));
+ assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
+ }
+
+ @Test
+ public void whenNullsLast_thenSortedByNameWithNullsLast() {
+ Comparator employeeNameComparator = Comparator.comparing(Employee::getName);
+ Comparator employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
+ Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
+// System.out.println(Arrays.toString(employeesArrayWithNulls));
+ assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
+ }
+
+ @Test
+ public void whenThenComparing_thenSortedByAgeName() {
+ Comparator employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
+
+ Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
+// System.out.println(Arrays.toString(someMoreEmployees));
+ assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
+ }
+
+ @Test
+ public void whenThenComparing_thenSortedByNameAge() {
+ Comparator employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
+
+ Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
+// System.out.println(Arrays.toString(someMoreEmployees));
+ assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
+ }
+
+
+}
+
diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java
new file mode 100644
index 0000000000..fe0ec1469c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SortedTests.java
@@ -0,0 +1,22 @@
+package com.baeldung.junit4vstestng;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class SortedTests {
+
+ @Test
+ public void a_givenString_whenChangedtoInt_thenTrue() {
+ assertTrue(Integer.valueOf("10") instanceof Integer);
+ }
+
+ @Test
+ public void b_givenInt_whenChangedtoString_thenTrue() {
+ assertTrue(String.valueOf(10) instanceof String);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java
new file mode 100644
index 0000000000..93962e7831
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/list/flattennestedlist/FlattenNestedListTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.list.flattennestedlist;
+
+import static java.util.Arrays.asList;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.hamcrest.collection.IsIterableContainingInOrder;
+import org.junit.Test;
+
+public class FlattenNestedListTest {
+ List> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
+
+ @Test
+ public void givenNestedList_thenFlattenImperatively() {
+ List ls = flattenListOfListsImperatively(lol);
+
+ assertNotNull(ls);
+ assertTrue(ls.size() == 8);
+ // assert content
+ assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
+ }
+
+ @Test
+ public void givenNestedList_thenFlattenFunctionally() {
+ List ls = flattenListOfListsStream(lol);
+
+ assertNotNull(ls);
+ assertTrue(ls.size() == 8);
+ // assert content
+ assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
+ }
+
+ public List flattenListOfListsImperatively(List> list) {
+ List ls = new ArrayList<>();
+ list.forEach(ls::addAll);
+ return ls;
+ }
+
+ public List flattenListOfListsStream(List> list) {
+ return list.stream().flatMap(Collection::stream).collect(Collectors.toList());
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsTest.java b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsTest.java
index ce24ff24bc..674a2f89bc 100644
--- a/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsTest.java
+++ b/core-java/src/test/java/com/baeldung/list/listoflist/ListOfListsTest.java
@@ -39,7 +39,8 @@ public class ListOfListsTest {
@SuppressWarnings("unchecked")
@Test
public void givenListOfLists_whenRemovingElements_thenCheckNames() {
- ((ArrayList) listOfLists.get(1)).remove(0);
+
+ ((ArrayList) listOfLists.get(1)).remove(0);
listOfLists.remove(1);
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1)
.get(0)).getName());
@@ -47,4 +48,29 @@ public class ListOfListsTest {
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0)
.get(0)).getName());
}
+
+ @Test
+ public void givenThreeList_whenCombineIntoOneList_thenCheckList() {
+ ArrayList pens = new ArrayList<>();
+ pens.add(new Pen("Pen 1"));
+ pens.add(new Pen("Pen 2"));
+ ArrayList pencils = new ArrayList<>();
+ pencils.add(new Pencil("Pencil 1"));
+ pencils.add(new Pencil("Pencil 2"));
+ ArrayList rubbers = new ArrayList<>();
+ rubbers.add(new Rubber("Rubber 1"));
+ rubbers.add(new Rubber("Rubber 2"));
+
+ List> list = new ArrayList>();
+ list.add(pens);
+ list.add(pencils);
+ list.add(rubbers);
+
+ assertEquals("Pen 1", ((Pen) list.get(0)
+ .get(0)).getName());
+ assertEquals("Pencil 1", ((Pencil) list.get(1)
+ .get(0)).getName());
+ assertEquals("Rubber 1", ((Rubber) list.get(2)
+ .get(0)).getName());
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyTest.java
new file mode 100644
index 0000000000..140560d079
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyTest.java
@@ -0,0 +1,186 @@
+package com.baeldung.money;
+
+import org.javamoney.moneta.FastMoney;
+import org.javamoney.moneta.Money;
+import org.javamoney.moneta.format.CurrencyStyle;
+import org.junit.Test;
+
+import javax.money.CurrencyUnit;
+import javax.money.Monetary;
+import javax.money.MonetaryAmount;
+import javax.money.UnknownCurrencyException;
+import javax.money.convert.ConversionQueryBuilder;
+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.*;
+
+public class JavaMoneyTest {
+
+ @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");
+ fail(); // if no exception
+ }
+
+ @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 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
+ 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 ¤")
+ .build());
+ String customFormatted = customFormat.format(oneDollar);
+
+ assertNotNull(customFormat);
+ assertEquals("USD 1", oneDollar.toString());
+ assertEquals("00001.00 US Dollar", customFormatted);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/stringtokenizer/TokenizerTest.java b/core-java/src/test/java/com/baeldung/stringtokenizer/TokenizerTest.java
new file mode 100644
index 0000000000..eed42a2f96
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/stringtokenizer/TokenizerTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.stringtokenizer;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+public class TokenizerTest {
+
+ private final MyTokenizer myTokenizer = new MyTokenizer();
+ private final List expectedTokensForString = Arrays.asList("Welcome", "to", "baeldung.com");
+ private final List expectedTokensForFile = Arrays.asList("1", "IND", "India", "2", "MY", "Malaysia", "3", "AU", "Australia");
+
+ @Test
+ public void givenString_thenGetListOfString() {
+ String str = "Welcome,to,baeldung.com";
+ List actualTokens = myTokenizer.getTokens(str);
+ assertEquals(expectedTokensForString, actualTokens);
+ }
+
+ @Test
+ public void givenFile_thenGetListOfString() {
+ List actualTokens = myTokenizer.getTokensFromFile("data.csv", "|");
+ assertEquals(expectedTokensForFile, actualTokens);
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java
similarity index 98%
rename from core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java
rename to core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java
index 2c330c513d..2e38886271 100644
--- a/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/shell/JavaProcessUnitIntegrationTest.java
@@ -7,7 +7,7 @@ import java.io.*;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
-public class JavaProcessUnitTest {
+public class JavaProcessUnitIntegrationTest {
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
private static class StreamGobbler implements Runnable {
diff --git a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
similarity index 93%
rename from core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java
rename to core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
index c2eb1cff5d..42e85fc586 100644
--- a/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamTest.java
+++ b/core-java/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
@@ -1,38 +1,38 @@
-package org.baeldung.java.streams;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ForkJoinPool;
-import java.util.stream.Collectors;
-import java.util.stream.LongStream;
-import java.util.stream.Stream;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class ThreadPoolInParallelStreamTest {
-
- @Test
- public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
- long firstNum = 1;
- long lastNum = 1_000_000;
-
- List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
-
- ForkJoinPool customThreadPool = new ForkJoinPool(4);
- long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
-
- assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
- }
-
- @Test
- public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
- List aList = new ArrayList<>();
- Stream parallelStream = aList.parallelStream();
-
- assertTrue(parallelStream.isParallel());
- }
-}
+package org.baeldung.java.streams;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ForkJoinPool;
+import java.util.stream.Collectors;
+import java.util.stream.LongStream;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class ThreadPoolInParallelStreamIntegrationTest {
+
+ @Test
+ public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException {
+ long firstNum = 1;
+ long lastNum = 1_000_000;
+
+ List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList());
+
+ ForkJoinPool customThreadPool = new ForkJoinPool(4);
+ long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get();
+
+ assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
+ }
+
+ @Test
+ public void givenList_whenCallingParallelStream_shouldBeParallelStream() {
+ List aList = new ArrayList<>();
+ Stream parallelStream = aList.parallelStream();
+
+ assertTrue(parallelStream.isParallel());
+ }
+}
diff --git a/cucumber/pom.xml b/cucumber/pom.xml
new file mode 100644
index 0000000000..77d04f96c2
--- /dev/null
+++ b/cucumber/pom.xml
@@ -0,0 +1,93 @@
+
+ 4.0.0
+ com.baeldung
+ cucumber
+ 1.0.0-SNAPSHOT
+ jar
+
+
+ 1.8
+ 1.8
+ UTF-8
+ 3.5.1
+ 1.7.21
+ 1.1.7
+ 4.12
+ 1.3
+ 1.2.5
+ 2.19.1
+
+
+
+
+
+
+
+ info.cukes
+ cucumber-junit
+ ${cucumber.version}
+ test
+
+
+
+ info.cukes
+ cucumber-java
+ ${cucumber.version}
+ test
+
+
+
+ org.hamcrest
+ hamcrest-library
+ ${hamcrest.library.version}
+ test
+
+
+
+ org.slf4j
+ slf4j-api
+ ${slf4j.version}
+
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ ch.qos.logback
+ logback-core
+ ${logback.version}
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.plugin.version}
+
+ true
+ true
+ ${java.source.version}
+ ${java.target.version}
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${surefire.plugin.version}
+
+
+ **/CalculatorTest.java
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cucumber/src/main/java/com/baeldung/cucumber/calculator/Calculator.java b/cucumber/src/main/java/com/baeldung/cucumber/calculator/Calculator.java
new file mode 100644
index 0000000000..fd4a3bad7b
--- /dev/null
+++ b/cucumber/src/main/java/com/baeldung/cucumber/calculator/Calculator.java
@@ -0,0 +1,7 @@
+package com.baeldung.cucumber.calculator;
+
+public class Calculator {
+ public int add(int a, int b) {
+ return a + b;
+ }
+}
diff --git a/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorRunSteps.java b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorRunSteps.java
new file mode 100644
index 0000000000..9c0e920a8d
--- /dev/null
+++ b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorRunSteps.java
@@ -0,0 +1,38 @@
+package com.baeldung.cucumber.calculator;
+
+import org.hamcrest.Matchers;
+import org.junit.Assert;
+
+import cucumber.api.java.Before;
+import cucumber.api.java.en.Given;
+import cucumber.api.java.en.Then;
+import cucumber.api.java.en.When;
+
+public class CalculatorRunSteps {
+
+ private int total;
+
+ private Calculator calculator;
+
+ @Before
+ private void init() {
+ total = -999;
+
+ }
+
+ @Given("^I have a calculator$")
+ public void initializeCalculator() throws Throwable {
+ calculator = new Calculator();
+ }
+
+ @When("^I add (-?\\d+) and (-?\\d+)$")
+ public void testAdd(int num1, int num2) throws Throwable {
+ total = calculator.add(num1, num2);
+ }
+
+ @Then("^the result should be (-?\\d+)$")
+ public void validateResult(int result) throws Throwable {
+ Assert.assertThat(total, Matchers.equalTo(result));
+ }
+
+}
diff --git a/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java
new file mode 100644
index 0000000000..6bbbca60d2
--- /dev/null
+++ b/cucumber/src/test/java/com/baeldung/cucumber/calculator/CalculatorTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.cucumber.calculator;
+
+import org.junit.runner.RunWith;
+
+import cucumber.api.CucumberOptions;
+import cucumber.api.junit.Cucumber;
+
+@RunWith(Cucumber.class)
+@CucumberOptions(
+ features={"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"}
+ , plugin = { "pretty", "json:target/reports/json/calculator.json" }
+ , glue = {"com.baeldung.cucumber.calculator"}
+)
+public class CalculatorTest {
+}
diff --git a/cucumber/src/test/resources/features/calculator-scenario-outline.feature b/cucumber/src/test/resources/features/calculator-scenario-outline.feature
new file mode 100644
index 0000000000..7437dbf5f9
--- /dev/null
+++ b/cucumber/src/test/resources/features/calculator-scenario-outline.feature
@@ -0,0 +1,16 @@
+Feature: Calculator
+ As a user
+ I want to use a calculator to add numbers
+ So that I don't need to add myself
+
+ Scenario Outline: Add two numbers &
+ Given I have a calculator
+ When I add and
+ Then the result should be
+
+ Examples:
+ | num1 | num2 | total |
+ | -2 | 3 | 1 |
+ | 10 | 15 | 25 |
+ | 99 | -99 | 0 |
+ | -1 | -10 | -11 |
\ No newline at end of file
diff --git a/cucumber/src/test/resources/features/calculator.feature b/cucumber/src/test/resources/features/calculator.feature
new file mode 100644
index 0000000000..eaf05cb6ca
--- /dev/null
+++ b/cucumber/src/test/resources/features/calculator.feature
@@ -0,0 +1,24 @@
+Feature: Calculator
+ As a user
+ I want to use a calculator to add numbers
+ So that I don't need to add myself
+
+ Scenario: Add two numbers -2 & 3
+ Given I have a calculator
+ When I add -2 and 3
+ Then the result should be 1
+
+ Scenario: Add two numbers 10 & 15
+ Given I have a calculator
+ When I add 10 and 15
+ Then the result should be 25
+
+ Scenario: Add two numbers 99 & -99
+ Given I have a calculator
+ When I add 99 and -99
+ Then the result should be 0
+
+ Scenario: Add two numbers -1 & -10
+ Given I have a calculator
+ When I add -1 and -10
+ Then the result should be -11
\ No newline at end of file
diff --git a/cucumber/src/test/resources/logback-test.xml b/cucumber/src/test/resources/logback-test.xml
new file mode 100644
index 0000000000..e980d88693
--- /dev/null
+++ b/cucumber/src/test/resources/logback-test.xml
@@ -0,0 +1,13 @@
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n%ex
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 7f2c78c9b0..2523cc2125 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -145,6 +145,7 @@
single
+ ${project.basedir}
org.baeldung.executable.ExecutableMavenJar
diff --git a/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events b/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events
new file mode 100644
index 0000000000..d3ce8b9cea
Binary files /dev/null and b/events/MessagesAggregate/0638124c-9a1b-4d25-8fce-cc223d472e77.events differ
diff --git a/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events b/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events
new file mode 100644
index 0000000000..2ab0ec469f
Binary files /dev/null and b/events/MessagesAggregate/d2ba9cbe-1a44-428e-a710-13b1bdc67c4b.events differ
diff --git a/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events b/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events
new file mode 100644
index 0000000000..d805fc253e
Binary files /dev/null and b/events/ToDoItem/bf420ffc-0c3b-403e-bb8c-66cf499c773e.events differ
diff --git a/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events b/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events
new file mode 100644
index 0000000000..3d67b74ced
Binary files /dev/null and b/events/ToDoItem/e72a057b-adea-4c69-83a0-0431318823e7.events differ
diff --git a/groovy-spock/pom.xml b/groovy-spock/pom.xml
new file mode 100644
index 0000000000..be84500b0d
--- /dev/null
+++ b/groovy-spock/pom.xml
@@ -0,0 +1,47 @@
+
+
+ 4.0.0
+ org.spockframework
+ groovy-spock
+ 1.0-SNAPSHOT
+ jar
+ Spock Framework - Example Project
+
+
+ UTF-8
+ UTF-8
+
+
+
+
+
+ org.codehaus.gmavenplus
+ gmavenplus-plugin
+ 1.5
+
+
+
+ compile
+ testCompile
+
+
+
+
+
+
+
+
+
+ org.spockframework
+ spock-core
+ 1.0-groovy-2.4
+ test
+
+
+ org.codehaus.groovy
+ groovy-all
+ 2.4.7
+
+
+
\ No newline at end of file
diff --git a/groovy-spock/src/test/groovy/FirstSpecification.groovy b/groovy-spock/src/test/groovy/FirstSpecification.groovy
new file mode 100644
index 0000000000..ed228899a2
--- /dev/null
+++ b/groovy-spock/src/test/groovy/FirstSpecification.groovy
@@ -0,0 +1,89 @@
+import spock.lang.Specification
+
+class FirstSpecification extends Specification {
+
+ def "one plus one should equal two"() {
+ expect:
+ 1 + 1 == 2
+ }
+
+ def "two plus two should equal four"() {
+ given:
+ int left = 2
+ int right = 2
+
+ when:
+ int result = left + right
+
+ then:
+ result == 4
+ }
+
+ def "Should be able to remove from list"() {
+ given:
+ def list = [1, 2, 3, 4]
+
+ when:
+ list.remove(0)
+
+ then:
+ list == [2, 3, 4]
+ }
+
+ def "Should get an index out of bounds when removing a non-existent item"() {
+ given:
+ def list = [1, 2, 3, 4]
+
+ when:
+ list.remove(20)
+
+ then:
+ thrown(IndexOutOfBoundsException)
+ list.size() == 4
+ }
+
+ def "numbers to the power of two"(int a, int b, int c) {
+ expect:
+ Math.pow(a, b) == c
+
+ where:
+ a | b | c
+ 1 | 2 | 1
+ 2 | 2 | 4
+ 3 | 2 | 9
+ }
+
+ def "Should return default value for mock"() {
+ given:
+ def paymentGateway = Mock(PaymentGateway)
+
+ when:
+ def result = paymentGateway.makePayment(12.99)
+
+ then:
+ !result
+ }
+
+ def "Should return true value for mock"() {
+ given:
+ def paymentGateway = Mock(PaymentGateway)
+ paymentGateway.makePayment(20) >> true
+
+ when:
+ def result = paymentGateway.makePayment(20)
+
+ then:
+ result
+ }
+
+ def "Should verify notify was called"() {
+ given:
+ def notifier = Mock(Notifier)
+
+ when:
+ notifier.notify('foo')
+
+ then:
+ 1 * notifier.notify('foo')
+ }
+}
diff --git a/groovy-spock/src/test/groovy/Notifier.groovy b/groovy-spock/src/test/groovy/Notifier.groovy
new file mode 100644
index 0000000000..d92d0f86ef
--- /dev/null
+++ b/groovy-spock/src/test/groovy/Notifier.groovy
@@ -0,0 +1,3 @@
+interface Notifier {
+ void notify(String message)
+}
\ No newline at end of file
diff --git a/groovy-spock/src/test/groovy/PaymentGateway.groovy b/groovy-spock/src/test/groovy/PaymentGateway.groovy
new file mode 100644
index 0000000000..2a66e050f9
--- /dev/null
+++ b/groovy-spock/src/test/groovy/PaymentGateway.groovy
@@ -0,0 +1,3 @@
+interface PaymentGateway {
+ boolean makePayment(BigDecimal amount)
+}
\ No newline at end of file
diff --git a/guava/README.md b/guava/README.md
index ee224bae5f..f46c4dd3de 100644
--- a/guava/README.md
+++ b/guava/README.md
@@ -24,3 +24,4 @@
- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset)
- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap)
- [Guide to Guava Table](http://www.baeldung.com/guava-table)
+- [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection)
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMathTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMathTest.java
new file mode 100644
index 0000000000..b8e13f0650
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMathTest.java
@@ -0,0 +1,220 @@
+package org.baeldung.guava;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.*;
+
+import java.math.BigInteger;
+import java.math.RoundingMode;
+
+import org.junit.Test;
+
+import com.google.common.math.DoubleMath;
+import com.google.common.math.IntMath;
+
+public class GuavaMathTest {
+ @Test(expected = ArithmeticException.class)
+ public void whenSumOverflow_thenThrowException() {
+ IntMath.checkedAdd(Integer.MAX_VALUE, 1);
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenSumUnderflow_thenThrowException() {
+ IntMath.checkedAdd(Integer.MIN_VALUE, -1);
+ }
+
+ @Test
+ public void should_calculate_sum() {
+ int result = IntMath.checkedAdd(2, 1);
+ assertThat(result, equalTo(3));
+ }
+
+ @Test
+ public void whenSumOverflow_thenReturnMaxInteger() {
+ int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
+ assertThat(result, equalTo(Integer.MAX_VALUE));
+ }
+
+ @Test
+ public void whenSumUnderflow_thenReturnMinInteger() {
+ int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
+ assertThat(result, equalTo(Integer.MIN_VALUE));
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenDifferenceOverflow_thenThrowException() {
+ IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenDifferenceUnderflow_thenThrowException() {
+ IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
+ }
+
+ @Test
+ public void should_calculate_difference() {
+ int result = IntMath.checkedSubtract(200, 100);
+ assertThat(result, equalTo(100));
+ }
+
+ @Test
+ public void whenDifferenceOverflow_thenReturnMaxInteger() {
+ int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
+ assertThat(result, equalTo(Integer.MAX_VALUE));
+ }
+
+ @Test
+ public void whenDifferenceUnderflow_thenReturnMinInteger() {
+ int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
+ assertThat(result, equalTo(Integer.MIN_VALUE));
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenProductOverflow_thenThrowException() {
+ IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenProductUnderflow_thenThrowException() {
+ IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
+ }
+
+ @Test
+ public void should_calculate_product() {
+ int result = IntMath.checkedMultiply(21, 3);
+ assertThat(result, equalTo(63));
+ }
+
+ @Test
+ public void whenProductOverflow_thenReturnMaxInteger() {
+ int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
+ assertThat(result, equalTo(Integer.MAX_VALUE));
+ }
+
+ @Test
+ public void whenProductUnderflow_thenReturnMinInteger() {
+ int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
+ assertThat(result, equalTo(Integer.MIN_VALUE));
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenPowerOverflow_thenThrowException() {
+ IntMath.checkedPow(Integer.MAX_VALUE, 2);
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenPowerUnderflow_thenThrowException() {
+ IntMath.checkedPow(Integer.MIN_VALUE, 3);
+ }
+
+ @Test
+ public void should_calculate_power() {
+ int result = IntMath.saturatedPow(3, 3);
+ assertThat(result, equalTo(27));
+ }
+
+ @Test
+ public void whenPowerOverflow_thenReturnMaxInteger() {
+ int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
+ assertThat(result, equalTo(Integer.MAX_VALUE));
+ }
+
+ @Test
+ public void whenPowerUnderflow_thenReturnMinInteger() {
+ int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
+ assertThat(result, equalTo(Integer.MIN_VALUE));
+ }
+
+ @Test
+ public void should_round_divide_result() {
+ int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
+ assertThat(result1, equalTo(1));
+
+ int result2 = IntMath.divide(3, 2, RoundingMode.UP);
+ assertThat(result2, equalTo(2));
+ }
+
+ @Test
+ public void should_round_log2_result() {
+ int result1 = IntMath.log2(5, RoundingMode.FLOOR);
+ assertThat(result1, equalTo(2));
+
+ int result2 = IntMath.log2(5, RoundingMode.CEILING);
+ assertThat(result2, equalTo(3));
+ }
+
+ @Test
+ public void should_round_log10_result() {
+ int result = IntMath.log10(11, RoundingMode.HALF_UP);
+ assertThat(result, equalTo(1));
+ }
+
+ @Test
+ public void should_round_sqrt_result() {
+ int result = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
+ assertThat(result, equalTo(2));
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenNeedRounding_thenThrowException() {
+ IntMath.sqrt(5, RoundingMode.UNNECESSARY);
+ }
+
+ @Test
+ public void should_calculate_gcd() {
+ int result = IntMath.gcd(15, 20);
+ assertThat(result, equalTo(5));
+ }
+
+ @Test
+ public void should_calculate_mod() {
+ int result = IntMath.mod(8, 3);
+ assertThat(result, equalTo(2));
+ }
+
+ @Test
+ public void should_test_if_is_power_of_two() {
+ boolean result1 = IntMath.isPowerOfTwo(8);
+ assertTrue(result1);
+
+ boolean result2 = IntMath.isPowerOfTwo(9);
+ assertFalse(result2);
+ }
+
+ @Test
+ public void should_calculate_factorial() {
+ int result = IntMath.factorial(4);
+ assertThat(result, equalTo(24));
+ }
+
+ @Test
+ public void should_calculate_binomial() {
+ int result = IntMath.binomial(7, 3);
+ assertThat(result, equalTo(35));
+ }
+
+ @Test
+ public void should_detect_integer() {
+ boolean result1 = DoubleMath.isMathematicalInteger(2.0);
+ assertThat(result1, equalTo(true));
+ boolean result2 = DoubleMath.isMathematicalInteger(2.1);
+ assertThat(result2, equalTo(false));
+ }
+
+ @Test
+ public void should_round_to_integer_types() {
+ int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
+ assertThat(result3, equalTo(2));
+
+ long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
+ assertThat(result4, equalTo(3L));
+
+ BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
+ assertThat(result5, equalTo(new BigInteger("3")));
+ }
+
+ @Test
+ public void should_calculate_log_2() {
+ int result6 = DoubleMath.log2(10, RoundingMode.UP);
+ assertThat(result6, equalTo(4));
+ }
+}
\ No newline at end of file
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaReflectionUtilsTest.java b/guava/src/test/java/org/baeldung/guava/GuavaReflectionUtilsTest.java
new file mode 100644
index 0000000000..e59a682e08
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaReflectionUtilsTest.java
@@ -0,0 +1,150 @@
+package org.baeldung.guava;
+
+
+import com.google.common.collect.Lists;
+import com.google.common.reflect.Invokable;
+import com.google.common.reflect.TypeToken;
+import org.junit.Test;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+
+import static junit.framework.TestCase.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class GuavaReflectionUtilsTest {
+
+ @Test
+ public void givenTwoGenericList_whenCheckIsAssignableFrom_thenReturnTrueDueToTypeErasure() {
+ //given
+ ArrayList stringList = Lists.newArrayList();
+ ArrayList intList = Lists.newArrayList();
+
+ //when
+ boolean result = stringList.getClass().isAssignableFrom(intList.getClass());
+
+ //then
+ assertTrue(result);
+ }
+
+ @Test
+ public void givenTypeToken_whenResolveType_thenShouldResolveProperType() {
+ //given
+ TypeToken> stringListToken = new TypeToken>() {
+ };
+ TypeToken> integerListToken = new TypeToken>() {
+ };
+ TypeToken> numberTypeToken = new TypeToken>() {
+ };
+
+ //then
+ assertFalse(stringListToken.isSubtypeOf(integerListToken));
+ assertFalse(numberTypeToken.isSubtypeOf(integerListToken));
+ assertTrue(integerListToken.isSubtypeOf(numberTypeToken));
+ }
+
+ @Test
+ public void givenCustomClass_whenCaptureGeneric_thenReturnTypeAtRuntime() {
+ //given
+ ParametrizedClass parametrizedClass = new ParametrizedClass() {
+ };
+
+ //then
+ assertEquals(parametrizedClass.type, TypeToken.of(String.class));
+ }
+
+ @Test
+ public void givenComplexType_whenGetTypeArgument_thenShouldReturnTypeAtRuntime() {
+ //given
+ TypeToken> funToken = new TypeToken>() {
+ };
+
+ //when
+ TypeToken> funResultToken = funToken.resolveType(Function.class.getTypeParameters()[1]);
+
+ //then
+ assertEquals(funResultToken, TypeToken.of(String.class));
+ }
+
+
+ @Test
+ public void givenMapType_whenGetTypeArgumentOfEntry_thenShouldReturnTypeAtRuntime() throws NoSuchMethodException {
+ //given
+ TypeToken