diff --git a/.gitignore b/.gitignore
index 784627b616..60c38ed8f5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+*/bin/*
+
*.class
# Package Files #
@@ -29,3 +31,5 @@ spring-openid/src/main/resources/application.properties
.recommenders/
/spring-hibernate4/nbproject/
spring-security-openid/src/main/resources/application.properties
+
+spring-all/*.log
diff --git a/.travis.yml b/.travis.yml
index c2a369a1b3..502c234c72 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,11 +1,19 @@
language: java
-install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
+before_install:
+ - export MAVEN_OPTS="-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit"
+ - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
+
+install: travis_wait 60 mvn -q test -fae
+
+sudo: required
+
+before_script:
+ - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
jdk:
- oraclejdk8
-sudo: false
addons:
apt:
packages:
@@ -14,4 +22,6 @@ addons:
cache:
directories:
- .autoconf
- - $HOME/.m2
\ No newline at end of file
+ - $HOME/.m2
+
+
diff --git a/JGit/pom.xml b/JGit/pom.xml
index 93c49edb92..6d505afcf3 100644
--- a/JGit/pom.xml
+++ b/JGit/pom.xml
@@ -6,6 +6,13 @@
1.0-SNAPSHOT
jar
http://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
UTF-8
1.8
@@ -40,24 +47,5 @@
slf4j-simple
1.7.21
-
- junit
- junit
- 4.12
- test
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.2
-
- 1.7
- 1.7
-
-
-
-
\ No newline at end of file
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
new file mode 100644
index 0000000000..ed7168b2c2
--- /dev/null
+++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
@@ -0,0 +1,31 @@
+import com.baeldung.jgit.helper.Helper;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.ObjectReader;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.junit.Test;
+import java.io.IOException;
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * Tests which show issues with JGit that we reported upstream.
+ */
+public class JGitBugIntegrationTest {
+ @Test
+ public void testRevWalkDisposeClosesReader() throws IOException {
+ try (Repository repo = Helper.openJGitRepository()) {
+ try (ObjectReader reader = repo.newObjectReader()) {
+ try (RevWalk walk = new RevWalk(reader)) {
+ walk.dispose();
+
+ Ref head = repo.exactRef("refs/heads/master");
+ System.out.println("Found head: " + head);
+
+ ObjectLoader loader = reader.open(head.getObjectId());
+ assertNotNull(loader);
+ }
+ }
+ }
+ }
+}
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
deleted file mode 100644
index acad4e395f..0000000000
--- a/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-import com.baeldung.jgit.helper.Helper;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.lib.ObjectReader;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.junit.Test;
-import java.io.IOException;
-import static org.junit.Assert.assertNotNull;
-
-/**
- * Tests which show issues with JGit that we reported upstream.
- */
-public class JGitBugTest {
- @Test
- public void testRevWalkDisposeClosesReader() throws IOException {
- try (Repository repo = Helper.openJGitRepository()) {
- try (ObjectReader reader = repo.newObjectReader()) {
- try (RevWalk walk = new RevWalk(reader)) {
- walk.dispose();
-
- Ref head = repo.exactRef("refs/heads/master");
- System.out.println("Found head: " + head);
-
- ObjectLoader loader = reader.open(head.getObjectId());
- assertNotNull(loader);
- }
- }
- }
- }
-}
diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java
deleted file mode 100644
index ce3a41e657..0000000000
--- a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.baeldung.jgit.porcelain;
-
-import org.junit.Test;
-
-public class PorcelainTest {
- @Test
- public void runSamples() throws Exception {
- // simply call all the samples to see any severe problems with the samples
- AddFile.main(null);
-
- CommitAll.main(null);
-
- CreateAndDeleteTag.main(null);
-
- Log.main(null);
- }
-}
diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
new file mode 100644
index 0000000000..d3b3358664
--- /dev/null
+++ b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.jgit.porcelain;
+
+import org.junit.Test;
+
+public class PorcelainUnitTest {
+ @Test
+ public void runSamples() throws Exception {
+ // simply call all the samples to see any severe problems with the samples
+ AddFile.main(null);
+
+ CommitAll.main(null);
+
+ CreateAndDeleteTag.main(null);
+
+ Log.main(null);
+ }
+}
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..ae0efb487f
--- /dev/null
+++ b/Twitter4J/pom.xml
@@ -0,0 +1,52 @@
+
+ 4.0.0
+ com.mabsisa
+ Twitter4J
+ jar
+ 1.0-SNAPSHOT
+ Twitter4J
+ http://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+ org.twitter4j
+ twitter4j-stream
+ 4.0.6
+
+
+
+
+ ${project.artifactId}
+
+
+ src/main/resources
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/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/ApplicationIntegrationTest.java b/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java
new file mode 100644
index 0000000000..4696283faa
--- /dev/null
+++ b/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.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 ApplicationIntegrationTest {
+
+ /**
+ * 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..f1e12ee243 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -2,3 +2,7 @@
- [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)
+- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
diff --git a/algorithms/pom.xml b/algorithms/pom.xml
index f72457650a..967bcbc706 100644
--- a/algorithms/pom.xml
+++ b/algorithms/pom.xml
@@ -1,63 +1,69 @@
- 4.0.0
- com.baeldung
- algorithms
- 0.0.1-SNAPSHOT
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ algorithms
+ 0.0.1-SNAPSHOT
-
- 4.12
- 3.6.0
- 1.5.0
-
+
+ 1.5.0
+ 1.16.12
+ 3.6.1
+
-
-
- junit
- junit
- ${junit.version}
- test
-
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
- install
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
- ${exec-maven-plugin.version}
-
-
-
-
-
-
-
- org.codehaus.mojo
- cobertura-maven-plugin
- 2.7
-
-
-
- com/baeldung/algorithms/dijkstra/*
-
-
- com/baeldung/algorithms/dijkstra/*
-
-
-
-
-
-
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+ io.jenetics
+ jenetics
+ 3.7.0
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ cobertura-maven-plugin
+ 2.7
+
+
+
+ com/baeldung/algorithms/dijkstra/*
+
+
+ com/baeldung/algorithms/dijkstra/*
+
+
+
+
+
+
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
new file mode 100644
index 0000000000..6ab7dbb4e5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -0,0 +1,47 @@
+package com.baeldung.algorithms;
+
+import java.util.Scanner;
+
+import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
+import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
+import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
+import com.baeldung.algorithms.slope_one.SlopeOne;
+
+public class RunAlgorithm {
+
+ 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:
+ System.out.println(
+ "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
+ break;
+ case 2:
+ SlopeOne.slopeOne(3);
+ break;
+ case 3:
+ SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
+ ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
+ break;
+ case 4:
+ 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;
+ }
+ in.close();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
similarity index 90%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/City.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
index 77e8652df0..cb5647f4d2 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
import lombok.Data;
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
similarity index 96%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
index a7dc974e97..bff64fc239 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
public class SimulatedAnnealing {
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
similarity index 97%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
index 9bf341fbbe..3139b49586 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
import java.util.ArrayList;
import java.util.Collections;
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
new file mode 100644
index 0000000000..4ea23b799f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
@@ -0,0 +1,37 @@
+package com.baeldung.algorithms.ga.ant_colony;
+
+public class Ant {
+
+ protected int trailSize;
+ protected int trail[];
+ protected boolean visited[];
+
+ public Ant(int tourSize) {
+ this.trailSize = tourSize;
+ this.trail = new int[tourSize];
+ this.visited = new boolean[tourSize];
+ }
+
+ protected void visitCity(int currentIndex, int city) {
+ trail[currentIndex + 1] = city;
+ visited[city] = true;
+ }
+
+ protected boolean visited(int i) {
+ return visited[i];
+ }
+
+ protected double trailLength(double graph[][]) {
+ double length = graph[trail[trailSize - 1]][trail[0]];
+ for (int i = 0; i < trailSize - 1; i++) {
+ length += graph[trail[i]][trail[i + 1]];
+ }
+ return length;
+ }
+
+ protected void clear() {
+ for (int i = 0; i < trailSize; i++)
+ visited[i] = false;
+ }
+
+}
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/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
new file mode 100644
index 0000000000..b0218ae23e
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
@@ -0,0 +1,22 @@
+package algorithms;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
+
+public class AntColonyOptimizationLongRunningUnitTest {
+
+ @Test
+ public void testGenerateRandomMatrix() {
+ AntColonyOptimization antTSP = new AntColonyOptimization(5);
+ Assert.assertNotNull(antTSP.generateRandomMatrix(5));
+ }
+
+ @Test
+ public void testStartAntOptimization() {
+ AntColonyOptimization antTSP = new AntColonyOptimization(5);
+ Assert.assertNotNull(antTSP.solve());
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
new file mode 100644
index 0000000000..fa8ecdee77
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
@@ -0,0 +1,16 @@
+package algorithms;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
+
+public class BinaryGeneticAlgorithmLongRunningUnitTest {
+
+ @Test
+ public void testGA() {
+ SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
+ Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
new file mode 100644
index 0000000000..68386278fc
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
@@ -0,0 +1,86 @@
+package algorithms;
+
+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;
+
+import static org.junit.Assert.assertTrue;
+
+public class DijkstraAlgorithmLongRunningUnitTest {
+
+ @Test
+ public void whenSPPSolved_thenCorrect() {
+
+ Node nodeA = new Node("A");
+ Node nodeB = new Node("B");
+ Node nodeC = new Node("C");
+ Node nodeD = new Node("D");
+ Node nodeE = new Node("E");
+ Node nodeF = new Node("F");
+
+ nodeA.addDestination(nodeB, 10);
+ nodeA.addDestination(nodeC, 15);
+
+ nodeB.addDestination(nodeD, 12);
+ nodeB.addDestination(nodeF, 15);
+
+ nodeC.addDestination(nodeE, 10);
+
+ nodeD.addDestination(nodeE, 2);
+ nodeD.addDestination(nodeF, 1);
+
+ nodeF.addDestination(nodeE, 5);
+
+ Graph graph = new Graph();
+
+ graph.addNode(nodeA);
+ graph.addNode(nodeB);
+ graph.addNode(nodeC);
+ graph.addNode(nodeD);
+ graph.addNode(nodeE);
+ graph.addNode(nodeF);
+
+ graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
+
+ List shortestPathForNodeB = Arrays.asList(nodeA);
+ List shortestPathForNodeC = Arrays.asList(nodeA);
+ List shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
+ List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
+ List shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
+
+ for (Node node : graph.getNodes()) {
+ switch (node.getName()) {
+ case "B":
+ assertTrue(node
+ .getShortestPath()
+ .equals(shortestPathForNodeB));
+ break;
+ case "C":
+ assertTrue(node
+ .getShortestPath()
+ .equals(shortestPathForNodeC));
+ break;
+ case "D":
+ assertTrue(node
+ .getShortestPath()
+ .equals(shortestPathForNodeD));
+ break;
+ case "E":
+ assertTrue(node
+ .getShortestPath()
+ .equals(shortestPathForNodeE));
+ break;
+ case "F":
+ assertTrue(node
+ .getShortestPath()
+ .equals(shortestPathForNodeF));
+ break;
+ }
+ }
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
deleted file mode 100644
index 07606bde4b..0000000000
--- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-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 java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertTrue;
-
-public class DijkstraAlgorithmTest {
-
- @Test
- public void whenSPPSolved_thenCorrect() {
-
- Node nodeA = new Node("A");
- Node nodeB = new Node("B");
- Node nodeC = new Node("C");
- Node nodeD = new Node("D");
- Node nodeE = new Node("E");
- Node nodeF = new Node("F");
-
- nodeA.addDestination(nodeB, 10);
- nodeA.addDestination(nodeC, 15);
-
- nodeB.addDestination(nodeD, 12);
- nodeB.addDestination(nodeF, 15);
-
- nodeC.addDestination(nodeE, 10);
-
- nodeD.addDestination(nodeE, 2);
- nodeD.addDestination(nodeF, 1);
-
- nodeF.addDestination(nodeE, 5);
-
- Graph graph = new Graph();
-
- graph.addNode(nodeA);
- graph.addNode(nodeB);
- graph.addNode(nodeC);
- graph.addNode(nodeD);
- graph.addNode(nodeE);
- graph.addNode(nodeF);
-
- graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
-
- List shortestPathForNodeB = Arrays.asList(nodeA);
- List shortestPathForNodeC = Arrays.asList(nodeA);
- List shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
- List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
- List shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
-
- for (Node node : graph.getNodes()) {
- switch (node.getName()) {
- case "B":
- assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
- break;
- case "C":
- assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
- break;
- case "D":
- assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
- break;
- case "E":
- assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
- break;
- case "F":
- assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
- break;
- }
- }
- }
-}
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
new file mode 100644
index 0000000000..c6800e9a64
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -0,0 +1,73 @@
+package algorithms;
+
+import com.baeldung.automata.*;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+
+public final class RtFiniteStateMachineLongRunningUnitTest {
+
+ @Test
+ public void acceptsSimplePair() {
+ String json = "{\"key\":\"value\"}";
+ FiniteStateMachine machine = this.buildJsonStateMachine();
+ for (int i = 0; i < json.length(); i++) {
+ machine = machine.switchState(String.valueOf(json.charAt(i)));
+ }
+ assertTrue(machine.canStop());
+ }
+
+ @Test
+ public void acceptsMorePairs() {
+ String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
+ FiniteStateMachine machine = this.buildJsonStateMachine();
+ for (int i = 0; i < json.length(); i++) {
+ machine = machine.switchState(String.valueOf(json.charAt(i)));
+ }
+ assertTrue(machine.canStop());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void missingColon() {
+ String json = "{\"key\"\"value\"}";
+ FiniteStateMachine machine = this.buildJsonStateMachine();
+ for (int i = 0; i < json.length(); i++) {
+ machine = machine.switchState(String.valueOf(json.charAt(i)));
+ }
+ }
+
+ /**
+ * Builds a finite state machine to validate a simple
+ * Json object.
+ * @return
+ */
+ private FiniteStateMachine buildJsonStateMachine() {
+ State first = new RtState();
+ State second = new RtState();
+ State third = new RtState();
+ State fourth = new RtState();
+ State fifth = new RtState();
+ State sixth = new RtState();
+ State seventh = new RtState();
+ State eighth = new RtState(true);
+
+ first.with(new RtTransition("{", second));
+ second.with(new RtTransition("\"", third));
+ //Add transitions with chars 0-9 and a-z
+ for (int i = 0; i < 26; i++) {
+ if (i < 10) {
+ third = third.with(new RtTransition(String.valueOf(i), third));
+ sixth = sixth.with(new RtTransition(String.valueOf(i), sixth));
+ }
+ third = third.with(new RtTransition(String.valueOf((char) ('a' + i)), third));
+ sixth = sixth.with(new RtTransition(String.valueOf((char) ('a' + i)), sixth));
+ }
+ third.with(new RtTransition("\"", fourth));
+ fourth.with(new RtTransition(":", fifth));
+ fifth.with(new RtTransition("\"", sixth));
+ sixth.with(new RtTransition("\"", seventh));
+ seventh.with(new RtTransition(",", second));
+ seventh.with(new RtTransition("}", eighth));
+ return new RtFiniteStateMachine(first);
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
new file mode 100644
index 0000000000..6ee129ece9
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
@@ -0,0 +1,15 @@
+package algorithms;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
+
+public class SimulatedAnnealingLongRunningUnitTest {
+
+ @Test
+ public void testSimulateAnnealing() {
+ Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
+ }
+
+}
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java
new file mode 100644
index 0000000000..9203131397
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java
@@ -0,0 +1,69 @@
+package com.baeldung.algorithms.primechecker;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class PrimeCheckerUnitTest {
+
+ private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
+
+ @Test
+ public void whenCheckIsPrime_thenTrue(){
+ assertTrue(primeChecker.isPrime(13l));
+ assertTrue(primeChecker.isPrime(1009L));
+ assertTrue(primeChecker.isPrime(74207281L));
+ }
+
+ @Test
+ public void whenCheckIsPrime_thenFalse(){
+ assertTrue(!primeChecker.isPrime(50L));
+ assertTrue(!primeChecker.isPrime(1001L));
+ assertTrue(!primeChecker.isPrime(74207282L));
+ }
+
+ private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
+
+ @Test
+ public void whenBFCheckIsPrime_thenTrue(){
+ assertTrue(bfPrimeChecker.isPrime(13));
+ assertTrue(bfPrimeChecker.isPrime(1009));
+ }
+
+ @Test
+ public void whenBFCheckIsPrime_thenFalse(){
+ assertFalse(bfPrimeChecker.isPrime(50));
+ assertFalse(bfPrimeChecker.isPrime(1001));
+ }
+
+
+ private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker();
+
+ @Test
+ public void whenOptCheckIsPrime_thenTrue(){
+ assertTrue(optimisedPrimeChecker.isPrime(13));
+ assertTrue(optimisedPrimeChecker.isPrime(1009));
+ }
+
+ @Test
+ public void whenOptCheckIsPrime_thenFalse(){
+ assertFalse(optimisedPrimeChecker.isPrime(50));
+ assertFalse(optimisedPrimeChecker.isPrime(1001));
+ }
+
+ private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker();
+
+ @Test
+ public void whenPrimesCheckIsPrime_thenTrue() {
+ assertTrue(primesPrimeChecker.isPrime(13));
+ assertTrue(primesPrimeChecker.isPrime(1009));
+ }
+
+ @Test
+ public void whenPrimesCheckIsPrime_thenFalse() {
+ assertFalse(primesPrimeChecker.isPrime(50));
+ assertFalse(primesPrimeChecker.isPrime(1001));
+ }
+
+}
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index e88e441b3e..df6f9d44b7 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -1,7 +1,7 @@
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml
index a365f35c11..eb827b2ea5 100644
--- a/annotations/annotation-user/pom.xml
+++ b/annotations/annotation-user/pom.xml
@@ -1,7 +1,6 @@
-
+
4.0.0
@@ -13,11 +12,6 @@
annotation-user
-
- 4.12
- 3.6.0
-
-
@@ -26,31 +20,6 @@
${project.parent.version}
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
deleted file mode 100644
index 8d01f8a517..0000000000
--- a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.annotation;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class PersonBuilderTest {
-
- @Test
- public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
-
- Person person = new PersonBuilder().setAge(25).setName("John").build();
-
- assertEquals(25, person.getAge());
- assertEquals("John", person.getName());
-
- }
-
-}
diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java
new file mode 100644
index 0000000000..d5f758089a
--- /dev/null
+++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.annotation;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class PersonBuilderUnitTest {
+
+ @Test
+ public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
+
+ Person person = new PersonBuilder().setAge(25).setName("John").build();
+
+ assertEquals(25, person.getAge());
+ assertEquals("John", person.getName());
+
+ }
+
+}
diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml
index 5d556af56f..1cc0a33702 100644
--- a/apache-bval/pom.xml
+++ b/apache-bval/pom.xml
@@ -5,6 +5,11 @@
apache-bval
0.0.1-SNAPSHOT
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
org.apache.bval
@@ -21,31 +26,9 @@
bval-extras
${bval.version}
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
- 3.6.0
- 4.12
1.1.2
\ No newline at end of file
diff --git a/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java b/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java
new file mode 100644
index 0000000000..ecbcd100da
--- /dev/null
+++ b/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java
@@ -0,0 +1,97 @@
+package com.baeldung.validation;
+
+import java.io.File;
+import java.util.Set;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+
+import org.apache.bval.jsr.ApacheValidationProvider;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+import com.baeldung.model.User;
+
+public class ValidationIntegrationTest {
+ private static ValidatorFactory validatorFactory;
+ private static Validator validator;
+
+ @BeforeClass
+ public static void setup() {
+ validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
+ .configure()
+ .buildValidatorFactory();
+ validator = validatorFactory.getValidator();
+ }
+
+ @Test
+ public void givenUser_whenValidate_thenValidationViolations() {
+ User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
+
+ Set> violations = validator.validate(user);
+ assertTrue("no violations", violations.size() > 0);
+ }
+
+ @Test
+ public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
+ User user = new User("ana@yahoo.com", "pass", "Ana", 12);
+
+ Set> propertyViolations = validator.validateProperty(user, "age");
+ assertEquals("size is not 1", 1, propertyViolations.size());
+ }
+
+ @Test
+ public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
+ User user = new User("ana@yahoo.com", "pass", "Ana", 18);
+
+ Set> valueViolations = validator.validateValue(User.class, "age", 20);
+ assertEquals("size is not 0", 0, valueViolations.size());
+ }
+
+ @Test
+ public void whenValidateNonJSR_thenCorrect() {
+ User user = new User("ana@yahoo.com", "pass", "Ana", 20);
+ user.setCardNumber("1234");
+ user.setIban("1234");
+ user.setWebsite("10.0.2.50");
+ user.setMainDirectory(new File("."));
+
+ Set> violations = validator.validateProperty(user, "iban");
+ assertEquals("size is not 1", 1, violations.size());
+
+ violations = validator.validateProperty(user, "website");
+ assertEquals("size is not 0", 0, violations.size());
+
+ violations = validator.validateProperty(user, "mainDirectory");
+ assertEquals("size is not 0", 0, violations.size());
+ }
+
+ @Test
+ public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
+ User user = new User("ana@yahoo.com", "password", "Ana", 20);
+ Set> violations = validator.validateProperty(user, "password");
+ assertEquals("message incorrect", "Invalid password", violations.iterator()
+ .next()
+ .getMessage());
+ }
+
+ @Test
+ public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
+ User user = new User("ana@yahoo.com", "password#", "Ana", 20);
+
+ Set> violations = validator.validateProperty(user, "password");
+ assertEquals("size is not 0", 0, violations.size());
+ }
+
+ @AfterClass
+ public static void close() {
+ if (validatorFactory != null) {
+ validatorFactory.close();
+ }
+ }
+}
diff --git a/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java b/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java
deleted file mode 100644
index cd58d4460a..0000000000
--- a/apache-bval/src/test/java/com/baeldung/validation/ValidationTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.baeldung.validation;
-
-import java.io.File;
-import java.util.Set;
-
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
-
-import org.apache.bval.jsr.ApacheValidationProvider;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import com.baeldung.model.User;
-
-public class ValidationTest {
- private static ValidatorFactory validatorFactory;
- private static Validator validator;
-
- @BeforeClass
- public static void setup() {
- validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
- .configure()
- .buildValidatorFactory();
- validator = validatorFactory.getValidator();
- }
-
- @Test
- public void givenUser_whenValidate_thenValidationViolations() {
- User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
-
- Set> violations = validator.validate(user);
- assertTrue("no violations", violations.size() > 0);
- }
-
- @Test
- public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
- User user = new User("ana@yahoo.com", "pass", "Ana", 12);
-
- Set> propertyViolations = validator.validateProperty(user, "age");
- assertEquals("size is not 1", 1, propertyViolations.size());
- }
-
- @Test
- public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
- User user = new User("ana@yahoo.com", "pass", "Ana", 18);
-
- Set> valueViolations = validator.validateValue(User.class, "age", 20);
- assertEquals("size is not 0", 0, valueViolations.size());
- }
-
- @Test
- public void whenValidateNonJSR_thenCorrect() {
- User user = new User("ana@yahoo.com", "pass", "Ana", 20);
- user.setCardNumber("1234");
- user.setIban("1234");
- user.setWebsite("10.0.2.50");
- user.setMainDirectory(new File("."));
-
- Set> violations = validator.validateProperty(user, "iban");
- assertEquals("size is not 1", 1, violations.size());
-
- violations = validator.validateProperty(user, "website");
- assertEquals("size is not 0", 0, violations.size());
-
- violations = validator.validateProperty(user, "mainDirectory");
- assertEquals("size is not 0", 0, violations.size());
- }
-
- @Test
- public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
- User user = new User("ana@yahoo.com", "password", "Ana", 20);
- Set> violations = validator.validateProperty(user, "password");
- assertEquals("message incorrect", "Invalid password", violations.iterator()
- .next()
- .getMessage());
- }
-
- @Test
- public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
- User user = new User("ana@yahoo.com", "password#", "Ana", 20);
-
- Set> violations = validator.validateProperty(user, "password");
- assertEquals("size is not 0", 0, violations.size());
- }
-
- @AfterClass
- public static void close() {
- if (validatorFactory != null) {
- validatorFactory.close();
- }
- }
-}
diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml
index b436b03305..6d8aa85679 100644
--- a/apache-cxf/cxf-aegis/pom.xml
+++ b/apache-cxf/cxf-aegis/pom.xml
@@ -8,7 +8,7 @@
0.0.1-SNAPSHOT
- 3.1.8
+ 3.1.8
diff --git a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java
new file mode 100644
index 0000000000..b28b987cfa
--- /dev/null
+++ b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java
@@ -0,0 +1,103 @@
+package com.baeldung.cxf.aegis;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.lang.reflect.Type;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.xml.namespace.QName;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamReader;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.apache.cxf.aegis.AegisContext;
+import org.apache.cxf.aegis.AegisReader;
+import org.apache.cxf.aegis.AegisWriter;
+import org.apache.cxf.aegis.type.AegisType;
+
+public class BaeldungIntegrationTest {
+ private AegisContext context;
+ private String fileName = "baeldung.xml";
+
+ @Test
+ public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
+ initializeContext();
+ CourseRepo inputRepo = initCourseRepo();
+ marshalCourseRepo(inputRepo);
+ CourseRepo outputRepo = unmarshalCourseRepo();
+ Course restCourse = outputRepo.getCourses().get(1);
+ Course securityCourse = outputRepo.getCourses().get(2);
+ assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
+ assertEquals("REST with Spring", restCourse.getName());
+ assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
+ assertNull(restCourse.getInstructor());
+ assertEquals("Learn Spring Security", securityCourse.getName());
+ assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
+ assertNull(securityCourse.getInstructor());
+ }
+
+ private void initializeContext() {
+ context = new AegisContext();
+ Set rootClasses = new HashSet();
+ rootClasses.add(CourseRepo.class);
+ context.setRootClasses(rootClasses);
+ Map, String> beanImplementationMap = new HashMap<>();
+ beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
+ context.setBeanImplementationMap(beanImplementationMap);
+ context.setWriteXsiTypes(true);
+ context.initialize();
+ }
+
+ private CourseRepoImpl initCourseRepo() {
+ Course restCourse = new Course();
+ restCourse.setId(1);
+ restCourse.setName("REST with Spring");
+ restCourse.setInstructor("Eugen");
+ restCourse.setEnrolmentDate(new Date(1234567890000L));
+ Course securityCourse = new Course();
+ securityCourse.setId(2);
+ securityCourse.setName("Learn Spring Security");
+ securityCourse.setInstructor("Eugen");
+ securityCourse.setEnrolmentDate(new Date(1456789000000L));
+ CourseRepoImpl courseRepo = new CourseRepoImpl();
+ courseRepo.setGreeting("Welcome to Beldung!");
+ courseRepo.addCourse(restCourse);
+ courseRepo.addCourse(securityCourse);
+ return courseRepo;
+ }
+
+ private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
+ AegisWriter writer = context.createXMLStreamWriter();
+ AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
+ XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
+ writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
+ xmlWriter.close();
+ }
+
+ private CourseRepo unmarshalCourseRepo() throws Exception {
+ AegisReader reader = context.createXMLStreamReader();
+ XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
+ CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
+ xmlReader.close();
+ return courseRepo;
+ }
+
+ @After
+ public void cleanup(){
+ File testFile = new File(fileName);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java
deleted file mode 100644
index 559de037a9..0000000000
--- a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.baeldung.cxf.aegis;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Test;
-
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.lang.reflect.Type;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import javax.xml.namespace.QName;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.stream.XMLStreamWriter;
-
-import org.apache.cxf.aegis.AegisContext;
-import org.apache.cxf.aegis.AegisReader;
-import org.apache.cxf.aegis.AegisWriter;
-import org.apache.cxf.aegis.type.AegisType;
-
-public class BaeldungTest {
- private AegisContext context;
- private String fileName = "baeldung.xml";
-
- @Test
- public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
- initializeContext();
- CourseRepo inputRepo = initCourseRepo();
- marshalCourseRepo(inputRepo);
- CourseRepo outputRepo = unmarshalCourseRepo();
- Course restCourse = outputRepo.getCourses().get(1);
- Course securityCourse = outputRepo.getCourses().get(2);
- assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
- assertEquals("REST with Spring", restCourse.getName());
- assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
- assertNull(restCourse.getInstructor());
- assertEquals("Learn Spring Security", securityCourse.getName());
- assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
- assertNull(securityCourse.getInstructor());
- }
-
- private void initializeContext() {
- context = new AegisContext();
- Set rootClasses = new HashSet();
- rootClasses.add(CourseRepo.class);
- context.setRootClasses(rootClasses);
- Map, String> beanImplementationMap = new HashMap<>();
- beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
- context.setBeanImplementationMap(beanImplementationMap);
- context.setWriteXsiTypes(true);
- context.initialize();
- }
-
- private CourseRepoImpl initCourseRepo() {
- Course restCourse = new Course();
- restCourse.setId(1);
- restCourse.setName("REST with Spring");
- restCourse.setInstructor("Eugen");
- restCourse.setEnrolmentDate(new Date(1234567890000L));
- Course securityCourse = new Course();
- securityCourse.setId(2);
- securityCourse.setName("Learn Spring Security");
- securityCourse.setInstructor("Eugen");
- securityCourse.setEnrolmentDate(new Date(1456789000000L));
- CourseRepoImpl courseRepo = new CourseRepoImpl();
- courseRepo.setGreeting("Welcome to Beldung!");
- courseRepo.addCourse(restCourse);
- courseRepo.addCourse(securityCourse);
- return courseRepo;
- }
-
- private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
- AegisWriter writer = context.createXMLStreamWriter();
- AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
- XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
- writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
- xmlWriter.close();
- }
-
- private CourseRepo unmarshalCourseRepo() throws Exception {
- AegisReader reader = context.createXMLStreamReader();
- XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
- CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
- xmlReader.close();
- return courseRepo;
- }
-}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
index 6e0ceaba7e..1b9ba22230 100644
--- a/apache-cxf/cxf-introduction/pom.xml
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -4,18 +4,18 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
cxf-introduction
-
+
com.baeldung
apache-cxf
0.0.1-SNAPSHOT
-
+
3.1.8
- 2.19.1
+ 2.19.1
-
+
@@ -36,7 +36,7 @@
-
+
org.apache.cxf
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
index c3095be5a5..981e0ef7aa 100644
--- a/apache-cxf/cxf-jaxrs-implementation/pom.xml
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -4,20 +4,20 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
cxf-jaxrs-implementation
-
+
com.baeldung
apache-cxf
0.0.1-SNAPSHOT
-
+
UTF-8
3.1.8
4.5.2
- 2.19.1
+ 2.19.1
-
+
@@ -38,7 +38,7 @@
-
+
org.apache.cxf
@@ -54,6 +54,12 @@
org.apache.httpcomponents
httpclient
${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
index 79a7650ced..2cd700680b 100644
--- a/apache-cxf/cxf-spring/pom.xml
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -8,7 +8,7 @@
apache-cxf
0.0.1-SNAPSHOT
-
+
org.apache.cxf
@@ -24,6 +24,12 @@
org.springframework
spring-context
${spring.version}
+
+
+ commons-logging
+ commons-logging
+
+
org.springframework
@@ -36,7 +42,7 @@
${javax.servlet-api.version}
-
+
@@ -57,7 +63,7 @@
-
+
live
@@ -96,7 +102,7 @@
-
+
maven-surefire-plugin
${surefire.version}
@@ -117,17 +123,17 @@
-
+
-
+
3.1.8
4.3.4.RELEASE
3.1.0
-
- 2.6
+
+ 2.6
2.19.1
- 1.6.1
+ 1.6.1
-
+
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 6849452908..3bc3853f2b 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -6,6 +6,12 @@
0.0.1-SNAPSHOT
pom
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
cxf-introduction
cxf-spring
@@ -14,33 +20,13 @@
- 4.12
- 3.6.0
1.5.0
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
install
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
org.codehaus.mojo
exec-maven-plugin
diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml
index 6f89497a7d..f7439dc244 100644
--- a/apache-fop/pom.xml
+++ b/apache-fop/pom.xml
@@ -7,64 +7,14 @@
apache-fop
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
-
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
-
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
-
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
-
org.apache.xmlgraphics
fop
@@ -78,6 +28,10 @@
org.apache.avalon.framework
avalon-framework-impl
+
+ commons-logging
+ commons-logging
+
@@ -90,6 +44,12 @@
avalon-framework
avalon-framework-impl
${avalon-framework.version}
+
+
+ commons-logging
+ commons-logging
+
+
@@ -101,9 +61,7 @@
org.dbdoclet
herold
- 6.1.0
- system
- ${basedir}/src/test/resources/jars/herold.jar
+ 8.0.4
@@ -122,33 +80,6 @@
true
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.7
- 1.7
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*IntegrationTest.java
- **/*LiveTest.java
-
-
-
-
-
-
@@ -192,19 +123,6 @@
4.3
8.0.2
r938
-
- 1.7.21
- 1.1.7
-
-
- 1.3
- 4.12
- 1.10.19
-
-
- 3.6.0
- 2.19.1
-
\ No newline at end of file
diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml
index 62d0ea5037..ec0dc2469a 100644
--- a/apache-fop/src/main/resources/logback.xml
+++ b/apache-fop/src/main/resources/logback.xml
@@ -1,5 +1,5 @@
+
-
web - %date [%thread] %-5level %logger{36} - %message%n
@@ -7,10 +7,13 @@
-
+
+
+
+
+
-
\ No newline at end of file
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/pom.xml b/apache-poi/pom.xml
index d8a2cc72e0..22c0cd156a 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -5,34 +5,18 @@
apache-poi
0.0.1-SNAPSHOT
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
- 3.6.0
- 4.12
3.15
- 1.0.6
+ 1.0.6
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
-
- junit
- junit
- ${junit.version}
- test
-
org.apache.poi
poi-ooxml
@@ -42,6 +26,12 @@
org.jxls
jxls-jexcel
${jexcel.version}
-
+
+
+ commons-logging
+ commons-logging
+
+
+
diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
new file mode 100644
index 0000000000..41efd9d9ba
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
@@ -0,0 +1,64 @@
+package com.baeldung.jexcel;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import jxl.read.biff.BiffException;
+import java.util.Map;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.jexcel.JExcelHelper;
+
+import jxl.write.WriteException;
+import jxl.read.biff.BiffException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.After;
+
+public class JExcelIntegrationTest {
+
+ private JExcelHelper jExcelHelper;
+ private static String FILE_NAME = "temp.xls";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException, WriteException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ jExcelHelper = new JExcelHelper();
+ jExcelHelper.writeJExcel();
+
+ }
+
+ @Test
+ public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
+ Map> data = jExcelHelper.readJExcel(fileLocation);
+
+ assertEquals("Name", data.get(0)
+ .get(0));
+ assertEquals("Age", data.get(0)
+ .get(1));
+
+ assertEquals("John Smith", data.get(2)
+ .get(0));
+ assertEquals("20", data.get(2)
+ .get(1));
+ }
+
+ @After
+ public void cleanup(){
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
deleted file mode 100644
index 8ee465be34..0000000000
--- a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.baeldung.jexcel;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import jxl.read.biff.BiffException;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.jexcel.JExcelHelper;
-
-import jxl.write.WriteException;
-import jxl.read.biff.BiffException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.junit.Before;
-
-public class JExcelTest {
-
- private JExcelHelper jExcelHelper;
- private static String FILE_NAME = "temp.xls";
- private String fileLocation;
-
- @Before
- public void generateExcelFile() throws IOException, WriteException {
-
- File currDir = new File(".");
- String path = currDir.getAbsolutePath();
- fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
-
- jExcelHelper = new JExcelHelper();
- jExcelHelper.writeJExcel();
-
- }
-
- @Test
- public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
- Map> data = jExcelHelper.readJExcel(fileLocation);
-
- assertEquals("Name", data.get(0)
- .get(0));
- assertEquals("Age", data.get(0)
- .get(1));
-
- assertEquals("John Smith", data.get(2)
- .get(0));
- assertEquals("20", data.get(2)
- .get(1));
- }
-
-}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
new file mode 100644
index 0000000000..5d7ccb9b94
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.poi.excel;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import jxl.read.biff.BiffException;
+import java.util.Map;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.poi.excel.ExcelPOIHelper;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.After;
+
+public class ExcelIntegrationTest {
+
+ private ExcelPOIHelper excelPOIHelper;
+ private static String FILE_NAME = "temp.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ excelPOIHelper = new ExcelPOIHelper();
+ excelPOIHelper.writeExcel();
+
+ }
+
+ @Test
+ public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
+ Map> data = excelPOIHelper.readExcel(fileLocation);
+
+ assertEquals("Name", data.get(0)
+ .get(0));
+ assertEquals("Age", data.get(0)
+ .get(1));
+
+ assertEquals("John Smith", data.get(1)
+ .get(0));
+ assertEquals("20", data.get(1)
+ .get(1));
+ }
+
+ @After
+ public void cleanup(){
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java
deleted file mode 100644
index 34fa64dd94..0000000000
--- a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.baeldung.poi.excel;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import jxl.read.biff.BiffException;
-import java.util.Map;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.baeldung.poi.excel.ExcelPOIHelper;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-import org.junit.Before;
-
-public class ExcelTest {
-
- private ExcelPOIHelper excelPOIHelper;
- private static String FILE_NAME = "temp.xlsx";
- private String fileLocation;
-
- @Before
- public void generateExcelFile() throws IOException {
-
- File currDir = new File(".");
- String path = currDir.getAbsolutePath();
- fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
-
- excelPOIHelper = new ExcelPOIHelper();
- excelPOIHelper.writeExcel();
-
- }
-
- @Test
- public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
- Map> data = excelPOIHelper.readExcel(fileLocation);
-
- assertEquals("Name", data.get(0)
- .get(0));
- assertEquals("Age", data.get(0)
- .get(1));
-
- assertEquals("John Smith", data.get(1)
- .get(0));
- assertEquals("20", data.get(1)
- .get(1));
- }
-
-}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java
new file mode 100644
index 0000000000..98b5c5b520
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.poi.word;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
+import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.apache.poi.xwpf.usermodel.XWPFParagraph;
+import org.apache.poi.xwpf.usermodel.XWPFRun;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class WordIntegrationTest {
+ static WordDocument wordDocument;
+
+ @BeforeClass
+ public static void generateMSWordFile() throws Exception {
+ WordIntegrationTest.wordDocument = new WordDocument();
+ wordDocument.handleSimpleDoc();
+ }
+
+ @Test
+ public void whenParsingOutputDocument_thenCorrect() throws Exception {
+ Path msWordPath = Paths.get(WordDocument.output);
+ XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
+ List paragraphs = document.getParagraphs();
+ document.close();
+
+ XWPFParagraph title = paragraphs.get(0);
+ XWPFRun titleRun = title.getRuns().get(0);
+ assertEquals("Build Your REST API with Spring", title.getText());
+ assertEquals("009933", titleRun.getColor());
+ assertTrue(titleRun.isBold());
+ assertEquals("Courier", titleRun.getFontFamily());
+ assertEquals(20, titleRun.getFontSize());
+
+ assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
+ assertEquals("What makes a good API?", paragraphs.get(3).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
+ }
+}
diff --git a/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java b/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
deleted file mode 100644
index bc1011a03a..0000000000
--- a/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.baeldung.poi.word;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
-import org.apache.poi.xwpf.usermodel.XWPFParagraph;
-import org.apache.poi.xwpf.usermodel.XWPFRun;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class WordTest {
- static WordDocument wordDocument;
-
- @BeforeClass
- public static void generateMSWordFile() throws Exception {
- WordTest.wordDocument = new WordDocument();
- wordDocument.handleSimpleDoc();
- }
-
- @Test
- public void whenParsingOutputDocument_thenCorrect() throws Exception {
- Path msWordPath = Paths.get(WordDocument.output);
- XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
- List paragraphs = document.getParagraphs();
- document.close();
-
- XWPFParagraph title = paragraphs.get(0);
- XWPFRun titleRun = title.getRuns().get(0);
- assertEquals("Build Your REST API with Spring", title.getText());
- assertEquals("009933", titleRun.getColor());
- assertTrue(titleRun.isBold());
- assertEquals("Courier", titleRun.getFontFamily());
- assertEquals(20, titleRun.getFontSize());
-
- assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
- assertEquals("What makes a good API?", paragraphs.get(3).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
- }
-}
diff --git a/apache-poi/temp.xls b/apache-poi/temp.xls
deleted file mode 100644
index 1fad76d88d..0000000000
Binary files a/apache-poi/temp.xls and /dev/null differ
diff --git a/apache-poi/temp.xlsx b/apache-poi/temp.xlsx
deleted file mode 100644
index 5281b2c4de..0000000000
Binary files a/apache-poi/temp.xlsx and /dev/null 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/pom.xml b/apache-solrj/pom.xml
index 74daeae55c..ea696b024b 100644
--- a/apache-solrj/pom.xml
+++ b/apache-solrj/pom.xml
@@ -1,50 +1,23 @@
- 4.0.0
- com.baeldung
- apache-solrj
- 0.0.1-SNAPSHOT
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ apache-solrj
+ 0.0.1-SNAPSHOT
jar
apache-solrj
-
- 4.12
- 2.19.1
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
-
- org.apache.solr
- solr-solrj
- 6.4.0
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
-
-
- maven-compiler-plugin
- 2.3.2
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- 1.8
- 1.8
-
- **/*IntegrationTest.java
- **/*LiveTest.java
-
-
-
-
-
+
+
+ org.apache.solr
+ solr-solrj
+ 6.4.0
+
+
\ No newline at end of file
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/apache-thrift/pom.xml b/apache-thrift/pom.xml
index 66cfb2bb41..91e51a7092 100644
--- a/apache-thrift/pom.xml
+++ b/apache-thrift/pom.xml
@@ -6,10 +6,14 @@
0.0.1-SNAPSHOT
pom
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
1.8
- 4.12
- 3.6.0
0.10.0
0.1.11
@@ -19,13 +23,12 @@
org.apache.thrift
libthrift
${thrift.version}
-
-
-
- junit
- junit
- ${junit.version}
- test
+
+
+ commons-logging
+ commons-logging
+
+
@@ -39,22 +42,15 @@
install
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
org.codehaus.mojo
build-helper-maven-plugin
generate-sources
- add-source
+
+ add-source
+
generated
diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java
new file mode 100644
index 0000000000..7d4b41c400
--- /dev/null
+++ b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.thrift;
+
+import org.apache.thrift.transport.TTransportException;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class CrossPlatformServiceIntegrationTest {
+
+ private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
+
+ @Before
+ public void setUp() {
+ new Thread(() -> {
+ try {
+ server.start();
+ } catch (TTransportException e) {
+ e.printStackTrace();
+ }
+ }).start();
+ try {
+ // wait for the server start up
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @After
+ public void tearDown() {
+ server.stop();
+ }
+
+ @Test
+ public void ping() {
+ CrossPlatformServiceClient client = new CrossPlatformServiceClient();
+ Assert.assertTrue(client.ping());
+ }
+}
diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java
deleted file mode 100644
index 4ba9ef2914..0000000000
--- a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.baeldung.thrift;
-
-import org.apache.thrift.transport.TTransportException;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class CrossPlatformServiceTest {
-
- private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
-
- @Before
- public void setUp() {
- new Thread(() -> {
- try {
- server.start();
- } catch (TTransportException e) {
- e.printStackTrace();
- }
- }).start();
- try {
- // wait for the server start up
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- @After
- public void tearDown() {
- server.stop();
- }
-
- @Test
- public void ping() {
- CrossPlatformServiceClient client = new CrossPlatformServiceClient();
- Assert.assertTrue(client.ping());
- }
-}
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
index 08f0e96a58..69633ebbab 100644
--- a/apache-velocity/pom.xml
+++ b/apache-velocity/pom.xml
@@ -1,5 +1,5 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.baeldung
@@ -9,27 +9,22 @@
war
apache-velocity
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
1.8
1.2
- 4.11
- 1.0.13
- 1.7.5
- 3.6.0
2.6
- 2.19.1
4.5.2
1.7
2.0
-
- junit
- junit
- ${junit.version}
- test
-
org.apache.velocity
velocity
@@ -40,21 +35,17 @@
velocity-tools
${velocity-tools-version}
-
- org.slf4j
- jcl-over-slf4j
- ${jcl-over-slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
org.apache.httpcomponents
httpclient
${org.apache.httpcomponents.version}
test
+
+
+ commons-logging
+ commons-logging
+
+
@@ -66,15 +57,6 @@
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${jdk.version}
- ${jdk.version}
-
-
org.apache.maven.plugins
maven-war-plugin
@@ -83,19 +65,6 @@
false
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*LiveTest.java
-
-
-
-
-
diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml
index 70a420a57a..ec0dc2469a 100644
--- a/apache-velocity/src/main/resources/logback.xml
+++ b/apache-velocity/src/main/resources/logback.xml
@@ -1,23 +1,19 @@
-
-
-
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
-
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
\ No newline at end of file
diff --git a/aspectj/README.md b/aspectj/README.md
deleted file mode 100644
index 71724e76b6..0000000000
--- a/aspectj/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant Articles:
-- [Intro to AspectJ](http://www.baeldung.com/aspectj)
-- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
diff --git a/aspectj/pom.xml b/aspectj/pom.xml
deleted file mode 100644
index 90b527c14f..0000000000
--- a/aspectj/pom.xml
+++ /dev/null
@@ -1,143 +0,0 @@
-
- 4.0.0
- com.baeldung
- aspectj
- 0.0.1-SNAPSHOT
- aspectj
-
-
-
- org.aspectj
- aspectjrt
- ${aspectj.version}
-
-
-
- org.aspectj
- aspectjweaver
- ${aspectj.version}
-
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- ch.qos.logback
- logback-core
- ${logback.version}
-
-
-
-
- junit
- junit
- ${junit.version}
-
-
-
- org.springframework
- spring-context
- 4.3.4.RELEASE
-
-
- org.springframework
- spring-beans
- 4.3.4.RELEASE
-
-
- org.springframework
- spring-core
- 4.3.4.RELEASE
-
-
- cglib
- cglib
- 3.2.4
-
-
- org.springframework
- spring-aop
- 4.3.4.RELEASE
-
-
- log4j
- log4j
- 1.2.17
-
-
-
-
- aspectj
-
-
- src/main/resources
- true
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${source.version}
- ${source.version}
-
-
-
-
-
- org.codehaus.mojo
- aspectj-maven-plugin
- 1.7
-
- ${source.version}
- ${source.version}
- ${source.version}
- true
- true
- ignore
- ${project.build.sourceEncoding}
-
-
-
-
-
-
- compile
- test-compile
-
-
-
-
-
-
-
-
-
-
- 1.8
- UTF-8
- 1.8.9
- 1.7.21
- 1.1.7
- 3.6.0
- 4.12
-
-
-
\ No newline at end of file
diff --git a/aspectj/src/main/java/com/baeldung/aspectj/Account.java b/aspectj/src/main/java/com/baeldung/aspectj/Account.java
deleted file mode 100644
index bc9ca375aa..0000000000
--- a/aspectj/src/main/java/com/baeldung/aspectj/Account.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.baeldung.aspectj;
-
-public class Account {
- int balance = 20;
-
- public boolean withdraw(int amount) {
- if (balance < amount) {
- return false;
- }
- balance = balance - amount;
- return true;
- }
-}
diff --git a/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java b/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java
deleted file mode 100644
index f16f28fdef..0000000000
--- a/aspectj/src/main/java/com/baeldung/performancemonitor/Person.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.performancemonitor;
-
-import java.time.LocalDate;
-
-public class Person {
- private String lastName;
- private String firstName;
- private LocalDate dateOfBirth;
-
- public Person() {
- }
-
- public Person(String firstName, String lastName, LocalDate dateOfBirth) {
- this.firstName = firstName;
- this.lastName = lastName;
- this.dateOfBirth = dateOfBirth;
- }
-
- public LocalDate getDateOfBirth() {
- return dateOfBirth;
- }
-
- public void setDateOfBirth(LocalDate dateOfBirth) {
- this.dateOfBirth = dateOfBirth;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-}
diff --git a/aspectj/src/main/resources/META-INF/aop.xml b/aspectj/src/main/resources/META-INF/aop.xml
deleted file mode 100644
index f930cde942..0000000000
--- a/aspectj/src/main/resources/META-INF/aop.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/aspectj/src/main/resources/log4j.properties b/aspectj/src/main/resources/log4j.properties
deleted file mode 100644
index 9e2afcd5b0..0000000000
--- a/aspectj/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-log4j.rootLogger=TRACE, stdout
-
-# Redirect log messages to console
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.Target=System.out
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
-
-log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorInterceptor=TRACE, stdout
-log4j.logger.com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor=INFO, stdout
\ No newline at end of file
diff --git a/aspectj/src/main/resources/logback.xml b/aspectj/src/main/resources/logback.xml
deleted file mode 100644
index 8b566286b8..0000000000
--- a/aspectj/src/main/resources/logback.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg %n
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java b/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java
deleted file mode 100644
index d90793f681..0000000000
--- a/aspectj/src/test/java/com/baeldung/aspectj/test/AccountTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.baeldung.aspectj.test;
-
-import static org.junit.Assert.*;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import com.baeldung.aspectj.Account;
-
-public class AccountTest {
- private Account account;
-
- @Before
- public void before() {
- account = new Account();
- }
-
- @Test
- public void givenBalance20AndMinBalance10_whenWithdraw5_thenSuccess() {
- assertTrue(account.withdraw(5));
- }
-
- @Test
- public void givenBalance20AndMinBalance10_whenWithdraw100_thenFail() {
- assertFalse(account.withdraw(100));
- }
-}
diff --git a/assertj/README.md b/assertj/README.md
deleted file mode 100644
index 86eff05057..0000000000
--- a/assertj/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-### Relevant Articles:
-- [AssertJ’s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
-- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)
diff --git a/assertj/pom.xml b/assertj/pom.xml
deleted file mode 100644
index 032f33c89d..0000000000
--- a/assertj/pom.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-
-
- 4.0.0
-
- com.baeldung
- assertj
- 1.0.0-SNAPSHOT
-
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- org.assertj
- assertj-guava
- 3.0.0
-
-
-
- junit
- junit
- ${junit.version}
- test
-
-
- org.assertj
- assertj-core
- ${assertj-core.version}
- test
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
-
- 19.0
- 3.1.0
- 4.12
- 3.6.1
-
- 3.6.0
-
-
-
\ No newline at end of file
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
deleted file mode 100644
index 90ef787ebe..0000000000
--- a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.assertj.introduction.domain;
-
-public class Person {
- private String name;
- private Integer age;
-
- public Person(String name, Integer age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public Integer getAge() {
- return age;
- }
-}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
deleted file mode 100644
index 10bb011903..0000000000
--- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package com.baeldung.assertj.introduction;
-
-import com.baeldung.assertj.introduction.domain.Dog;
-import com.baeldung.assertj.introduction.domain.Person;
-import org.assertj.core.util.Maps;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-import static org.assertj.core.api.Assertions.*;
-
-public class AssertJCoreTest {
-
- @Test
- public void whenComparingReferences_thenNotEqual() throws Exception {
- Dog fido = new Dog("Fido", 5.15f);
- Dog fidosClone = new Dog("Fido", 5.15f);
-
- assertThat(fido).isNotEqualTo(fidosClone);
- }
-
- @Test
- public void whenComparingFields_thenEqual() throws Exception {
- Dog fido = new Dog("Fido", 5.15f);
- Dog fidosClone = new Dog("Fido", 5.15f);
-
- assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
- }
-
- @Test
- public void whenCheckingForElement_thenContains() throws Exception {
- List list = Arrays.asList("1", "2", "3");
-
- assertThat(list).contains("1");
- }
-
- @Test
- public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
- List list = Arrays.asList("1", "2", "3");
-
- assertThat(list).isNotEmpty();
- assertThat(list).startsWith("1");
- assertThat(list).doesNotContainNull();
-
- assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
- }
-
- @Test
- public void whenCheckingRunnable_thenIsInterface() throws Exception {
- assertThat(Runnable.class).isInterface();
- }
-
- @Test
- public void whenCheckingCharacter_thenIsUnicode() throws Exception {
- char someCharacter = 'c';
-
- assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
- }
-
- @Test
- public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
- assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
- }
-
- @Test
- public void whenComparingWithOffset_thenEquals() throws Exception {
- assertThat(5.1).isEqualTo(5, withPrecision(1d));
- }
-
- @Test
- public void whenCheckingString_then() throws Exception {
- assertThat("".isEmpty()).isTrue();
- }
-
- @Test
- public void whenCheckingFile_then() throws Exception {
- final File someFile = File.createTempFile("aaa", "bbb");
- someFile.deleteOnExit();
-
- assertThat(someFile).exists().isFile().canRead().canWrite();
- }
-
- @Test
- public void whenCheckingIS_then() throws Exception {
- InputStream given = new ByteArrayInputStream("foo".getBytes());
- InputStream expected = new ByteArrayInputStream("foo".getBytes());
-
- assertThat(given).hasSameContentAs(expected);
- }
-
- @Test
- public void whenGivenMap_then() throws Exception {
- Map map = Maps.newHashMap(2, "a");
-
- assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
- }
-
- @Test
- public void whenGivenException_then() throws Exception {
- Exception ex = new Exception("abc");
-
- assertThat(ex).hasNoCause().hasMessageEndingWith("c");
- }
-
- @Ignore // IN ORDER TO TEST, REMOVE THIS LINE
- @Test
- public void whenRunningAssertion_thenDescribed() throws Exception {
- Person person = new Person("Alex", 34);
-
- assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
- }
-}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java
deleted file mode 100644
index 84aaf46dd1..0000000000
--- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.baeldung.assertj.introduction;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.HashBasedTable;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Multimaps;
-import com.google.common.collect.Range;
-import com.google.common.collect.Table;
-import com.google.common.collect.TreeRangeMap;
-import com.google.common.io.Files;
-import org.assertj.guava.data.MapEntry;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.HashSet;
-
-import static org.assertj.guava.api.Assertions.assertThat;
-import static org.assertj.guava.api.Assertions.entry;
-
-public class AssertJGuavaTest {
-
- @Test
- public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
- final File temp1 = File.createTempFile("bael", "dung1");
- final File temp2 = File.createTempFile("bael", "dung2");
-
- assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
- }
-
- @Test
- public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
- final Multimap mmap = ArrayListMultimap.create();
- mmap.put(1, "one");
- mmap.put(1, "1");
-
- assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
- }
-
- @Test
- public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
- final Multimap mmap1 = ArrayListMultimap.create();
- mmap1.put(1, "one");
- mmap1.put(1, "1");
- mmap1.put(2, "two");
- mmap1.put(2, "2");
-
- final Multimap mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
- mmap1_clone.put(1, "one");
- mmap1_clone.put(1, "1");
- mmap1_clone.put(2, "two");
- mmap1_clone.put(2, "2");
-
- final Multimap mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
- mmap2.put(1, "one");
- mmap2.put(1, "1");
-
- assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
- }
-
- @Test
- public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
- final Optional something = Optional.of("something");
-
- assertThat(something).isPresent().extractingValue().isEqualTo("something");
- }
-
- @Test
- public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
- final Range range = Range.openClosed("a", "g");
-
- assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
- }
-
- @Test
- public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
- final TreeRangeMap map = TreeRangeMap.create();
-
- map.put(Range.closed(0, 60), "F");
- map.put(Range.closed(61, 70), "D");
-
- assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
- }
-
- @Test
- public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
- final Table table = HashBasedTable.create(2, 2);
-
- table.put(1, "A", "PRESENT");
- table.put(1, "B", "ABSENT");
-
- assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
- }
-
-}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java
deleted file mode 100644
index f89defaed1..0000000000
--- a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.baeldung.assertj.introduction;
-
-import org.junit.Test;
-
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-import java.util.function.Predicate;
-
-import static java.time.LocalDate.ofYearDay;
-import static java.util.Arrays.asList;
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class AssertJJava8Test {
-
- @Test
- public void givenOptional_shouldAssert() throws Exception {
- final Optional givenOptional = Optional.of("something");
-
- assertThat(givenOptional).isPresent().hasValue("something");
- }
-
- @Test
- public void givenPredicate_shouldAssert() throws Exception {
- final Predicate predicate = s -> s.length() > 4;
-
- assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
- }
-
- @Test
- public void givenLocalDate_shouldAssert() throws Exception {
- final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
- final LocalDate todayDate = LocalDate.now();
-
- assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
-
- assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
- }
-
- @Test
- public void givenLocalDateTime_shouldAssert() throws Exception {
- final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
-
- assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
- }
-
- @Test
- public void givenLocalTime_shouldAssert() throws Exception {
- final LocalTime givenLocalTime = LocalTime.of(12, 15);
-
- assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
- }
-
- @Test
- public void givenList_shouldAssertFlatExtracting() throws Exception {
- final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
-
- assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
- }
-
- @Test
- public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
- final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
-
- assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
- }
-
- @Test
- public void givenList_shouldAssertFlatExtractingClass() throws Exception {
- final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
-
- assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
- }
-
- @Test
- public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
- final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
-
- assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
- }
-
- @Test
- public void givenString_shouldSatisfy() throws Exception {
- final String givenString = "someString";
-
- assertThat(givenString).satisfies(s -> {
- assertThat(s).isNotEmpty();
- assertThat(s).hasSize(10);
- });
- }
-
- @Test
- public void givenString_shouldMatch() throws Exception {
- final String emptyString = "";
-
- assertThat(emptyString).matches(String::isEmpty);
- }
-
- @Test
- public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
- final List givenList = Arrays.asList("");
-
- assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
- }
-}
diff --git a/autovalue/pom.xml b/autovalue/pom.xml
index 32616dc8bc..9e6aeff866 100644
--- a/autovalue/pom.xml
+++ b/autovalue/pom.xml
@@ -6,20 +6,11 @@
1.0
autovalue
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 7
- 7
- false
-
-
-
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
@@ -27,19 +18,10 @@
auto-value
${auto-value.version}
-
-
- junit
- junit
- ${junit.version}
- test
-
1.3
- 4.12
- 3.6.0
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/aws/pom.xml b/aws/pom.xml
index 681b76cfd4..8d60240c87 100644
--- a/aws/pom.xml
+++ b/aws/pom.xml
@@ -1,63 +1,81 @@
- 4.0.0
- com.baeldung
- aws
- 0.1.0-SNAPSHOT
- jar
- aws
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ aws
+ 0.1.0-SNAPSHOT
+ jar
+ aws
-
- 2.5
- 1.3.0
- 1.1.0
- 2.8.0
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
-
- com.amazonaws
- aws-lambda-java-core
- ${aws-lambda-java-core.version}
-
+
+ 2.5
+ 1.3.0
+ 1.1.0
+ 2.8.0
+
-
- com.amazonaws
- aws-lambda-java-events
- ${aws-lambda-java-events.version}
-
+
+
+ com.amazonaws
+ aws-lambda-java-core
+ ${aws-lambda-java-core.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
-
- commons-io
- commons-io
- ${commons-io.version}
-
+
+ com.amazonaws
+ aws-lambda-java-events
+ ${aws-lambda-java-events.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
-
- com.google.code.gson
- gson
- ${gson.version}
-
-
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
- 3.0.0
-
- false
-
-
-
- package
-
- shade
-
-
-
-
-
-
+
+ com.google.code.gson
+ gson
+ ${gson.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+ 3.0.0
+
+ false
+
+
+
+ package
+
+ shade
+
+
+
+
+
+
\ No newline at end of file
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..97fe607cad
--- /dev/null
+++ b/axon/pom.xml
@@ -0,0 +1,31 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+
+ axon
+
+
+
+ org.axonframework
+ axon-test
+ ${axon.version}
+ test
+
+
+ org.axonframework
+ axon-core
+ ${axon.version}
+
+
+
+
+ 3.0.2
+
+
+
\ 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/MessagesAggregateIntegrationTest.java b/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java
new file mode 100644
index 0000000000..ad099d2c2b
--- /dev/null
+++ b/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.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 MessagesAggregateIntegrationTest {
+
+ 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/cdi/pom.xml b/cdi/pom.xml
index e5aaeb2c7b..da0672afde 100644
--- a/cdi/pom.xml
+++ b/cdi/pom.xml
@@ -7,6 +7,12 @@
cdi
1.0-SNAPSHOT
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
org.springframework
@@ -30,12 +36,6 @@
${weld-se-core.version}
-
- junit
- junit
- ${junit.version}
- test
-
org.springframework
spring-test
@@ -45,23 +45,6 @@
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*IntegrationTest.java
- **/*LiveTest.java
-
-
-
-
-
-
integration
@@ -100,8 +83,6 @@
4.3.4.RELEASE
1.8.9
2.4.1.Final
- 4.12
- 2.19.1
\ No newline at end of file
diff --git a/core-java-9/README.md b/core-java-9/README.md
index 53ad79e59c..3e82ffe14b 100644
--- a/core-java-9/README.md
+++ b/core-java-9/README.md
@@ -8,3 +8,8 @@
- [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)
+- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
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/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml
index eefdc7a337..ec0dc2469a 100644
--- a/core-java-9/src/main/resources/logback.xml
+++ b/core-java-9/src/main/resources/logback.xml
@@ -1,5 +1,5 @@
+
-
web - %date [%thread] %-5level %logger{36} - %message%n
@@ -7,10 +7,13 @@
-
+
+
+
+
+
-
+
-
\ No newline at end of file
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
deleted file mode 100644
index 121c17a860..0000000000
--- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.baeldung.java8;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.List;
-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 {
-
- private static List> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
-
- @Test
- public void filterOutPresentOptionalsWithFilter() {
- assertEquals(4, listOfOptionals.size());
-
- List filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
-
- assertEquals(2, filteredList.size());
- assertEquals("foo", filteredList.get(0));
- assertEquals("bar", filteredList.get(1));
- }
-
- @Test
- public void filterOutPresentOptionalsWithFlatMap() {
- assertEquals(4, listOfOptionals.size());
-
- List filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
- assertEquals(2, filteredList.size());
-
- assertEquals("foo", filteredList.get(0));
- assertEquals("bar", filteredList.get(1));
- }
-
- @Test
- public void filterOutPresentOptionalsWithFlatMap2() {
- assertEquals(4, listOfOptionals.size());
-
- List filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
- assertEquals(2, filteredList.size());
-
- assertEquals("foo", filteredList.get(0));
- assertEquals("bar", filteredList.get(1));
- }
-
- @Test
- public void filterOutPresentOptionalsWithJava9() {
- assertEquals(4, listOfOptionals.size());
-
- List filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
-
- assertEquals(2, filteredList.size());
- assertEquals("foo", filteredList.get(0));
- assertEquals("bar", filteredList.get(1));
- }
-
-}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamUnitTest.java
new file mode 100644
index 0000000000..7a28a4b977
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamUnitTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.java9;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+public class Java9OptionalsStreamUnitTest {
+
+ private static List> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
+
+ @Test
+ public void filterOutPresentOptionalsWithFilter() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
+
+ assertEquals(2, filteredList.size());
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithFlatMap() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList());
+ assertEquals(2, filteredList.size());
+
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithFlatMap2() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList());
+ assertEquals(2, filteredList.size());
+
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithJava9() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList());
+
+ assertEquals(2, filteredList.size());
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
deleted file mode 100644
index c0a5042b58..0000000000
--- a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.baeldung.java9;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-
-import java.awt.Image;
-import java.awt.image.BaseMultiResolutionImage;
-import java.awt.image.BufferedImage;
-import java.awt.image.MultiResolutionImage;
-import java.util.List;
-
-import org.junit.Test;
-
-public class MultiResultionImageTest {
-
- @Test
- public void baseMultiResImageTest() {
- int baseIndex = 1;
- int length = 4;
- BufferedImage[] resolutionVariants = new BufferedImage[length];
- for (int i = 0; i < length; i++) {
- resolutionVariants[i] = createImage(i);
- }
- MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
- List rvImageList = bmrImage.getResolutionVariants();
- assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
-
- for (int i = 0; i < length; i++) {
- int imageSize = getSize(i);
- Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
- assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
- }
-
- }
-
- private static int getSize(int i) {
- return 8 * (i + 1);
- }
-
- private static BufferedImage createImage(int i) {
- return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
- }
-
-}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java
new file mode 100644
index 0000000000..2c383a44b4
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageUnitTest.java
@@ -0,0 +1,44 @@
+package com.baeldung.java9;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+import java.awt.Image;
+import java.awt.image.BaseMultiResolutionImage;
+import java.awt.image.BufferedImage;
+import java.awt.image.MultiResolutionImage;
+import java.util.List;
+
+import org.junit.Test;
+
+public class MultiResultionImageUnitTest {
+
+ @Test
+ public void baseMultiResImageTest() {
+ int baseIndex = 1;
+ int length = 4;
+ BufferedImage[] resolutionVariants = new BufferedImage[length];
+ for (int i = 0; i < length; i++) {
+ resolutionVariants[i] = createImage(i);
+ }
+ MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
+ List rvImageList = bmrImage.getResolutionVariants();
+ assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
+
+ for (int i = 0; i < length; i++) {
+ int imageSize = getSize(i);
+ Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
+ assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
+ }
+
+ }
+
+ private static int getSize(int i) {
+ return 8 * (i + 1);
+ }
+
+ private static BufferedImage createImage(int i) {
+ return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB);
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
deleted file mode 100644
index 56b4bb7b8c..0000000000
--- a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.baeldung.java9;
-
-import java.util.Optional;
-import java.util.stream.Stream;
-
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
-public class OptionalToStreamTest {
-
- @Test
- public void testOptionalToStream() {
- Optional op = Optional.ofNullable("String value");
- Stream strOptionalStream = op.stream();
- Stream filteredStream = strOptionalStream.filter((str) -> {
- return str != null && str.startsWith("String");
- });
- assertEquals(1, filteredStream.count());
-
- }
-}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java
new file mode 100644
index 0000000000..adb3171eec
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.java9;
+
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
+public class OptionalToStreamUnitTest {
+
+ @Test
+ public void testOptionalToStream() {
+ Optional op = Optional.ofNullable("String value");
+ Stream strOptionalStream = op.stream();
+ Stream filteredStream = strOptionalStream.filter((str) -> {
+ return str != null && str.startsWith("String");
+ });
+ assertEquals(1, filteredStream.count());
+
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
deleted file mode 100644
index 0f8db83d9c..0000000000
--- a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.baeldung.java9;
-
-import java.util.Set;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class SetExamplesTest {
-
- @Test
- public void testUnmutableSet() {
- Set strKeySet = Set.of("key1", "key2", "key3");
- try {
- strKeySet.add("newKey");
- } catch (UnsupportedOperationException uoe) {
- }
- assertEquals(strKeySet.size(), 3);
- }
-
- @Test
- public void testArrayToSet() {
- Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
- Set intSet = Set.of(intArray);
- assertEquals(intSet.size(), intArray.length);
- }
-}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java
new file mode 100644
index 0000000000..9e7e8e6e4b
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.java9;
+
+import java.util.Set;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class SetExamplesUnitTest {
+
+ @Test
+ public void testUnmutableSet() {
+ Set strKeySet = Set.of("key1", "key2", "key3");
+ try {
+ strKeySet.add("newKey");
+ } catch (UnsupportedOperationException uoe) {
+ }
+ assertEquals(strKeySet.size(), 3);
+ }
+
+ @Test
+ public void testArrayToSet() {
+ Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
+ Set intSet = Set.of(intArray);
+ assertEquals(intSet.size(), intArray.length);
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.java
new file mode 100644
index 0000000000..5d52acb284
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/concurrent/future/CompletableFutureUnitTest.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 CompletableFutureUnitTest {
+ @Test
+ public void testDelay () throws Exception {
+ Object input = new Object();
+ CompletableFuture