diff --git a/.gitignore b/.gitignore
index 0e71421ee7..21586748b7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,3 +66,10 @@ jmeter/src/main/resources/*-JMeter.csv
**/nb-configuration.xml
core-scala/.cache-main
core-scala/.cache-tests
+
+
+persistence-modules/hibernate5/transaction.log
+apache-avro/src/main/java/com/baeldung/avro/model/
+jta/transaction-logs/
+software-security/sql-injection-samples/derby.log
+spring-soap/src/main/java/com/baeldung/springsoap/gen/
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
index 683422dc97..5e86714a89 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
-script: travis_wait 60 mvn -q install -Pdefault-first,default-second
+script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
sudo: required
diff --git a/JGit/pom.xml b/JGit/pom.xml
index 176d55d321..deae1e45e3 100644
--- a/JGit/pom.xml
+++ b/JGit/pom.xml
@@ -5,9 +5,9 @@
com.baeldungJGit1.0-SNAPSHOT
+ JGitjarhttp://maven.apache.org
- JGitcom.baeldung
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
index cb476b9d9e..a50028a9ae 100644
--- a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
+++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
@@ -28,14 +28,14 @@ public class Log {
System.out.println("Had " + count + " commits overall on current branch");
logs = git.log()
- .add(repository.resolve("remotes/origin/testbranch"))
+ .add(repository.resolve(git.getRepository().getFullBranch()))
.call();
count = 0;
for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++;
}
- System.out.println("Had " + count + " commits overall on test-branch");
+ System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log()
.all()
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
index ed7168b2c2..ad34890996 100644
--- a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
+++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
@@ -1,3 +1,5 @@
+package com.baeldung.jgit;
+
import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
diff --git a/README.md b/README.md
index f3fe5e3bf0..378d77196a 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ Java and Spring Tutorials
================
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
-A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
+A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml
index 982c1adc23..b82b9f6778 100644
--- a/Twitter4J/pom.xml
+++ b/Twitter4J/pom.xml
@@ -2,8 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0Twitter4J
- jarTwitter4J
+ jarcom.baeldung
diff --git a/akka-http/README.md b/akka-http/README.md
new file mode 100644
index 0000000000..3831b5079f
--- /dev/null
+++ b/akka-http/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [Introduction to Akka HTTP](https://www.baeldung.com/akka-http)
diff --git a/akka-http/pom.xml b/akka-http/pom.xml
new file mode 100644
index 0000000000..6d73f2f2e6
--- /dev/null
+++ b/akka-http/pom.xml
@@ -0,0 +1,47 @@
+
+
+
+ 4.0.0
+ akka-http
+ akka-http
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+
+
+
+ com.typesafe.akka
+ akka-http_2.12
+ ${akka.http.version}
+
+
+ com.typesafe.akka
+ akka-stream_2.12
+ ${akka.stream.version}
+
+
+ com.typesafe.akka
+ akka-http-jackson_2.12
+ ${akka.http.version}
+
+
+ com.typesafe.akka
+ akka-http-testkit_2.12
+ ${akka.http.version}
+ test
+
+
+
+
+ UTF-8
+ UTF-8
+ 10.0.11
+ 2.5.11
+
+
diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/User.java b/akka-http/src/main/java/com/baeldung/akkahttp/User.java
new file mode 100644
index 0000000000..43c21eca62
--- /dev/null
+++ b/akka-http/src/main/java/com/baeldung/akkahttp/User.java
@@ -0,0 +1,26 @@
+package com.baeldung.akkahttp;
+
+public class User {
+
+ private final Long id;
+
+ private final String name;
+
+ public User() {
+ this.name = "";
+ this.id = null;
+ }
+
+ public User(Long id, String name) {
+ this.name = name;
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+}
\ No newline at end of file
diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java
new file mode 100644
index 0000000000..431014a88b
--- /dev/null
+++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java
@@ -0,0 +1,41 @@
+package com.baeldung.akkahttp;
+
+import akka.actor.AbstractActor;
+import akka.actor.Props;
+import akka.japi.pf.FI;
+import com.baeldung.akkahttp.UserMessages.ActionPerformed;
+import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
+import com.baeldung.akkahttp.UserMessages.GetUserMessage;
+
+
+class UserActor extends AbstractActor {
+
+ private UserService userService = new UserService();
+
+ static Props props() {
+ return Props.create(UserActor.class);
+ }
+
+ @Override
+ public Receive createReceive() {
+ return receiveBuilder()
+ .match(CreateUserMessage.class, handleCreateUser())
+ .match(GetUserMessage.class, handleGetUser())
+ .build();
+ }
+
+ private FI.UnitApply handleCreateUser() {
+ return createUserMessageMessage -> {
+ userService.createUser(createUserMessageMessage.getUser());
+ sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser()
+ .getName())), getSelf());
+ };
+ }
+
+ private FI.UnitApply handleGetUser() {
+ return getUserMessageMessage -> {
+ sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf());
+ };
+ }
+
+}
diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java
new file mode 100644
index 0000000000..995b92bcb0
--- /dev/null
+++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserMessages.java
@@ -0,0 +1,49 @@
+package com.baeldung.akkahttp;
+
+import java.io.Serializable;
+
+public interface UserMessages {
+
+ class ActionPerformed implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String description;
+
+ public ActionPerformed(String description) {
+ this.description = description;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+ }
+
+ class CreateUserMessage implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private final User user;
+
+ public CreateUserMessage(User user) {
+ this.user = user;
+ }
+
+ public User getUser() {
+ return user;
+ }
+ }
+
+ class GetUserMessage implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private final Long userId;
+
+ public GetUserMessage(Long userId) {
+ this.userId = userId;
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+ }
+
+}
diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java
new file mode 100644
index 0000000000..0c1dbd1f60
--- /dev/null
+++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserServer.java
@@ -0,0 +1,70 @@
+package com.baeldung.akkahttp;
+
+import java.util.Optional;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.TimeUnit;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.http.javadsl.marshallers.jackson.Jackson;
+import akka.http.javadsl.model.StatusCodes;
+import akka.http.javadsl.server.HttpApp;
+import akka.http.javadsl.server.Route;
+import akka.pattern.PatternsCS;
+import akka.util.Timeout;
+import com.baeldung.akkahttp.UserMessages.ActionPerformed;
+import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
+import com.baeldung.akkahttp.UserMessages.GetUserMessage;
+import scala.concurrent.duration.Duration;
+import static akka.http.javadsl.server.PathMatchers.*;
+
+class UserServer extends HttpApp {
+
+ private final ActorRef userActor;
+
+ Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
+
+ UserServer(ActorRef userActor) {
+ this.userActor = userActor;
+ }
+
+ @Override
+ public Route routes() {
+ return path("users", this::postUser)
+ .orElse(path(segment("users").slash(longSegment()), id ->
+ route(getUser(id))));
+ }
+
+ private Route getUser(Long id) {
+ return get(() -> {
+ CompletionStage> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout)
+ .thenApply(obj -> (Optional) obj);
+
+ return onSuccess(() -> user, performed -> {
+ if (performed.isPresent())
+ return complete(StatusCodes.OK, performed.get(), Jackson.marshaller());
+ else
+ return complete(StatusCodes.NOT_FOUND);
+ });
+ });
+ }
+
+ private Route postUser() {
+ return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> {
+ CompletionStage userCreated = PatternsCS.ask(userActor, new CreateUserMessage(user), timeout)
+ .thenApply(obj -> (ActionPerformed) obj);
+
+ return onSuccess(() -> userCreated, performed -> {
+ return complete(StatusCodes.CREATED, performed, Jackson.marshaller());
+ });
+ })));
+ }
+
+ public static void main(String[] args) throws Exception {
+ ActorSystem system = ActorSystem.create("userServer");
+ ActorRef userActor = system.actorOf(UserActor.props(), "userActor");
+ UserServer server = new UserServer(userActor);
+ server.startServer("localhost", 8080, system);
+ }
+
+}
diff --git a/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java b/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java
new file mode 100644
index 0000000000..50dc1e1b28
--- /dev/null
+++ b/akka-http/src/main/java/com/baeldung/akkahttp/UserService.java
@@ -0,0 +1,35 @@
+package com.baeldung.akkahttp;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+public class UserService {
+
+ private final static List users = new ArrayList<>();
+
+ static {
+ users.add(new User(1l, "Alice"));
+ users.add(new User(2l, "Bob"));
+ users.add(new User(3l, "Chris"));
+ users.add(new User(4l, "Dick"));
+ users.add(new User(5l, "Eve"));
+ users.add(new User(6l, "Finn"));
+ }
+
+ public Optional getUser(Long id) {
+ return users.stream()
+ .filter(user -> user.getId()
+ .equals(id))
+ .findFirst();
+ }
+
+ public void createUser(User user) {
+ users.add(user);
+ }
+
+ public List getUsers(){
+ return users;
+ }
+
+}
diff --git a/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java
new file mode 100644
index 0000000000..1170a2d761
--- /dev/null
+++ b/akka-http/src/test/java/com/baeldung/akkahttp/UserServerUnitTest.java
@@ -0,0 +1,50 @@
+package com.baeldung.akkahttp;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.http.javadsl.model.ContentTypes;
+import akka.http.javadsl.model.HttpEntities;
+import akka.http.javadsl.model.HttpRequest;
+import akka.http.javadsl.testkit.JUnitRouteTest;
+import akka.http.javadsl.testkit.TestRoute;
+import org.junit.Test;
+
+public class UserServerUnitTest extends JUnitRouteTest {
+
+ ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
+
+ ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor");
+
+ TestRoute appRoute = testRoute(new UserServer(userActorRef).routes());
+
+ @Test
+ public void whenRequest_thenActorResponds() {
+
+ appRoute.run(HttpRequest.GET("/users/1"))
+ .assertEntity(alice())
+ .assertStatusCode(200);
+
+ appRoute.run(HttpRequest.GET("/users/42"))
+ .assertStatusCode(404);
+
+ appRoute.run(HttpRequest.DELETE("/users/1"))
+ .assertStatusCode(200);
+
+ appRoute.run(HttpRequest.DELETE("/users/42"))
+ .assertStatusCode(200);
+
+ appRoute.run(HttpRequest.POST("/users")
+ .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod())))
+ .assertStatusCode(201);
+
+ }
+
+ private String alice() {
+ return "{\"id\":1,\"name\":\"Alice\"}";
+ }
+
+ private String zaphod() {
+ return "{\"id\":42,\"name\":\"Zaphod\"}";
+ }
+
+}
diff --git a/algorithms-genetic/README.md b/algorithms-genetic/README.md
index 0f68918fff..39f8d59eee 100644
--- a/algorithms-genetic/README.md
+++ b/algorithms-genetic/README.md
@@ -1,4 +1,6 @@
## Relevant articles:
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
-- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
\ No newline at end of file
+- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
+- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
+- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
diff --git a/algorithms-genetic/pom.xml b/algorithms-genetic/pom.xml
index 2a10a81980..56f6a31525 100644
--- a/algorithms-genetic/pom.xml
+++ b/algorithms-genetic/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldungalgorithms-genetic0.0.1-SNAPSHOT
-
+ algorithms-genetic
+
com.baeldungparent-modules
@@ -54,11 +54,11 @@
- 1.16.123.6.13.7.03.9.01.11
-
\ No newline at end of file
+
+
diff --git a/algorithms-genetic/roundUpToHundred/.gitignore b/algorithms-genetic/roundUpToHundred/.gitignore
deleted file mode 100644
index ae3c172604..0000000000
--- a/algorithms-genetic/roundUpToHundred/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin/
diff --git a/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
deleted file mode 100644
index 6c02a340d3..0000000000
--- a/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.java.src;
-
-import java.util.Scanner;
-
-public class RoundUpToHundred {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- double input = scanner.nextDouble();
- scanner.close();
-
- RoundUpToHundred.round(input);
- }
-
- static long round(double input) {
- long i = (long) Math.ceil(input);
- return ((i + 99) / 100) * 100;
- };
-
-}
diff --git a/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
deleted file mode 100644
index cb541ad49c..0000000000
--- a/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.java.src;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class RoundUpToHundredTest {
- @Test
- public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
- assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
- assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
- assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
- }
-}
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
index ce04d26db3..779cb9b970 100644
--- a/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
+++ b/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -5,7 +5,6 @@ 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 {
@@ -13,11 +12,8 @@ public class RunAlgorithm {
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");
- System.out.println("6 - All pairs in an array that add up to a given sum");
+ System.out.println("2 - Simple Genetic Algorithm");
+ System.out.println("3 - Ant Colony");
int decision = in.nextInt();
switch (decision) {
case 1:
@@ -25,19 +21,13 @@ public class RunAlgorithm {
"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:
+ case 3:
AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization();
break;
- case 5:
- System.out.println("Please run the DijkstraAlgorithmTest.");
- break;
default:
System.out.println("Unknown option");
break;
diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md
index 9efb2233bf..ea6d6f379b 100644
--- a/algorithms-miscellaneous-1/README.md
+++ b/algorithms-miscellaneous-1/README.md
@@ -9,4 +9,12 @@
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
-- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
\ No newline at end of file
+- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
+- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
+- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
+- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
+- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
+- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
+- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
+- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
+- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml
index 16749d452e..30130208f8 100644
--- a/algorithms-miscellaneous-1/pom.xml
+++ b/algorithms-miscellaneous-1/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldungalgorithms-miscellaneous-10.0.1-SNAPSHOT
-
+ algorithms-miscellaneous-1
+
com.baeldungparent-modules
@@ -17,6 +17,11 @@
commons-math3${commons-math3.version}
+
+ com.google.guava
+ guava
+ ${guava.version}
+ commons-codeccommons-codec
@@ -34,6 +39,11 @@
${org.assertj.core.version}test
+
+ com.github.dpaukov
+ combinatoricslib3
+ 3.3.0
+
@@ -69,10 +79,10 @@
- 1.16.123.6.13.9.01.11
+ 27.0.1-jre
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/roundUpToHundred/.gitignore b/algorithms-miscellaneous-1/roundUpToHundred/.gitignore
deleted file mode 100644
index ae3c172604..0000000000
--- a/algorithms-miscellaneous-1/roundUpToHundred/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin/
diff --git a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
deleted file mode 100644
index cb541ad49c..0000000000
--- a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.java.src;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class RoundUpToHundredTest {
- @Test
- public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
- assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
- assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
- assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
- }
-}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java
new file mode 100644
index 0000000000..40142ce940
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/ApacheCommonsCombinationGenerator.java
@@ -0,0 +1,29 @@
+package com.baeldung.algorithms.combination;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+import org.apache.commons.math3.util.CombinatoricsUtils;
+
+public class ApacheCommonsCombinationGenerator {
+
+ private static final int N = 6;
+ private static final int R = 3;
+
+ /**
+ * Print all combinations of r elements from a set
+ * @param n - number of elements in set
+ * @param r - number of elements in selection
+ */
+ public static void generate(int n, int r) {
+ Iterator iterator = CombinatoricsUtils.combinationsIterator(n, r);
+ while (iterator.hasNext()) {
+ final int[] combination = iterator.next();
+ System.out.println(Arrays.toString(combination));
+ }
+ }
+
+ public static void main(String[] args) {
+ generate(N, R);
+ }
+}
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java
new file mode 100644
index 0000000000..0afdeefb8b
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/CombinatoricsLibCombinationGenerator.java
@@ -0,0 +1,13 @@
+package com.baeldung.algorithms.combination;
+
+import org.paukov.combinatorics3.Generator;
+
+public class CombinatoricsLibCombinationGenerator {
+
+ public static void main(String[] args) {
+ Generator.combination(0, 1, 2, 3, 4, 5)
+ .simple(3)
+ .stream()
+ .forEach(System.out::println);
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java
new file mode 100644
index 0000000000..d2783881ba
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/GuavaCombinationsGenerator.java
@@ -0,0 +1,17 @@
+package com.baeldung.algorithms.combination;
+
+import java.util.Arrays;
+import java.util.Set;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+
+public class GuavaCombinationsGenerator {
+
+ public static void main(String[] args) {
+
+ Set> combinations = Sets.combinations(ImmutableSet.of(0, 1, 2, 3, 4, 5), 3);
+ System.out.println(combinations.size());
+ System.out.println(Arrays.toString(combinations.toArray()));
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java
new file mode 100644
index 0000000000..676d2f41e3
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/IterativeCombinationGenerator.java
@@ -0,0 +1,52 @@
+package com.baeldung.algorithms.combination;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class IterativeCombinationGenerator {
+
+ private static final int N = 5;
+ private static final int R = 2;
+
+ /**
+ * Generate all combinations of r elements from a set
+ * @param n the number of elements in input set
+ * @param r the number of elements in a combination
+ * @return the list containing all combinations
+ */
+ public List generate(int n, int r) {
+ List combinations = new ArrayList<>();
+ int[] combination = new int[r];
+
+ // initialize with lowest lexicographic combination
+ for (int i = 0; i < r; i++) {
+ combination[i] = i;
+ }
+
+ while (combination[r - 1] < n) {
+ combinations.add(combination.clone());
+
+ // generate next combination in lexicographic order
+ int t = r - 1;
+ while (t != 0 && combination[t] == n - r + t) {
+ t--;
+ }
+ combination[t]++;
+ for (int i = t + 1; i < r; i++) {
+ combination[i] = combination[i - 1] + 1;
+ }
+ }
+
+ return combinations;
+ }
+
+ public static void main(String[] args) {
+ IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
+ List combinations = generator.generate(N, R);
+ System.out.println(combinations.size());
+ for (int[] combination : combinations) {
+ System.out.println(Arrays.toString(combination));
+ }
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java
new file mode 100644
index 0000000000..52305b8c2f
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SelectionRecursiveCombinationGenerator.java
@@ -0,0 +1,53 @@
+package com.baeldung.algorithms.combination;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class SelectionRecursiveCombinationGenerator {
+
+ private static final int N = 6;
+ private static final int R = 3;
+
+ /**
+ * Generate all combinations of r elements from a set
+ * @param n - number of elements in input set
+ * @param r - number of elements to be chosen
+ * @return the list containing all combinations
+ */
+ public List generate(int n, int r) {
+ List combinations = new ArrayList<>();
+ helper(combinations, new int[r], 0, n - 1, 0);
+ return combinations;
+ }
+
+ /**
+ * Choose elements from set by recursing over elements selected
+ * @param combinations - List to store generated combinations
+ * @param data - current combination
+ * @param start - starting element of remaining set
+ * @param end - last element of remaining set
+ * @param index - number of elements chosen so far.
+ */
+ private void helper(List combinations, int data[], int start, int end, int index) {
+ if (index == data.length) {
+ int[] combination = data.clone();
+ combinations.add(combination);
+ } else {
+ int max = Math.min(end, end + 1 - data.length + index);
+ for (int i = start; i <= max; i++) {
+ data[index] = i;
+ helper(combinations, data, i + 1, end, index + 1);
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
+ List combinations = generator.generate(N, R);
+ for (int[] combination : combinations) {
+ System.out.println(Arrays.toString(combination));
+ }
+ System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java
new file mode 100644
index 0000000000..a73447b31d
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/combination/SetRecursiveCombinationGenerator.java
@@ -0,0 +1,50 @@
+package com.baeldung.algorithms.combination;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class SetRecursiveCombinationGenerator {
+
+ private static final int N = 5;
+ private static final int R = 2;
+
+ /**
+ * Generate all combinations of r elements from a set
+ * @param n - number of elements in set
+ * @param r - number of elements in selection
+ * @return the list containing all combinations
+ */
+ public List generate(int n, int r) {
+ List combinations = new ArrayList<>();
+ helper(combinations, new int[r], 0, n-1, 0);
+ return combinations;
+ }
+
+ /**
+ * @param combinations - List to contain the generated combinations
+ * @param data - List of elements in the selection
+ * @param start - index of the starting element in the remaining set
+ * @param end - index of the last element in the set
+ * @param index - number of elements selected so far
+ */
+ private void helper(List combinations, int data[], int start, int end, int index) {
+ if (index == data.length) {
+ int[] combination = data.clone();
+ combinations.add(combination);
+ } else if (start <= end) {
+ data[index] = start;
+ helper(combinations, data, start + 1, end, index + 1);
+ helper(combinations, data, start + 1, end, index);
+ }
+ }
+
+ public static void main(String[] args) {
+ SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
+ List combinations = generator.generate(N, R);
+ for (int[] combination : combinations) {
+ System.out.println(Arrays.toString(combination));
+ }
+ System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
new file mode 100644
index 0000000000..5153c2e18e
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
@@ -0,0 +1,46 @@
+package com.baeldung.algorithms.enumstatemachine;
+
+public enum LeaveRequestState {
+
+ Submitted {
+ @Override
+ public LeaveRequestState nextState() {
+ System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
+ return Escalated;
+ }
+
+ @Override
+ public String responsiblePerson() {
+ return "Employee";
+ }
+ },
+ Escalated {
+ @Override
+ public LeaveRequestState nextState() {
+ System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
+ return Approved;
+ }
+
+ @Override
+ public String responsiblePerson() {
+ return "Team Leader";
+ }
+ },
+ Approved {
+ @Override
+ public LeaveRequestState nextState() {
+ System.out.println("Approving the Leave Request.");
+ return this;
+ }
+
+ @Override
+ public String responsiblePerson() {
+ return "Department Manager";
+ }
+ };
+
+ public abstract String responsiblePerson();
+
+ public abstract LeaveRequestState nextState();
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java
new file mode 100644
index 0000000000..43d2221773
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java
@@ -0,0 +1,63 @@
+package com.baeldung.algorithms.factorial;
+
+import java.math.BigInteger;
+import java.util.stream.LongStream;
+
+import org.apache.commons.math3.util.CombinatoricsUtils;
+
+import com.google.common.math.BigIntegerMath;
+
+public class Factorial {
+
+ public long factorialUsingForLoop(int n) {
+ long fact = 1;
+ for (int i = 2; i <= n; i++) {
+ fact = fact * i;
+ }
+ return fact;
+ }
+
+ public long factorialUsingStreams(int n) {
+ return LongStream.rangeClosed(1, n)
+ .reduce(1, (long x, long y) -> x * y);
+ }
+
+ public long factorialUsingRecursion(int n) {
+ if (n <= 2) {
+ return n;
+ }
+ return n * factorialUsingRecursion(n - 1);
+ }
+
+ private Long[] factorials = new Long[20];
+
+ public long factorialUsingMemoize(int n) {
+
+ if (factorials[n] != null) {
+ return factorials[n];
+ }
+
+ if (n <= 2) {
+ return n;
+ }
+ long nthValue = n * factorialUsingMemoize(n - 1);
+ factorials[n] = nthValue;
+ return nthValue;
+ }
+
+ public BigInteger factorialHavingLargeResult(int n) {
+ BigInteger result = BigInteger.ONE;
+ for (int i = 2; i <= n; i++)
+ result = result.multiply(BigInteger.valueOf(i));
+ return result;
+ }
+
+ public long factorialUsingApacheCommons(int n) {
+ return CombinatoricsUtils.factorial(n);
+ }
+
+ public BigInteger factorialUsingGuava(int n) {
+ return BigIntegerMath.factorial(n);
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java
new file mode 100644
index 0000000000..7fedd78ffb
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/permutation/Permutation.java
@@ -0,0 +1,123 @@
+package com.baeldung.algorithms.permutation;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+public class Permutation {
+
+ public static void printAllRecursive(T[] elements, char delimiter) {
+ printAllRecursive(elements.length, elements, delimiter);
+ }
+
+ public static void printAllRecursive(int n, T[] elements, char delimiter) {
+
+ if(n == 1) {
+ printArray(elements, delimiter);
+ } else {
+ for(int i = 0; i < n-1; i++) {
+ printAllRecursive(n - 1, elements, delimiter);
+ if(n % 2 == 0) {
+ swap(elements, i, n-1);
+ } else {
+ swap(elements, 0, n-1);
+ }
+ }
+ printAllRecursive(n - 1, elements, delimiter);
+ }
+ }
+
+ public static void printAllIterative(int n, T[] elements, char delimiter) {
+
+ int[] indexes = new int[n];
+ for (int i = 0; i < n; i++) {
+ indexes[i] = 0;
+ }
+
+ printArray(elements, delimiter);
+
+ int i = 0;
+ while (i < n) {
+ if (indexes[i] < i) {
+ swap(elements, i % 2 == 0 ? 0: indexes[i], i);
+ printArray(elements, delimiter);
+ indexes[i]++;
+ i = 0;
+ }
+ else {
+ indexes[i] = 0;
+ i++;
+ }
+ }
+ }
+
+ public static > void printAllOrdered(T[] elements, char delimiter) {
+
+ Arrays.sort(elements);
+ boolean hasNext = true;
+
+ while(hasNext) {
+ printArray(elements, delimiter);
+ int k = 0, l = 0;
+ hasNext = false;
+ for (int i = elements.length - 1; i > 0; i--) {
+ if (elements[i].compareTo(elements[i - 1]) > 0) {
+ k = i - 1;
+ hasNext = true;
+ break;
+ }
+ }
+
+ for (int i = elements.length - 1; i > k; i--) {
+ if (elements[i].compareTo(elements[k]) > 0) {
+ l = i;
+ break;
+ }
+ }
+
+ swap(elements, k, l);
+ Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length));
+ }
+ }
+
+ public static void printRandom(T[] elements, char delimiter) {
+
+ Collections.shuffle(Arrays.asList(elements));
+ printArray(elements, delimiter);
+ }
+
+ private static void swap(T[] elements, int a, int b) {
+
+ T tmp = elements[a];
+ elements[a] = elements[b];
+ elements[b] = tmp;
+ }
+
+ private static void printArray(T[] elements, char delimiter) {
+
+ String delimiterSpace = delimiter + " ";
+ for(int i = 0; i < elements.length; i++) {
+ System.out.print(elements[i] + delimiterSpace);
+ }
+ System.out.print('\n');
+ }
+
+ public static void main(String[] argv) {
+
+ Integer[] elements = {1,2,3,4};
+
+ System.out.println("Rec:");
+ printAllRecursive(elements, ';');
+
+ System.out.println("Iter:");
+ printAllIterative(elements.length, elements, ';');
+
+ System.out.println("Orderes:");
+ printAllOrdered(elements, ';');
+
+ System.out.println("Random:");
+ printRandom(elements, ';');
+
+ System.out.println("Random:");
+ printRandom(elements, ';');
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java
new file mode 100644
index 0000000000..cd1f3e94d5
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java
@@ -0,0 +1,54 @@
+package com.baeldung.algorithms.string;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+public class LongestSubstringNonRepeatingCharacters {
+
+ public static String getUniqueCharacterSubstringBruteForce(String input) {
+ String output = "";
+ for (int start = 0; start < input.length(); start++) {
+ Set visited = new HashSet<>();
+ int end = start;
+ for (; end < input.length(); end++) {
+ char currChar = input.charAt(end);
+ if (visited.contains(currChar)) {
+ break;
+ } else {
+ visited.add(currChar);
+ }
+ }
+ if (output.length() < end - start + 1) {
+ output = input.substring(start, end);
+ }
+ }
+ return output;
+ }
+
+ public static String getUniqueCharacterSubstring(String input) {
+ Map visited = new HashMap<>();
+ String output = "";
+ for (int start = 0, end = 0; end < input.length(); end++) {
+ char currChar = input.charAt(end);
+ if (visited.containsKey(currChar)) {
+ start = Math.max(visited.get(currChar) + 1, start);
+ }
+ if (output.length() < end - start + 1) {
+ output = input.substring(start, end + 1);
+ }
+ visited.put(currChar, end);
+ }
+ return output;
+ }
+
+ public static void main(String[] args) {
+ if(args.length > 0) {
+ System.out.println(getUniqueCharacterSubstring(args[0]));
+ } else {
+ System.err.println("This program expects command-line input. Please try again!");
+ }
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java
new file mode 100644
index 0000000000..b3d142eb07
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/SubstringPalindrome.java
@@ -0,0 +1,90 @@
+package com.baeldung.algorithms.string;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class SubstringPalindrome {
+
+ public Set findAllPalindromesUsingCenter(String input) {
+ final Set palindromes = new HashSet<>();
+ if (input == null || input.isEmpty()) {
+ return palindromes;
+ }
+ if (input.length() == 1) {
+ palindromes.add(input);
+ return palindromes;
+ }
+ for (int i = 0; i < input.length(); i++) {
+ palindromes.addAll(findPalindromes(input, i, i + 1));
+ palindromes.addAll(findPalindromes(input, i, i));
+ }
+ return palindromes;
+ }
+
+ private Set findPalindromes(String input, int low, int high) {
+ Set result = new HashSet<>();
+ while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
+ result.add(input.substring(low, high + 1));
+ low--;
+ high++;
+ }
+ return result;
+ }
+
+ public Set findAllPalindromesUsingBruteForceApproach(String input) {
+ Set palindromes = new HashSet<>();
+ if (input == null || input.isEmpty()) {
+ return palindromes;
+ }
+ if (input.length() == 1) {
+ palindromes.add(input);
+ return palindromes;
+ }
+ for (int i = 0; i < input.length(); i++) {
+ for (int j = i + 1; j <= input.length(); j++)
+ if (isPalindrome(input.substring(i, j))) {
+ palindromes.add(input.substring(i, j));
+ }
+ }
+ return palindromes;
+ }
+
+ private boolean isPalindrome(String input) {
+ StringBuilder plain = new StringBuilder(input);
+ StringBuilder reverse = plain.reverse();
+ return (reverse.toString()).equals(input);
+ }
+
+ public Set findAllPalindromesUsingManachersAlgorithm(String input) {
+ Set palindromes = new HashSet<>();
+ String formattedInput = "@" + input + "#";
+ char inputCharArr[] = formattedInput.toCharArray();
+ int max;
+ int radius[][] = new int[2][input.length() + 1];
+ for (int j = 0; j <= 1; j++) {
+ radius[j][0] = max = 0;
+ int i = 1;
+ while (i <= input.length()) {
+ palindromes.add(Character.toString(inputCharArr[i]));
+ while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
+ max++;
+ radius[j][i] = max;
+ int k = 1;
+ while ((radius[j][i - k] != max - k) && (k < max)) {
+ radius[j][i + k] = Math.min(radius[j][i - k], max - k);
+ k++;
+ }
+ max = Math.max(max - k, 0);
+ i += k;
+ }
+ }
+ for (int i = 1; i <= input.length(); i++) {
+ for (int j = 0; j <= 1; j++) {
+ for (max = radius[j][i]; max > 0; max--) {
+ palindromes.add(input.substring(i - max - 1, max + j + i - 1));
+ }
+ }
+ }
+ return palindromes;
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java
new file mode 100644
index 0000000000..a7031f4fba
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java
@@ -0,0 +1,16 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+public class LinkedListFindMiddle {
+
+ public T findMiddle(MyNode head) {
+ MyNode slowPointer = head;
+ MyNode fastPointer = head;
+
+ while (fastPointer.next != null && fastPointer.next.next != null) {
+ fastPointer = fastPointer.next.next;
+ slowPointer = slowPointer.next;
+ }
+ return slowPointer.data;
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java
new file mode 100644
index 0000000000..7d93f03ef9
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java
@@ -0,0 +1,20 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+public class MyNode {
+ MyNode next;
+ E data;
+
+ public MyNode(E value) {
+ data = value;
+ next = null;
+ }
+
+ public MyNode(E value, MyNode n) {
+ data = value;
+ next = n;
+ }
+
+ public void setNext(MyNode n) {
+ next = n;
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java
new file mode 100644
index 0000000000..b4e3698c01
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java
@@ -0,0 +1,22 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+public class RotateArray {
+
+ public void rotate(int[] input, int step) {
+ step %= input.length;
+ reverse(input, 0, input.length - 1);
+ reverse(input, 0, step - 1);
+ reverse(input, step, input.length - 1);
+ }
+
+ private void reverse(int[] input, int start, int end) {
+ while (start < end) {
+ int temp = input[start];
+ input[start] = input[end];
+ input[end] = temp;
+ start++;
+ end--;
+ }
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java
new file mode 100644
index 0000000000..14eceaa1bd
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java
@@ -0,0 +1,38 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+public class TwoSum {
+
+ public boolean twoSum(int[] input, int targetValue) {
+
+ int pointerOne = 0;
+ int pointerTwo = input.length - 1;
+
+ while (pointerOne < pointerTwo) {
+ int sum = input[pointerOne] + input[pointerTwo];
+
+ if (sum == targetValue) {
+ return true;
+ } else if (sum < targetValue) {
+ pointerOne++;
+ } else {
+ pointerTwo--;
+ }
+ }
+
+ return false;
+ }
+
+ public boolean twoSumSlow(int[] input, int targetValue) {
+
+ for (int i = 0; i < input.length; i++) {
+ for (int j = 1; j < input.length; j++) {
+ if (input[i] + input[j] == targetValue) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt b/algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt
deleted file mode 100644
index 8b48c325d2..0000000000
--- a/algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-S ########
-# #
-# ### ## #
-# # # #
-# # # # #
-# ## #####
-# # #
-# # # # #
-##### ####
-# # E
-# # # #
-##########
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt b/algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt
deleted file mode 100644
index df5b6bc66b..0000000000
--- a/algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-S ##########################
-# # # #
-# # #### ############### #
-# # # # # #
-# # #### # # ###############
-# # # # # # #
-# # # #### ### ########### #
-# # # # # #
-# ################## #
-######### # # # # #
-# # #### # ####### # #
-# # ### ### # # # # #
-# # ## # ##### # #
-##### ####### # # # # #
-# # ## ## #### # #
-# ##### ####### # #
-# # ############
-####### ######### # #
-# # ######## #
-# ####### ###### ## # E
-# # # ## #
-############################
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java
new file mode 100644
index 0000000000..987b6ddae6
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/combination/CombinationUnitTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.algorithms.combination;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.List;
+
+import org.junit.Test;
+
+public class CombinationUnitTest {
+
+ private static final int N = 5;
+ private static final int R = 3;
+ private static final int nCr = 10;
+
+ @Test
+ public void givenSetAndSelectionSize_whenCalculatedUsingSetRecursiveAlgorithm_thenExpectedCount() {
+ SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
+ List selection = generator.generate(N, R);
+ assertEquals(nCr, selection.size());
+ }
+
+ @Test
+ public void givenSetAndSelectionSize_whenCalculatedUsingSelectionRecursiveAlgorithm_thenExpectedCount() {
+ SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
+ List selection = generator.generate(N, R);
+ assertEquals(nCr, selection.size());
+ }
+
+ @Test
+ public void givenSetAndSelectionSize_whenCalculatedUsingIterativeAlgorithm_thenExpectedCount() {
+ IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
+ List selection = generator.generate(N, R);
+ assertEquals(nCr, selection.size());
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
new file mode 100644
index 0000000000..61ed6b3aec
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.algorithms.enumstatemachine;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class LeaveRequestStateUnitTest {
+
+ @Test
+ public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
+ LeaveRequestState state = LeaveRequestState.Escalated;
+
+ assertEquals(state.responsiblePerson(), "Team Leader");
+ }
+
+
+ @Test
+ public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
+ LeaveRequestState state = LeaveRequestState.Approved;
+
+ assertEquals(state.responsiblePerson(), "Department Manager");
+ }
+
+ @Test
+ public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
+ LeaveRequestState state = LeaveRequestState.Submitted;
+
+ state = state.nextState();
+ assertEquals(state, LeaveRequestState.Escalated);
+
+ state = state.nextState();
+ assertEquals(state, LeaveRequestState.Approved);
+
+ state = state.nextState();
+ assertEquals(state, LeaveRequestState.Approved);
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java
new file mode 100644
index 0000000000..c185dba62b
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java
@@ -0,0 +1,72 @@
+package com.baeldung.algorithms.factorial;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.math.BigInteger;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class FactorialUnitTest {
+
+ Factorial factorial;
+
+ @Before
+ public void setup() {
+ factorial = new Factorial();
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingForLoop_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingStreams_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingRecursion_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingMemoize_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120);
+
+ n = 6;
+
+ assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720);
+ }
+
+ @Test
+ public void whenCalculatingFactorialHavingLargeResult_thenCorrect() {
+ int n = 22;
+
+ assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000"));
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingGuava_thenCorrect() {
+ int n = 22;
+
+ assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000"));
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java
new file mode 100644
index 0000000000..9f1e6a2519
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.algorithms.string;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
+import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
+
+public class LongestSubstringNonRepeatingCharactersUnitTest {
+
+ @Test
+ void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
+ assertEquals("", getUniqueCharacterSubstringBruteForce(""));
+ assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
+ assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
+ assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
+ }
+
+ @Test
+ void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
+ assertEquals("", getUniqueCharacterSubstring(""));
+ assertEquals("A", getUniqueCharacterSubstring("A"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
+ assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
+ assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java
new file mode 100644
index 0000000000..8d225f67fa
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/SubstringPalindromeUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.algorithms.string;
+
+import static org.junit.Assert.assertEquals;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.Test;
+
+public class SubstringPalindromeUnitTest {
+
+ private static final String INPUT_BUBBLE = "bubble";
+ private static final String INPUT_CIVIC = "civic";
+ private static final String INPUT_INDEED = "indeed";
+ private static final String INPUT_ABABAC = "ababac";
+
+ Set EXPECTED_PALINDROME_BUBBLE = new HashSet() {
+ {
+ add("b");
+ add("u");
+ add("l");
+ add("e");
+ add("bb");
+ add("bub");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_CIVIC = new HashSet() {
+ {
+ add("civic");
+ add("ivi");
+ add("i");
+ add("c");
+ add("v");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_INDEED = new HashSet() {
+ {
+ add("i");
+ add("n");
+ add("d");
+ add("e");
+ add("ee");
+ add("deed");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_ABABAC = new HashSet() {
+ {
+ add("a");
+ add("b");
+ add("c");
+ add("aba");
+ add("bab");
+ add("ababa");
+ }
+ };
+
+ private SubstringPalindrome palindrome = new SubstringPalindrome();
+
+ @Test
+ public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
+ }
+
+ @Test
+ public void whenUsingCenterApproach_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
+ }
+
+ @Test
+ public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
+ }
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java
new file mode 100644
index 0000000000..422a53fa3e
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class LinkedListFindMiddleUnitTest {
+
+ LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle();
+
+ @Test
+ public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
+
+ MyNode head = createNodesList(8);
+
+ assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("4");
+
+ head = createNodesList(9);
+
+ assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("5");
+ }
+
+ private static MyNode createNodesList(int n) {
+
+ MyNode head = new MyNode("1");
+ MyNode current = head;
+
+ for (int i = 2; i <= n; i++) {
+ MyNode newNode = new MyNode(String.valueOf(i));
+ current.setNext(newNode);
+ current = newNode;
+ }
+
+ return head;
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java
new file mode 100644
index 0000000000..da227ae751
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+public class RotateArrayUnitTest {
+
+ private RotateArray rotateArray = new RotateArray();
+
+ private int[] inputArray;
+
+ private int step;
+
+ @Test
+ public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
+
+ inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
+ step = 4;
+
+ rotateArray.rotate(inputArray, step);
+
+ assertThat(inputArray).containsExactly(new int[] { 4, 5, 6, 7, 1, 2, 3 });
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java
new file mode 100644
index 0000000000..aa76f8e1cf
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.algorithms.twopointertechnique;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class TwoSumUnitTest {
+
+ private TwoSum twoSum = new TwoSum();
+
+ private int[] sortedArray;
+
+ private int targetValue;
+
+ @Test
+ public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
+
+ sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
+
+ targetValue = 12;
+
+ assertTrue(twoSum.twoSumSlow(sortedArray, targetValue));
+ }
+
+ @Test
+ public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
+
+ sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
+
+ targetValue = 20;
+
+ assertFalse(twoSum.twoSumSlow(sortedArray, targetValue));
+ }
+
+ @Test
+ public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
+
+ sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
+
+ targetValue = 12;
+
+ assertTrue(twoSum.twoSum(sortedArray, targetValue));
+ }
+
+ @Test
+ public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
+
+ sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
+
+ targetValue = 20;
+
+ assertFalse(twoSum.twoSum(sortedArray, targetValue));
+ }
+
+}
diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md
index 2634fd6b56..d693a44f66 100644
--- a/algorithms-miscellaneous-2/README.md
+++ b/algorithms-miscellaneous-2/README.md
@@ -10,7 +10,6 @@
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
-- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
@@ -18,3 +17,4 @@
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
+- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml
index eeae544612..e85dd456a3 100644
--- a/algorithms-miscellaneous-2/pom.xml
+++ b/algorithms-miscellaneous-2/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungalgorithms-miscellaneous-20.0.1-SNAPSHOT
+ algorithms-miscellaneous-2com.baeldung
@@ -33,6 +33,11 @@
jgrapht-core${org.jgrapht.core.version}
+
+ org.jgrapht
+ jgrapht-ext
+ ${org.jgrapht.ext.version}
+ pl.allegro.financetradukisto
@@ -63,7 +68,7 @@
org.codehaus.mojocobertura-maven-plugin
- 2.7
+ ${cobertura-maven-plugin.version}
@@ -79,12 +84,13 @@
- 1.16.123.6.11.0.11.0.1
+ 1.0.13.9.01.11
+ 2.7
\ No newline at end of file
diff --git a/algorithms-miscellaneous-2/roundUpToHundred/.gitignore b/algorithms-miscellaneous-2/roundUpToHundred/.gitignore
deleted file mode 100644
index ae3c172604..0000000000
--- a/algorithms-miscellaneous-2/roundUpToHundred/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin/
diff --git a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
deleted file mode 100644
index 6c02a340d3..0000000000
--- a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.java.src;
-
-import java.util.Scanner;
-
-public class RoundUpToHundred {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- double input = scanner.nextDouble();
- scanner.close();
-
- RoundUpToHundred.round(input);
- }
-
- static long round(double input) {
- long i = (long) Math.ceil(input);
- return ((i + 99) / 100) * 100;
- };
-
-}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
new file mode 100644
index 0000000000..a1a096bc30
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -0,0 +1,28 @@
+package com.baeldung.algorithms;
+
+import java.util.Scanner;
+
+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("1 - Slope One");
+ System.out.println("2 - Dijkstra");
+ int decision = in.nextInt();
+ switch (decision) {
+ case 1:
+ SlopeOne.slopeOne(3);
+ break;
+ case 2:
+ System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
+ break;
+ default:
+ System.out.println("Unknown option");
+ break;
+ }
+ in.close();
+ }
+
+}
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java
new file mode 100644
index 0000000000..e1c41f9518
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java
@@ -0,0 +1,22 @@
+package com.baeldung.algorithms.mercator;
+
+class EllipticalMercator extends Mercator {
+
+ @Override
+ double yAxisProjection(double input) {
+
+ input = Math.min(Math.max(input, -89.5), 89.5);
+ double earthDimensionalRateNormalized = 1.0 - Math.pow(RADIUS_MINOR / RADIUS_MAJOR, 2);
+
+ double inputOnEarthProj = Math.sqrt(earthDimensionalRateNormalized) * Math.sin( Math.toRadians(input));
+
+ inputOnEarthProj = Math.pow(((1.0 - inputOnEarthProj)/(1.0+inputOnEarthProj)), 0.5 * Math.sqrt(earthDimensionalRateNormalized));
+ double inputOnEarthProjNormalized = Math.tan(0.5 * ((Math.PI*0.5) - Math.toRadians(input)))/inputOnEarthProj;
+ return (-1) * RADIUS_MAJOR * Math.log(inputOnEarthProjNormalized);
+ }
+
+ @Override
+ double xAxisProjection(double input) {
+ return RADIUS_MAJOR * Math.toRadians(input);
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java
new file mode 100644
index 0000000000..b289b1839d
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java
@@ -0,0 +1,10 @@
+package com.baeldung.algorithms.mercator;
+
+abstract class Mercator {
+ final static double RADIUS_MAJOR = 6378137.0;
+ final static double RADIUS_MINOR = 6356752.3142;
+
+ abstract double yAxisProjection(double input);
+
+ abstract double xAxisProjection(double input);
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java
new file mode 100644
index 0000000000..1be976d82e
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java
@@ -0,0 +1,14 @@
+package com.baeldung.algorithms.mercator;
+
+public class SphericalMercator extends Mercator {
+
+ @Override
+ double xAxisProjection(double input) {
+ return Math.toRadians(input) * RADIUS_MAJOR;
+ }
+
+ @Override
+ double yAxisProjection(double input) {
+ return Math.log(Math.tan(Math.PI / 4 + Math.toRadians(input) / 2)) * RADIUS_MAJOR;
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java
new file mode 100644
index 0000000000..7905b752a9
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java
@@ -0,0 +1,42 @@
+package com.baeldung.algorithms.reversingtree;
+
+public class TreeNode {
+
+ private int value;
+ private TreeNode rightChild;
+ private TreeNode leftChild;
+
+ public int getValue() {
+ return value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public TreeNode getRightChild() {
+ return rightChild;
+ }
+
+ public void setRightChild(TreeNode rightChild) {
+ this.rightChild = rightChild;
+ }
+
+ public TreeNode getLeftChild() {
+ return leftChild;
+ }
+
+ public void setLeftChild(TreeNode leftChild) {
+ this.leftChild = leftChild;
+ }
+
+ public TreeNode(int value, TreeNode rightChild, TreeNode leftChild) {
+ this.value = value;
+ this.rightChild = rightChild;
+ this.leftChild = leftChild;
+ }
+
+ public TreeNode(int value) {
+ this.value = value;
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java
new file mode 100644
index 0000000000..6d3a9ddd31
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java
@@ -0,0 +1,68 @@
+package com.baeldung.algorithms.reversingtree;
+
+import java.util.LinkedList;
+
+public class TreeReverser {
+
+ public TreeNode createBinaryTree() {
+
+ TreeNode leaf1 = new TreeNode(3);
+ TreeNode leaf2 = new TreeNode(1);
+ TreeNode leaf3 = new TreeNode(9);
+ TreeNode leaf4 = new TreeNode(6);
+
+ TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
+ TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
+
+ TreeNode root = new TreeNode(4, nodeRight, nodeLeft);
+
+ return root;
+ }
+
+ public void reverseRecursive(TreeNode treeNode) {
+ if (treeNode == null) {
+ return;
+ }
+
+ TreeNode temp = treeNode.getLeftChild();
+ treeNode.setLeftChild(treeNode.getRightChild());
+ treeNode.setRightChild(temp);
+
+ reverseRecursive(treeNode.getLeftChild());
+ reverseRecursive(treeNode.getRightChild());
+ }
+
+ public void reverseIterative(TreeNode treeNode) {
+ LinkedList queue = new LinkedList();
+
+ if (treeNode != null) {
+ queue.add(treeNode);
+ }
+
+ while (!queue.isEmpty()) {
+
+ TreeNode node = queue.poll();
+ if (node.getLeftChild() != null)
+ queue.add(node.getLeftChild());
+ if (node.getRightChild() != null)
+ queue.add(node.getRightChild());
+
+ TreeNode temp = node.getLeftChild();
+ node.setLeftChild(node.getRightChild());
+ node.setRightChild(temp);
+ }
+ }
+
+ public String toString(TreeNode root) {
+ if (root == null) {
+ return "";
+ }
+
+ StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
+
+ buffer.append(toString(root.getLeftChild()));
+ buffer.append(toString(root.getRightChild()));
+
+ return buffer.toString();
+ }
+}
diff --git a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java
similarity index 90%
rename from algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java
index 6c02a340d3..333019e294 100644
--- a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/roundedup/RoundUpToHundred.java
@@ -1,4 +1,4 @@
-package com.java.src;
+package com.baeldung.algorithms.roundedup;
import java.util.Scanner;
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/Item.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/Item.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/Item.java
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
diff --git a/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/User.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/User.java
similarity index 100%
rename from algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/User.java
rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/slope_one/User.java
diff --git a/algorithms-genetic/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
similarity index 100%
rename from algorithms-genetic/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java
new file mode 100644
index 0000000000..96b644c46c
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.algorithms.mercator;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+
+public class EllipticalMercatorUnitTest {
+
+ @Test
+ public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
+ Mercator mercator = new EllipticalMercator();
+ double result = mercator.xAxisProjection(22);
+ Assert.assertEquals(result, 2449028.7974520186, 0.0);
+ }
+
+ @Test
+ public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
+ Mercator mercator = new EllipticalMercator();
+ double result = mercator.yAxisProjection(44);
+ Assert.assertEquals(result, 5435749.887511954, 0.0);
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java
new file mode 100644
index 0000000000..348c6ad3e4
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.algorithms.mercator;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SphericalMercatorUnitTest {
+
+ @Test
+ public void giventThatTheInputIs22_whenXAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
+ Mercator mercator = new SphericalMercator();
+ double result = mercator.xAxisProjection(22);
+ Assert.assertEquals(result, 2449028.7974520186, 0.0);
+ }
+
+ @Test
+ public void giventThatTheInputIs44_whenYAxisProjectionIsCalled_thenTheResultIsTheCorrectOne() {
+ Mercator mercator = new SphericalMercator();
+ double result = mercator.yAxisProjection(44);
+ Assert.assertEquals(result, 5465442.183322753, 0.0);
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java
new file mode 100644
index 0000000000..cbc265fae1
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.algorithms.reversingtree;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class TreeReverserUnitTest {
+
+ @Test
+ public void givenTreeWhenReversingRecursivelyThenReversed() {
+ TreeReverser reverser = new TreeReverser();
+
+ TreeNode treeNode = reverser.createBinaryTree();
+
+ reverser.reverseRecursive(treeNode);
+
+ assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
+ .trim());
+ }
+
+ @Test
+ public void givenTreeWhenReversingIterativelyThenReversed() {
+ TreeReverser reverser = new TreeReverser();
+
+ TreeNode treeNode = reverser.createBinaryTree();
+
+ reverser.reverseIterative(treeNode);
+
+ assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
+ .trim());
+ }
+
+}
diff --git a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java
similarity index 83%
rename from algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java
index cb541ad49c..5191d65787 100644
--- a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/roundedup/RoundUpToHundredUnitTest.java
@@ -1,10 +1,10 @@
-package com.java.src;
+package com.baeldung.algorithms.roundedup;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
-public class RoundUpToHundredTest {
+public class RoundUpToHundredUnitTest {
@Test
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
new file mode 100644
index 0000000000..3b841d574a
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.jgrapht;
+
+import static org.junit.Assert.assertTrue;
+import java.awt.Color;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import javax.imageio.ImageIO;
+import org.jgrapht.ext.JGraphXAdapter;
+import org.jgrapht.graph.DefaultDirectedGraph;
+import org.jgrapht.graph.DefaultEdge;
+import org.junit.Before;
+import org.junit.Test;
+import com.mxgraph.layout.mxCircleLayout;
+import com.mxgraph.layout.mxIGraphLayout;
+import com.mxgraph.util.mxCellRenderer;
+
+public class GraphImageGenerationUnitTest {
+ static DefaultDirectedGraph g;
+
+ @Before
+ public void createGraph() throws IOException {
+ File imgFile = new File("src/test/resources/graph.png");
+ imgFile.createNewFile();
+ g = new DefaultDirectedGraph(DefaultEdge.class);
+ String x1 = "x1";
+ String x2 = "x2";
+ String x3 = "x3";
+ g.addVertex(x1);
+ g.addVertex(x2);
+ g.addVertex(x3);
+ g.addEdge(x1, x2);
+ g.addEdge(x2, x3);
+ g.addEdge(x3, x1);
+ }
+
+ @Test
+ public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
+ JGraphXAdapter graphAdapter = new JGraphXAdapter(g);
+ mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
+ layout.execute(graphAdapter.getDefaultParent());
+ File imgFile = new File("src/test/resources/graph.png");
+ BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
+ ImageIO.write(image, "PNG", imgFile);
+ assertTrue(imgFile.exists());
+ }
+}
\ No newline at end of file
diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png
new file mode 100644
index 0000000000..7165a51782
Binary files /dev/null and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ
diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md
index f88b93e25e..36460293b0 100644
--- a/algorithms-sorting/README.md
+++ b/algorithms-sorting/README.md
@@ -4,4 +4,4 @@
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
-
+- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml
index 60ae37f2a4..b25adf05a8 100644
--- a/algorithms-sorting/pom.xml
+++ b/algorithms-sorting/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungalgorithms-sorting0.0.1-SNAPSHOT
+ algorithms-sortingcom.baeldung
@@ -49,7 +49,6 @@
- 1.16.123.6.13.9.01.11
diff --git a/algorithms-sorting/roundUpToHundred/.gitignore b/algorithms-sorting/roundUpToHundred/.gitignore
deleted file mode 100644
index ae3c172604..0000000000
--- a/algorithms-sorting/roundUpToHundred/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin/
diff --git a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
deleted file mode 100644
index 6c02a340d3..0000000000
--- a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.java.src;
-
-import java.util.Scanner;
-
-public class RoundUpToHundred {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- double input = scanner.nextDouble();
- scanner.close();
-
- RoundUpToHundred.round(input);
- }
-
- static long round(double input) {
- long i = (long) Math.ceil(input);
- return ((i + 99) / 100) * 100;
- };
-
-}
diff --git a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
deleted file mode 100644
index cb541ad49c..0000000000
--- a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.java.src;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class RoundUpToHundredTest {
- @Test
- public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
- assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
- assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
- assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
- }
-}
diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
index 0deb48b6a0..945b4ffd7e 100644
--- a/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
+++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
@@ -34,7 +34,7 @@ public class MergeSort {
while (i < left && j < right) {
- if (l[i] < r[j])
+ if (l[i] <= r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml
index cdfb1fb2a3..55e37e2ec4 100644
--- a/animal-sniffer-mvn-plugin/pom.xml
+++ b/animal-sniffer-mvn-plugin/pom.xml
@@ -3,9 +3,9 @@
4.0.0com.baeldunganimal-sniffer-mvn-plugin
- jar1.0-SNAPSHOTanimal-sniffer-mvn-plugin
+ jarhttp://maven.apache.org
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index 8e53334521..d9aca6040d 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0annotation-processing
-
+ annotation-processing
+
com.baeldung1.0.0-SNAPSHOT
diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml
index 07ea9a5b5a..422cc7f119 100644
--- a/annotations/annotation-user/pom.xml
+++ b/annotations/annotation-user/pom.xml
@@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0annotation-user
+ annotation-userannotations
diff --git a/annotations/pom.xml b/annotations/pom.xml
index 2c73d3d91b..5fe89adf0a 100644
--- a/annotations/pom.xml
+++ b/annotations/pom.xml
@@ -3,8 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0annotations
+ annotationspom
-
+
parent-modulescom.baeldung
diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml
index ddf5844271..5d170f0a81 100644
--- a/apache-avro/pom.xml
+++ b/apache-avro/pom.xml
@@ -3,19 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldungapache-avro0.0.1-SNAPSHOT
- Apache Avro
+ apache-avro
-
- UTF-8
- 3.5
- 1.8.2
- 1.8
- 1.7.25
-
-
com.baeldungparent-modules
@@ -86,4 +77,12 @@
+
+
+ UTF-8
+ 3.5
+ 1.8.2
+ 1.7.25
+
+
diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml
index 5ddb1ecb59..786f587fb1 100644
--- a/apache-bval/pom.xml
+++ b/apache-bval/pom.xml
@@ -4,7 +4,8 @@
apache-bvalapache-bval0.0.1-SNAPSHOT
-
+ apache-bval
+
com.baeldungparent-modules
diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml
index ac10811e7a..259319d547 100644
--- a/apache-curator/pom.xml
+++ b/apache-curator/pom.xml
@@ -3,6 +3,7 @@
4.0.0apache-curator0.0.1-SNAPSHOT
+ apache-curatorjar
@@ -38,7 +39,7 @@
com.fasterxml.jackson.corejackson-databind
- ${jackson-databind.version}
+ ${jackson.version}
@@ -58,7 +59,6 @@
4.0.13.4.11
- 2.9.43.6.11.7.0
diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml
index b7e9e426a2..1d36178b82 100644
--- a/apache-cxf/cxf-aegis/pom.xml
+++ b/apache-cxf/cxf-aegis/pom.xml
@@ -2,7 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0cxf-aegis
-
+ cxf-aegis
+
com.baeldungapache-cxf
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
index a9e82c16b3..17f03afd25 100644
--- a/apache-cxf/cxf-introduction/pom.xml
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -4,7 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0cxf-introduction
-
+ cxf-introduction
+
com.baeldungapache-cxf
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
index 89acbdf1bd..03d0f67c90 100644
--- a/apache-cxf/cxf-jaxrs-implementation/pom.xml
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -4,7 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0cxf-jaxrs-implementation
-
+ cxf-jaxrs-implementation
+
com.baeldungapache-cxf
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
index 31e75e7cdd..97715af54c 100644
--- a/apache-cxf/cxf-spring/pom.xml
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -3,6 +3,7 @@
4.0.0cxf-springwar
+ cxf-springcom.baeldung
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 8918fd4450..0016f33d70 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungapache-cxf0.0.1-SNAPSHOT
+ apache-cxfpom
diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml
index d4b6c19d03..cb5c96660a 100644
--- a/apache-cxf/sse-jaxrs/pom.xml
+++ b/apache-cxf/sse-jaxrs/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
sse-jaxrs
+ sse-jaxrspom
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
index 0f5406fbc7..c7acf22c32 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -3,15 +3,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
+ sse-jaxrs-client
+ sse-jaxrs-client
+
com.baeldungsse-jaxrs0.0.1-SNAPSHOT
- sse-jaxrs-client
-
3.2.0
@@ -21,7 +21,6 @@
org.codehaus.mojoexec-maven-plugin
- 1.6.0singleEvent
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
index 2e82dc3829..eeb5726ee1 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -3,16 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
+ sse-jaxrs-server
+ sse-jaxrs-server
+ war
+
com.baeldungsse-jaxrs0.0.1-SNAPSHOT
- sse-jaxrs-server
- war
-
2.4.2false
diff --git a/apache-fop/README.md b/apache-fop/README.md
index 772681ad57..1e734a5f36 100644
--- a/apache-fop/README.md
+++ b/apache-fop/README.md
@@ -3,7 +3,3 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
-- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
-- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
-- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
-
diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml
index a3f6604ac4..15c7e04d29 100644
--- a/apache-geode/pom.xml
+++ b/apache-geode/pom.xml
@@ -3,32 +3,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
- com.baeldungapache-geode1.0-SNAPSHOT
-
+ apache-geode
+
com.baeldungparent-modules1.0.0-SNAPSHOT
-
-
- 1.6.0
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- 1.8
- 1.8
-
-
-
-
@@ -39,8 +22,24 @@
junitjunit
- RELEASE
+ ${junit.version}
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ ${java.version}
+ ${java.version}
+
+
+
+
+
+
+ 1.6.0
+
\ No newline at end of file
diff --git a/apache-meecrowave/pom.xml b/apache-meecrowave/pom.xml
index cf13aa1c1b..fb5af69f9b 100644
--- a/apache-meecrowave/pom.xml
+++ b/apache-meecrowave/pom.xml
@@ -7,51 +7,58 @@
apache-meecrowaveA sample REST API application with Meecrowave
-
- 1.8
- 1.8
- org.apache.meecrowavemeecrowave-core
- 1.2.1
+ ${meecrowave-core.version}org.apache.meecrowavemeecrowave-jpa
- 1.2.1
+ ${meecrowave-jpa.version}com.squareup.okhttp3okhttp
- 3.10.0
+ ${okhttp.version}org.apache.meecrowavemeecrowave-junit
- 1.2.0
+ ${meecrowave-junit.version}testjunitjunit
- 4.10
+ ${junit.version}test
-
+
org.apache.meecrowavemeecrowave-maven-plugin
- 1.2.1
+ ${meecrowave-maven-plugin.version}
+
+
+ 1.8
+ 1.8
+ 4.10
+ 1.2.0
+ 3.10.0
+ 1.2.1
+ 1.2.1
+ 1.2.1
+
\ No newline at end of file
diff --git a/apache-opennlp/pom.xml b/apache-opennlp/pom.xml
index 985c9a2df2..6b2e6a9729 100644
--- a/apache-opennlp/pom.xml
+++ b/apache-opennlp/pom.xml
@@ -4,6 +4,7 @@
4.0.0apache-opennlp1.0-SNAPSHOT
+ apache-opennlpjar
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index a1ec626d43..54c3e8e928 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungapache-poi0.0.1-SNAPSHOT
+ apache-poicom.baeldung
diff --git a/apache-pulsar/README.md b/apache-pulsar/README.md
new file mode 100644
index 0000000000..2970bc3d88
--- /dev/null
+++ b/apache-pulsar/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+
+- [Introduction to Apache Pulsar](https://www.baeldung.com/apache-pulsar)
diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml
index da004a7638..11df6d0b87 100644
--- a/apache-pulsar/pom.xml
+++ b/apache-pulsar/pom.xml
@@ -1,21 +1,24 @@
- 4.0.0
- com.baeldung.pulsar
- pulsar-java
- 0.0.1
+ 4.0.0
+ com.baeldung.pulsar
+ apache-pulsar
+ 0.0.1
+ apache-pulsar
-
-
- org.apache.pulsar
- pulsar-client
- 2.1.1-incubating
- compile
-
-
-
- 1.8
- 1.8
-
+
+
+ org.apache.pulsar
+ pulsar-client
+ ${pulsar-client.version}
+ compile
+
+
+
+
+ 1.8
+ 1.8
+ 2.1.1-incubating
+
diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml
index 98d9563284..644d70b30a 100644
--- a/apache-shiro/pom.xml
+++ b/apache-shiro/pom.xml
@@ -5,7 +5,8 @@
4.0.0apache-shiro1.0-SNAPSHOT
-
+ apache-shiro
+
parent-boot-1com.baeldung
diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml
index 9a807c2f26..1227fdca46 100644
--- a/apache-solrj/pom.xml
+++ b/apache-solrj/pom.xml
@@ -4,8 +4,8 @@
com.baeldungapache-solrj0.0.1-SNAPSHOT
- jarapache-solrj
+ jarcom.baeldung
diff --git a/apache-spark/README.md b/apache-spark/README.md
index fb8059eb27..a4dce212b4 100644
--- a/apache-spark/README.md
+++ b/apache-spark/README.md
@@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)
+- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)
diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml
index 290b63a14d..f0f002a7e9 100644
--- a/apache-spark/pom.xml
+++ b/apache-spark/pom.xml
@@ -4,8 +4,8 @@
com.baeldungapache-spark1.0-SNAPSHOT
- jarapache-spark
+ jarhttp://maven.apache.org
@@ -15,16 +15,77 @@
-
org.apache.spark
- spark-core_2.10
+ spark-core_2.11${org.apache.spark.spark-core.version}
+ provided
+
+ org.apache.spark
+ spark-sql_2.11
+ ${org.apache.spark.spark-sql.version}
+ provided
+
+
+ org.apache.spark
+ spark-streaming_2.11
+ ${org.apache.spark.spark-streaming.version}
+ provided
+
+
+ org.apache.spark
+ spark-streaming-kafka-0-10_2.11
+ ${org.apache.spark.spark-streaming-kafka.version}
+
+
+ com.datastax.spark
+ spark-cassandra-connector_2.11
+ ${com.datastax.spark.spark-cassandra-connector.version}
+
+
+ com.datastax.spark
+ spark-cassandra-connector-java_2.11
+ ${com.datastax.spark.spark-cassandra-connector-java.version}
+
-
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${java.version}
+ ${java.version}
+
+
+
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+
+
+
+ jar-with-dependencies
+
+
+
+
+
- 2.2.0
+ 2.3.0
+ 2.3.0
+ 2.3.0
+ 2.3.0
+ 2.3.0
+ 1.5.2
+ 3.2
diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java
new file mode 100644
index 0000000000..b0caa468b1
--- /dev/null
+++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/Word.java
@@ -0,0 +1,25 @@
+package com.baeldung.data.pipeline;
+
+import java.io.Serializable;
+
+public class Word implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private String word;
+ private int count;
+ Word(String word, int count) {
+ this.word = word;
+ this.count = count;
+ }
+ public String getWord() {
+ return word;
+ }
+ public void setWord(String word) {
+ this.word = word;
+ }
+ public int getCount() {
+ return count;
+ }
+ public void setCount(int count) {
+ this.count = count;
+ }
+}
\ No newline at end of file
diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java
new file mode 100644
index 0000000000..db2a73b411
--- /dev/null
+++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingApp.java
@@ -0,0 +1,80 @@
+package com.baeldung.data.pipeline;
+
+import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions;
+import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.spark.SparkConf;
+import org.apache.spark.api.java.JavaRDD;
+import org.apache.spark.streaming.Durations;
+import org.apache.spark.streaming.api.java.JavaDStream;
+import org.apache.spark.streaming.api.java.JavaInputDStream;
+import org.apache.spark.streaming.api.java.JavaPairDStream;
+import org.apache.spark.streaming.api.java.JavaStreamingContext;
+import org.apache.spark.streaming.kafka010.ConsumerStrategies;
+import org.apache.spark.streaming.kafka010.KafkaUtils;
+import org.apache.spark.streaming.kafka010.LocationStrategies;
+
+import scala.Tuple2;
+
+public class WordCountingApp {
+
+ public static void main(String[] args) throws InterruptedException {
+ Logger.getLogger("org")
+ .setLevel(Level.OFF);
+ Logger.getLogger("akka")
+ .setLevel(Level.OFF);
+
+ Map kafkaParams = new HashMap<>();
+ kafkaParams.put("bootstrap.servers", "localhost:9092");
+ kafkaParams.put("key.deserializer", StringDeserializer.class);
+ kafkaParams.put("value.deserializer", StringDeserializer.class);
+ kafkaParams.put("group.id", "use_a_separate_group_id_for_each_stream");
+ kafkaParams.put("auto.offset.reset", "latest");
+ kafkaParams.put("enable.auto.commit", false);
+
+ Collection topics = Arrays.asList("messages");
+
+ SparkConf sparkConf = new SparkConf();
+ sparkConf.setMaster("local[2]");
+ sparkConf.setAppName("WordCountingApp");
+ sparkConf.set("spark.cassandra.connection.host", "127.0.0.1");
+
+ JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1));
+
+ JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams));
+
+ JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
+
+ JavaDStream lines = results.map(tuple2 -> tuple2._2());
+
+ JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
+ .iterator());
+
+ JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
+ .reduceByKey((i1, i2) -> i1 + i2);
+
+ wordCounts.foreachRDD(javaRdd -> {
+ Map wordCountMap = javaRdd.collectAsMap();
+ for (String key : wordCountMap.keySet()) {
+ List wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
+ JavaRDD rdd = streamingContext.sparkContext()
+ .parallelize(wordList);
+ javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
+ .saveToCassandra();
+ }
+ });
+
+ streamingContext.start();
+ streamingContext.awaitTermination();
+ }
+}
\ No newline at end of file
diff --git a/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java
new file mode 100644
index 0000000000..efbe5f3851
--- /dev/null
+++ b/apache-spark/src/main/java/com/baeldung/data/pipeline/WordCountingAppWithCheckpoint.java
@@ -0,0 +1,97 @@
+package com.baeldung.data.pipeline;
+
+import static com.datastax.spark.connector.japi.CassandraJavaUtil.javaFunctions;
+import static com.datastax.spark.connector.japi.CassandraJavaUtil.mapToRow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.spark.SparkConf;
+import org.apache.spark.api.java.JavaRDD;
+import org.apache.spark.api.java.JavaSparkContext;
+import org.apache.spark.api.java.function.Function2;
+import org.apache.spark.streaming.Durations;
+import org.apache.spark.streaming.StateSpec;
+import org.apache.spark.streaming.api.java.JavaDStream;
+import org.apache.spark.streaming.api.java.JavaInputDStream;
+import org.apache.spark.streaming.api.java.JavaMapWithStateDStream;
+import org.apache.spark.streaming.api.java.JavaPairDStream;
+import org.apache.spark.streaming.api.java.JavaStreamingContext;
+import org.apache.spark.streaming.kafka010.ConsumerStrategies;
+import org.apache.spark.streaming.kafka010.KafkaUtils;
+import org.apache.spark.streaming.kafka010.LocationStrategies;
+
+import scala.Tuple2;
+
+public class WordCountingAppWithCheckpoint {
+
+ public static JavaSparkContext sparkContext;
+
+ public static void main(String[] args) throws InterruptedException {
+
+ Logger.getLogger("org")
+ .setLevel(Level.OFF);
+ Logger.getLogger("akka")
+ .setLevel(Level.OFF);
+
+ Map kafkaParams = new HashMap<>();
+ kafkaParams.put("bootstrap.servers", "localhost:9092");
+ kafkaParams.put("key.deserializer", StringDeserializer.class);
+ kafkaParams.put("value.deserializer", StringDeserializer.class);
+ kafkaParams.put("group.id", "use_a_separate_group_id_for_each_stream");
+ kafkaParams.put("auto.offset.reset", "latest");
+ kafkaParams.put("enable.auto.commit", false);
+
+ Collection topics = Arrays.asList("messages");
+
+ SparkConf sparkConf = new SparkConf();
+ sparkConf.setMaster("local[2]");
+ sparkConf.setAppName("WordCountingAppWithCheckpoint");
+ sparkConf.set("spark.cassandra.connection.host", "127.0.0.1");
+
+ JavaStreamingContext streamingContext = new JavaStreamingContext(sparkConf, Durations.seconds(1));
+
+ sparkContext = streamingContext.sparkContext();
+
+ streamingContext.checkpoint("./.checkpoint");
+
+ JavaInputDStream> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies. Subscribe(topics, kafkaParams));
+
+ JavaPairDStream results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
+
+ JavaDStream lines = results.map(tuple2 -> tuple2._2());
+
+ JavaDStream words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
+ .iterator());
+
+ JavaPairDStream wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
+ .reduceByKey((Function2) (i1, i2) -> i1 + i2);
+
+ JavaMapWithStateDStream> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
+ int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
+ Tuple2 output = new Tuple2<>(word, sum);
+ state.update(sum);
+ return output;
+ }));
+
+ cumulativeWordCounts.foreachRDD(javaRdd -> {
+ List> wordCountList = javaRdd.collect();
+ for (Tuple2 tuple : wordCountList) {
+ List wordList = Arrays.asList(new Word(tuple._1, tuple._2));
+ JavaRDD rdd = sparkContext.parallelize(wordList);
+ javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
+ .saveToCassandra();
+ }
+ });
+
+ streamingContext.start();
+ streamingContext.awaitTermination();
+ }
+}
\ No newline at end of file
diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml
index b22364cb19..ab54fc2cef 100644
--- a/apache-thrift/pom.xml
+++ b/apache-thrift/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungapache-thrift0.0.1-SNAPSHOT
+ apache-thriftpom
diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml
index 5a76fdeeda..0399914a5f 100644
--- a/apache-tika/pom.xml
+++ b/apache-tika/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldungapache-tika0.0.1-SNAPSHOT
-
+ apache-tika
+
com.baeldungparent-modules
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
index 19cf77d945..a0a8389f7d 100644
--- a/apache-velocity/pom.xml
+++ b/apache-velocity/pom.xml
@@ -4,8 +4,8 @@
com.baeldung0.1-SNAPSHOTapache-velocity
- warapache-velocity
+ warcom.baeldung
diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml
index 0b29186ccc..53e4217358 100644
--- a/apache-zookeeper/pom.xml
+++ b/apache-zookeeper/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldungapache-zookeeper0.0.1-SNAPSHOT
+ apache-zookeeperjar
diff --git a/asm/pom.xml b/asm/pom.xml
index 5aad2a0e37..e56438c808 100644
--- a/asm/pom.xml
+++ b/asm/pom.xml
@@ -5,6 +5,7 @@
com.baeldung.examplesasm1.0
+ asmjar
diff --git a/atomix/pom.xml b/atomix/pom.xml
index f85d2d7484..e50c1d867f 100644
--- a/atomix/pom.xml
+++ b/atomix/pom.xml
@@ -4,7 +4,8 @@
com.atomix.ioatomix0.0.1-SNAPSHOT
-
+ atomix
+
com.baeldungparent-modules
diff --git a/aws-lambda/pom.xml b/aws-lambda/pom.xml
index c47c3cd86f..c799718e61 100644
--- a/aws-lambda/pom.xml
+++ b/aws-lambda/pom.xml
@@ -5,8 +5,8 @@
com.baeldungaws-lambda0.1.0-SNAPSHOT
- jaraws-lambda
+ jarparent-modules
diff --git a/aws/README.md b/aws/README.md
index 2c61928095..d14ea8a75e 100644
--- a/aws/README.md
+++ b/aws/README.md
@@ -4,7 +4,6 @@
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
-- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
diff --git a/aws/pom.xml b/aws/pom.xml
index ab63f6afa1..560f9145f9 100644
--- a/aws/pom.xml
+++ b/aws/pom.xml
@@ -4,8 +4,8 @@
com.baeldungaws0.1.0-SNAPSHOT
- jaraws
+ jarcom.baeldung
diff --git a/axon/pom.xml b/axon/pom.xml
index 915a04feb5..2b9ac1fcdd 100644
--- a/axon/pom.xml
+++ b/axon/pom.xml
@@ -3,29 +3,62 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0axon
+ axon
+ Basic Axon Framework with Spring Boot configuration tutorial
- parent-modulescom.baeldung
- 1.0.0-SNAPSHOT
+ parent-boot-2
+ 0.0.1-SNAPSHOT
+ ../parent-boot-2
+
+ org.axonframework
+ axon-spring-boot-starter
+ ${axon.version}
+
+
+ org.axonframework
+ axon-server-connector
+
+
+
+
org.axonframeworkaxon-test${axon.version}test
+
- org.axonframework
- axon-core
- ${axon.version}
+ org.springframework.boot
+ spring-boot-autoconfigure
+ ${spring-boot.version}
+ compile
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ com.h2database
+ h2
+ runtime
- 3.0.2
+ 4.0.3
\ 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
deleted file mode 100644
index 77b50d09bd..0000000000
--- a/axon/src/main/java/com/baeldung/axon/MessagesRunner.java
+++ /dev/null
@@ -1,54 +0,0 @@
-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/OrderApplication.java b/axon/src/main/java/com/baeldung/axon/OrderApplication.java
new file mode 100644
index 0000000000..8f507e141c
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/OrderApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.axon;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class OrderApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(OrderApplication.class, args);
+ }
+
+}
\ 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
deleted file mode 100644
index e762604b74..0000000000
--- a/axon/src/main/java/com/baeldung/axon/aggregates/MessagesAggregate.java
+++ /dev/null
@@ -1,36 +0,0 @@
-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/commandmodel/OrderAggregate.java b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java
new file mode 100644
index 0000000000..b37b2fdd66
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/commandmodel/OrderAggregate.java
@@ -0,0 +1,58 @@
+package com.baeldung.axon.commandmodel;
+
+import static org.axonframework.modelling.command.AggregateLifecycle.apply;
+
+import org.axonframework.commandhandling.CommandHandler;
+import org.axonframework.eventsourcing.EventSourcingHandler;
+import org.axonframework.modelling.command.AggregateIdentifier;
+import org.axonframework.spring.stereotype.Aggregate;
+
+import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
+import com.baeldung.axon.coreapi.commands.PlaceOrderCommand;
+import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
+import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
+import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
+import com.baeldung.axon.coreapi.events.OrderShippedEvent;
+
+@Aggregate
+public class OrderAggregate {
+
+ @AggregateIdentifier
+ private String orderId;
+ private boolean orderConfirmed;
+
+ @CommandHandler
+ public OrderAggregate(PlaceOrderCommand command) {
+ apply(new OrderPlacedEvent(command.getOrderId(), command.getProduct()));
+ }
+
+ @CommandHandler
+ public void handle(ConfirmOrderCommand command) {
+ apply(new OrderConfirmedEvent(orderId));
+ }
+
+ @CommandHandler
+ public void handle(ShipOrderCommand command) {
+ if (!orderConfirmed) {
+ throw new IllegalStateException("Cannot ship an order which has not been confirmed yet.");
+ }
+
+ apply(new OrderShippedEvent(orderId));
+ }
+
+ @EventSourcingHandler
+ public void on(OrderPlacedEvent event) {
+ this.orderId = event.getOrderId();
+ orderConfirmed = false;
+ }
+
+ @EventSourcingHandler
+ public void on(OrderConfirmedEvent event) {
+ orderConfirmed = true;
+ }
+
+ protected OrderAggregate() {
+ // Required by Axon to build a default Aggregate prior to Event Sourcing
+ }
+
+}
\ 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
deleted file mode 100644
index d0651bf12e..0000000000
--- a/axon/src/main/java/com/baeldung/axon/commands/CreateMessageCommand.java
+++ /dev/null
@@ -1,24 +0,0 @@
-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
deleted file mode 100644
index e66582d9ec..0000000000
--- a/axon/src/main/java/com/baeldung/axon/commands/MarkReadMessageCommand.java
+++ /dev/null
@@ -1,18 +0,0 @@
-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/coreapi/commands/ConfirmOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java
new file mode 100644
index 0000000000..244b69f3b7
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java
@@ -0,0 +1,43 @@
+package com.baeldung.axon.coreapi.commands;
+
+import org.axonframework.modelling.command.TargetAggregateIdentifier;
+
+import java.util.Objects;
+
+public class ConfirmOrderCommand {
+
+ @TargetAggregateIdentifier
+ private final String orderId;
+
+ public ConfirmOrderCommand(String orderId) {
+ this.orderId = orderId;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final ConfirmOrderCommand other = (ConfirmOrderCommand) obj;
+ return Objects.equals(this.orderId, other.orderId);
+ }
+
+ @Override
+ public String toString() {
+ return "ConfirmOrderCommand{" +
+ "orderId='" + orderId + '\'' +
+ '}';
+ }
+}
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java
new file mode 100644
index 0000000000..c70d503050
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/PlaceOrderCommand.java
@@ -0,0 +1,51 @@
+package com.baeldung.axon.coreapi.commands;
+
+import java.util.Objects;
+
+import org.axonframework.modelling.command.TargetAggregateIdentifier;
+
+public class PlaceOrderCommand {
+
+ @TargetAggregateIdentifier
+ private final String orderId;
+ private final String product;
+
+ public PlaceOrderCommand(String orderId, String product) {
+ this.orderId = orderId;
+ this.product = product;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ public String getProduct() {
+ return product;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId, product);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final PlaceOrderCommand other = (PlaceOrderCommand) obj;
+ return Objects.equals(this.orderId, other.orderId)
+ && Objects.equals(this.product, other.product);
+ }
+
+ @Override
+ public String toString() {
+ return "PlaceOrderCommand{" +
+ "orderId='" + orderId + '\'' +
+ ", product='" + product + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java
new file mode 100644
index 0000000000..7312bc1fdb
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java
@@ -0,0 +1,43 @@
+package com.baeldung.axon.coreapi.commands;
+
+import java.util.Objects;
+
+import org.axonframework.modelling.command.TargetAggregateIdentifier;
+
+public class ShipOrderCommand {
+
+ @TargetAggregateIdentifier
+ private final String orderId;
+
+ public ShipOrderCommand(String orderId) {
+ this.orderId = orderId;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final ShipOrderCommand other = (ShipOrderCommand) obj;
+ return Objects.equals(this.orderId, other.orderId);
+ }
+
+ @Override
+ public String toString() {
+ return "ShipOrderCommand{" +
+ "orderId='" + orderId + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java
new file mode 100644
index 0000000000..d2b7d58435
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java
@@ -0,0 +1,40 @@
+package com.baeldung.axon.coreapi.events;
+
+import java.util.Objects;
+
+public class OrderConfirmedEvent {
+
+ private final String orderId;
+
+ public OrderConfirmedEvent(String orderId) {
+ this.orderId = orderId;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final OrderConfirmedEvent other = (OrderConfirmedEvent) obj;
+ return Objects.equals(this.orderId, other.orderId);
+ }
+
+ @Override
+ public String toString() {
+ return "OrderConfirmedEvent{" +
+ "orderId='" + orderId + '\'' +
+ '}';
+ }
+}
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java
new file mode 100644
index 0000000000..06de4c5f9f
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderPlacedEvent.java
@@ -0,0 +1,48 @@
+package com.baeldung.axon.coreapi.events;
+
+import java.util.Objects;
+
+public class OrderPlacedEvent {
+
+ private final String orderId;
+ private final String product;
+
+ public OrderPlacedEvent(String orderId, String product) {
+ this.orderId = orderId;
+ this.product = product;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ public String getProduct() {
+ return product;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId, product);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final OrderPlacedEvent other = (OrderPlacedEvent) obj;
+ return Objects.equals(this.orderId, other.orderId)
+ && Objects.equals(this.product, other.product);
+ }
+
+ @Override
+ public String toString() {
+ return "OrderPlacedEvent{" +
+ "orderId='" + orderId + '\'' +
+ ", product='" + product + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java
new file mode 100644
index 0000000000..76aa684629
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java
@@ -0,0 +1,40 @@
+package com.baeldung.axon.coreapi.events;
+
+import java.util.Objects;
+
+public class OrderShippedEvent {
+
+ private final String orderId;
+
+ public OrderShippedEvent(String orderId) {
+ this.orderId = orderId;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final OrderShippedEvent other = (OrderShippedEvent) obj;
+ return Objects.equals(this.orderId, other.orderId);
+ }
+
+ @Override
+ public String toString() {
+ return "OrderShippedEvent{" +
+ "orderId='" + orderId + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java
new file mode 100644
index 0000000000..9d6ca2cfb2
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java
@@ -0,0 +1,5 @@
+package com.baeldung.axon.coreapi.queries;
+
+public class FindAllOrderedProductsQuery {
+
+}
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java
new file mode 100644
index 0000000000..d215c5fc32
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java
@@ -0,0 +1,7 @@
+package com.baeldung.axon.coreapi.queries;
+
+public enum OrderStatus {
+
+ PLACED, CONFIRMED, SHIPPED
+
+}
diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java
new file mode 100644
index 0000000000..d847bb2a98
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderedProduct.java
@@ -0,0 +1,64 @@
+package com.baeldung.axon.coreapi.queries;
+
+import java.util.Objects;
+
+public class OrderedProduct {
+
+ private final String orderId;
+ private final String product;
+ private OrderStatus orderStatus;
+
+ public OrderedProduct(String orderId, String product) {
+ this.orderId = orderId;
+ this.product = product;
+ orderStatus = OrderStatus.PLACED;
+ }
+
+ public String getOrderId() {
+ return orderId;
+ }
+
+ public String getProduct() {
+ return product;
+ }
+
+ public OrderStatus getOrderStatus() {
+ return orderStatus;
+ }
+
+ public void setOrderConfirmed() {
+ this.orderStatus = OrderStatus.CONFIRMED;
+ }
+
+ public void setOrderShipped() {
+ this.orderStatus = OrderStatus.SHIPPED;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(orderId, product, orderStatus);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null || getClass() != obj.getClass()) {
+ return false;
+ }
+ final OrderedProduct other = (OrderedProduct) obj;
+ return Objects.equals(this.orderId, other.orderId)
+ && Objects.equals(this.product, other.product)
+ && Objects.equals(this.orderStatus, other.orderStatus);
+ }
+
+ @Override
+ public String toString() {
+ return "OrderedProduct{" +
+ "orderId='" + orderId + '\'' +
+ ", product='" + product + '\'' +
+ ", orderStatus=" + orderStatus +
+ '}';
+ }
+}
diff --git a/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java b/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java
deleted file mode 100644
index 3e51e19c4e..0000000000
--- a/axon/src/main/java/com/baeldung/axon/eventhandlers/MessagesEventHandler.java
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index 3c9aac5ed8..0000000000
--- a/axon/src/main/java/com/baeldung/axon/events/MessageCreatedEvent.java
+++ /dev/null
@@ -1,20 +0,0 @@
-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
deleted file mode 100644
index 57bfc8e19e..0000000000
--- a/axon/src/main/java/com/baeldung/axon/events/MessageReadEvent.java
+++ /dev/null
@@ -1,14 +0,0 @@
-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/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java b/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java
new file mode 100644
index 0000000000..a9f34cc691
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java
@@ -0,0 +1,52 @@
+package com.baeldung.axon.gui;
+
+import java.util.List;
+import java.util.UUID;
+
+import org.axonframework.commandhandling.gateway.CommandGateway;
+import org.axonframework.messaging.responsetypes.ResponseTypes;
+import org.axonframework.queryhandling.QueryGateway;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
+import com.baeldung.axon.coreapi.commands.PlaceOrderCommand;
+import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
+import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
+import com.baeldung.axon.coreapi.queries.OrderedProduct;
+
+@RestController
+public class OrderRestEndpoint {
+
+ private final CommandGateway commandGateway;
+ private final QueryGateway queryGateway;
+
+ public OrderRestEndpoint(CommandGateway commandGateway, QueryGateway queryGateway) {
+ this.commandGateway = commandGateway;
+ this.queryGateway = queryGateway;
+ }
+
+ @PostMapping("/ship-order")
+ public void shipOrder() {
+ String orderId = UUID.randomUUID().toString();
+ commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair"));
+ commandGateway.send(new ConfirmOrderCommand(orderId));
+ commandGateway.send(new ShipOrderCommand(orderId));
+ }
+
+ @PostMapping("/ship-unconfirmed-order")
+ public void shipUnconfirmedOrder() {
+ String orderId = UUID.randomUUID().toString();
+ commandGateway.send(new PlaceOrderCommand(orderId, "Deluxe Chair"));
+ // This throws an exception, as an Order cannot be shipped if it has not been confirmed yet.
+ commandGateway.send(new ShipOrderCommand(orderId));
+ }
+
+ @GetMapping("/all-orders")
+ public List findAllOrderedProducts() {
+ return queryGateway.query(new FindAllOrderedProductsQuery(), ResponseTypes.multipleInstancesOf(OrderedProduct.class))
+ .join();
+ }
+
+}
diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java
new file mode 100644
index 0000000000..d4cf3d999b
--- /dev/null
+++ b/axon/src/main/java/com/baeldung/axon/querymodel/OrderedProductsEventHandler.java
@@ -0,0 +1,50 @@
+package com.baeldung.axon.querymodel;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.axonframework.eventhandling.EventHandler;
+import org.axonframework.queryhandling.QueryHandler;
+import org.springframework.stereotype.Service;
+
+import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
+import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
+import com.baeldung.axon.coreapi.events.OrderShippedEvent;
+import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
+import com.baeldung.axon.coreapi.queries.OrderedProduct;
+
+@Service
+public class OrderedProductsEventHandler {
+
+ private final Map orderedProducts = new HashMap<>();
+
+ @EventHandler
+ public void on(OrderPlacedEvent event) {
+ String orderId = event.getOrderId();
+ orderedProducts.put(orderId, new OrderedProduct(orderId, event.getProduct()));
+ }
+
+ @EventHandler
+ public void on(OrderConfirmedEvent event) {
+ orderedProducts.computeIfPresent(event.getOrderId(), (orderId, orderedProduct) -> {
+ orderedProduct.setOrderConfirmed();
+ return orderedProduct;
+ });
+ }
+
+ @EventHandler
+ public void on(OrderShippedEvent event) {
+ orderedProducts.computeIfPresent(event.getOrderId(), (orderId, orderedProduct) -> {
+ orderedProduct.setOrderShipped();
+ return orderedProduct;
+ });
+ }
+
+ @QueryHandler
+ public List handle(FindAllOrderedProductsQuery query) {
+ return new ArrayList<>(orderedProducts.values());
+ }
+
+}
\ No newline at end of file
diff --git a/axon/src/main/resources/order-api.http b/axon/src/main/resources/order-api.http
new file mode 100644
index 0000000000..a3c69c72bc
--- /dev/null
+++ b/axon/src/main/resources/order-api.http
@@ -0,0 +1,11 @@
+POST http://localhost:8080/ship-order
+
+###
+
+POST http://localhost:8080/ship-unconfirmed-order
+
+###
+
+GET http://localhost:8080/all-orders
+
+###
diff --git a/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java b/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java
deleted file mode 100644
index ad099d2c2b..0000000000
--- a/axon/src/test/java/com/baeldung/axon/MessagesAggregateIntegrationTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-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/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java
new file mode 100644
index 0000000000..9beedbaa19
--- /dev/null
+++ b/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.axon.commandmodel;
+
+import java.util.UUID;
+
+import org.axonframework.test.aggregate.AggregateTestFixture;
+import org.axonframework.test.aggregate.FixtureConfiguration;
+import org.junit.*;
+
+import com.baeldung.axon.coreapi.commands.ConfirmOrderCommand;
+import com.baeldung.axon.coreapi.commands.PlaceOrderCommand;
+import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
+import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
+import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
+import com.baeldung.axon.coreapi.events.OrderShippedEvent;
+
+public class OrderAggregateUnitTest {
+
+ private FixtureConfiguration fixture;
+
+ @Before
+ public void setUp() {
+ fixture = new AggregateTestFixture<>(OrderAggregate.class);
+ }
+
+ @Test
+ public void giveNoPriorActivity_whenPlaceOrderCommand_thenShouldPublishOrderPlacedEvent() {
+ String orderId = UUID.randomUUID().toString();
+ String product = "Deluxe Chair";
+ fixture.givenNoPriorActivity()
+ .when(new PlaceOrderCommand(orderId, product))
+ .expectEvents(new OrderPlacedEvent(orderId, product));
+ }
+
+ @Test
+ public void givenOrderPlacedEvent_whenConfirmOrderCommand_thenShouldPublishOrderConfirmedEvent() {
+ String orderId = UUID.randomUUID().toString();
+ String product = "Deluxe Chair";
+ fixture.given(new OrderPlacedEvent(orderId, product))
+ .when(new ConfirmOrderCommand(orderId))
+ .expectEvents(new OrderConfirmedEvent(orderId));
+ }
+
+ @Test
+ public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() {
+ String orderId = UUID.randomUUID().toString();
+ String product = "Deluxe Chair";
+ fixture.given(new OrderPlacedEvent(orderId, product))
+ .when(new ShipOrderCommand(orderId))
+ .expectException(IllegalStateException.class);
+ }
+
+ @Test
+ public void givenOrderPlacedEventAndOrderConfirmedEvent_whenShipOrderCommand_thenShouldPublishOrderShippedEvent() {
+ String orderId = UUID.randomUUID().toString();
+ String product = "Deluxe Chair";
+ fixture.given(new OrderPlacedEvent(orderId, product), new OrderConfirmedEvent(orderId))
+ .when(new ShipOrderCommand(orderId))
+ .expectEvents(new OrderShippedEvent(orderId));
+ }
+
+}
\ No newline at end of file
diff --git a/azure/pom.xml b/azure/pom.xml
index 555efeef70..270b3e4829 100644
--- a/azure/pom.xml
+++ b/azure/pom.xml
@@ -5,9 +5,9 @@
com.baeldungazure0.1
- warazureDemo project for Spring Boot on Azure
+ warparent-boot-2
@@ -127,7 +127,6 @@
${azure.containerRegistry}.azurecr.io1.1.01.1.0
- 1.8
diff --git a/blade/README.md b/blade/README.md
new file mode 100644
index 0000000000..d823de775f
--- /dev/null
+++ b/blade/README.md
@@ -0,0 +1,5 @@
+### Relevant Articles:
+
+- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
+
+Run Integration Tests with `mvn integration-test`
\ No newline at end of file
diff --git a/blade/pom.xml b/blade/pom.xml
new file mode 100644
index 0000000000..37615bed01
--- /dev/null
+++ b/blade/pom.xml
@@ -0,0 +1,205 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ blade
+ 1.0.0-SNAPSHOT
+ blade
+
+
+
+
+
+
+
+
+
+
+
+ com.bladejava
+ blade-mvc
+ ${blade-mvc.version}
+
+
+
+ org.webjars
+ bootstrap
+ ${bootstrap.version}
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj-core.version}
+ test
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+ test
+
+
+ org.apache.httpcomponents
+ httpmime
+ ${httpmime.version}
+ test
+
+
+ org.apache.httpcomponents
+ httpcore
+ ${httpcore.version}
+ test
+
+
+
+ sample-blade-app
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+ 3
+ true
+
+ **/*LiveTest.java
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ **/*LiveTest.java
+
+
+
+
+
+ integration-test
+ verify
+
+
+
+
+
+
+ com.bazaarvoice.maven.plugins
+ process-exec-maven-plugin
+ ${process-exec-maven-plugin.version}
+
+
+
+ blade-process
+ pre-integration-test
+
+ start
+
+
+ Blade
+ false
+
+ java
+ -jar
+ sample-blade-app.jar
+
+
+
+
+
+
+ stop-all
+ post-integration-test
+
+ stop-all
+
+
+
+
+
+
+
+ maven-assembly-plugin
+ 3.1.0
+
+ ${project.build.finalName}
+ false
+
+
+ com.baeldung.blade.sample.App
+
+
+
+ jar-with-dependencies
+
+
+
+
+ make-assembly
+ package
+
+ single
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+ UTF-8
+
+
+
+
+
+
+ 1.8
+ 1.8
+ 2.0.14.RELEASE
+ 4.2.1
+ 3.8.1
+ 1.18.4
+ 4.12
+ 4.5.6
+ 4.5.6
+ 4.4.10
+ 3.11.1
+ 3.0.0-M3
+ 0.7
+ 2.21.0
+ 3.7.0
+
+
diff --git a/blade/src/main/java/com/baeldung/blade/sample/App.java b/blade/src/main/java/com/baeldung/blade/sample/App.java
new file mode 100644
index 0000000000..f3f3d4aebd
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/App.java
@@ -0,0 +1,38 @@
+package com.baeldung.blade.sample;
+
+import com.baeldung.blade.sample.interceptors.BaeldungMiddleware;
+import com.blade.Blade;
+import com.blade.event.EventType;
+import com.blade.mvc.WebContext;
+import com.blade.mvc.http.Session;
+
+public class App {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(App.class);
+
+ public static void main(String[] args) {
+
+ Blade.of()
+ .get("/", ctx -> ctx.render("index.html"))
+ .get("/basic-route-example", ctx -> ctx.text("GET called"))
+ .post("/basic-route-example", ctx -> ctx.text("POST called"))
+ .put("/basic-route-example", ctx -> ctx.text("PUT called"))
+ .delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
+ .addStatics("/custom-static")
+ // .showFileList(true)
+ .enableCors(true)
+ .before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
+ .on(EventType.SERVER_STARTED, e -> {
+ String version = WebContext.blade()
+ .env("app.version")
+ .orElse("N/D");
+ log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
+ })
+ .on(EventType.SESSION_CREATED, e -> {
+ Session session = (Session) e.attribute("session");
+ session.attribute("mySessionValue", "Baeldung");
+ })
+ .use(new BaeldungMiddleware())
+ .start(App.class, args);
+ }
+}
diff --git a/blade/src/main/java/com/baeldung/blade/sample/AttributesExampleController.java b/blade/src/main/java/com/baeldung/blade/sample/AttributesExampleController.java
new file mode 100644
index 0000000000..339ba701f7
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/AttributesExampleController.java
@@ -0,0 +1,37 @@
+package com.baeldung.blade.sample;
+
+import com.blade.mvc.annotation.GetRoute;
+import com.blade.mvc.annotation.Path;
+import com.blade.mvc.http.Request;
+import com.blade.mvc.http.Response;
+import com.blade.mvc.http.Session;
+
+@Path
+public class AttributesExampleController {
+
+ public final static String REQUEST_VALUE = "Some Request value";
+ public final static String SESSION_VALUE = "1337";
+ public final static String HEADER = "Some Header";
+
+ @GetRoute("/request-attribute-example")
+ public void getRequestAttribute(Request request, Response response) {
+ request.attribute("request-val", REQUEST_VALUE);
+ String requestVal = request.attribute("request-val");
+ response.text(requestVal);
+ }
+
+ @GetRoute("/session-attribute-example")
+ public void getSessionAttribute(Request request, Response response) {
+ Session session = request.session();
+ session.attribute("session-val", SESSION_VALUE);
+ String sessionVal = session.attribute("session-val");
+ response.text(sessionVal);
+ }
+
+ @GetRoute("/header-example")
+ public void getHeader(Request request, Response response) {
+ String headerVal = request.header("a-header", HEADER);
+ response.header("a-header", headerVal);
+ }
+
+}
diff --git a/blade/src/main/java/com/baeldung/blade/sample/LogExampleController.java b/blade/src/main/java/com/baeldung/blade/sample/LogExampleController.java
new file mode 100644
index 0000000000..f0c22c70dd
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/LogExampleController.java
@@ -0,0 +1,22 @@
+package com.baeldung.blade.sample;
+
+import com.blade.mvc.annotation.Path;
+import com.blade.mvc.annotation.Route;
+import com.blade.mvc.http.Response;
+
+@Path
+public class LogExampleController {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleController.class);
+
+ @Route(value = "/test-logs")
+ public void testLogs(Response response) {
+ log.trace("This is a TRACE Message");
+ log.debug("This is a DEBUG Message");
+ log.info("This is an INFO Message");
+ log.warn("This is a WARN Message");
+ log.error("This is an ERROR Message");
+ response.text("Check in ./logs");
+ }
+
+}
diff --git a/blade/src/main/java/com/baeldung/blade/sample/ParameterInjectionExampleController.java b/blade/src/main/java/com/baeldung/blade/sample/ParameterInjectionExampleController.java
new file mode 100644
index 0000000000..bc28244022
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/ParameterInjectionExampleController.java
@@ -0,0 +1,71 @@
+package com.baeldung.blade.sample;
+
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+
+import com.baeldung.blade.sample.vo.User;
+import com.blade.mvc.annotation.CookieParam;
+import com.blade.mvc.annotation.GetRoute;
+import com.blade.mvc.annotation.HeaderParam;
+import com.blade.mvc.annotation.JSON;
+import com.blade.mvc.annotation.MultipartParam;
+import com.blade.mvc.annotation.Param;
+import com.blade.mvc.annotation.Path;
+import com.blade.mvc.annotation.PathParam;
+import com.blade.mvc.annotation.PostRoute;
+import com.blade.mvc.http.Response;
+import com.blade.mvc.multipart.FileItem;
+import com.blade.mvc.ui.RestResponse;
+
+@Path
+public class ParameterInjectionExampleController {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParameterInjectionExampleController.class);
+
+ @GetRoute("/params/form")
+ public void formParam(@Param String name, Response response) {
+ log.info("name: " + name);
+ response.text(name);
+ }
+
+ @GetRoute("/params/path/:uid")
+ public void restfulParam(@PathParam Integer uid, Response response) {
+ log.info("uid: " + uid);
+ response.text(String.valueOf(uid));
+ }
+
+ @PostRoute("/params-file") // DO NOT USE A SLASH WITHIN THE ROUTE OR IT WILL BREAK (?)
+ @JSON
+ public RestResponse> fileParam(@MultipartParam FileItem fileItem) throws Exception {
+ try {
+ byte[] fileContent = fileItem.getData();
+
+ log.debug("Saving the uploaded file");
+ java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
+ Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
+
+ return RestResponse.ok();
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ return RestResponse.fail(e.getMessage());
+ }
+ }
+
+ @GetRoute("/params/header")
+ public void headerParam(@HeaderParam String customheader, Response response) {
+ log.info("Custom header: " + customheader);
+ response.text(customheader);
+ }
+
+ @GetRoute("/params/cookie")
+ public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
+ log.info("myCookie: " + myCookie);
+ response.text(myCookie);
+ }
+
+ @PostRoute("/params/vo")
+ public void voParam(@Param User user, Response response) {
+ log.info("user as voParam: " + user.toString());
+ response.html(user.toString() + "
Back");
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/RouteExampleController.java b/blade/src/main/java/com/baeldung/blade/sample/RouteExampleController.java
new file mode 100644
index 0000000000..7ba2a270a9
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/RouteExampleController.java
@@ -0,0 +1,78 @@
+package com.baeldung.blade.sample;
+
+import com.baeldung.blade.sample.configuration.BaeldungException;
+import com.blade.mvc.WebContext;
+import com.blade.mvc.annotation.DeleteRoute;
+import com.blade.mvc.annotation.GetRoute;
+import com.blade.mvc.annotation.Path;
+import com.blade.mvc.annotation.PostRoute;
+import com.blade.mvc.annotation.PutRoute;
+import com.blade.mvc.annotation.Route;
+import com.blade.mvc.http.HttpMethod;
+import com.blade.mvc.http.Request;
+import com.blade.mvc.http.Response;
+
+@Path
+public class RouteExampleController {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RouteExampleController.class);
+
+ @GetRoute("/route-example")
+ public String get() {
+ return "get.html";
+ }
+
+ @PostRoute("/route-example")
+ public String post() {
+ return "post.html";
+ }
+
+ @PutRoute("/route-example")
+ public String put() {
+ return "put.html";
+ }
+
+ @DeleteRoute("/route-example")
+ public String delete() {
+ return "delete.html";
+ }
+
+ @Route(value = "/another-route-example", method = HttpMethod.GET)
+ public String anotherGet() {
+ return "get.html";
+ }
+
+ @Route(value = "/allmatch-route-example")
+ public String allmatch() {
+ return "allmatch.html";
+ }
+
+ @Route(value = "/triggerInternalServerError")
+ public void triggerInternalServerError() {
+ int x = 1 / 0;
+ }
+
+ @Route(value = "/triggerBaeldungException")
+ public void triggerBaeldungException() throws BaeldungException {
+ throw new BaeldungException("Foobar Exception to threat differently");
+ }
+
+ @Route(value = "/user/foo")
+ public void urlCoveredByNarrowedWebhook(Response response) {
+ response.text("Check out for the WebHook covering '/user/*' in the logs");
+ }
+
+ @GetRoute("/load-configuration-in-a-route")
+ public void loadConfigurationInARoute(Response response) {
+ String authors = WebContext.blade()
+ .env("app.authors", "Unknown authors");
+ log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
+ response.render("index.html");
+ }
+
+ @GetRoute("/template-output-test")
+ public void templateOutputTest(Request request, Response response) {
+ request.attribute("name", "Blade");
+ response.render("template-output-test.html");
+ }
+}
diff --git a/blade/src/main/java/com/baeldung/blade/sample/configuration/BaeldungException.java b/blade/src/main/java/com/baeldung/blade/sample/configuration/BaeldungException.java
new file mode 100644
index 0000000000..01a030b7e7
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/configuration/BaeldungException.java
@@ -0,0 +1,9 @@
+package com.baeldung.blade.sample.configuration;
+
+public class BaeldungException extends RuntimeException {
+
+ public BaeldungException(String message) {
+ super(message);
+ }
+
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/configuration/GlobalExceptionHandler.java b/blade/src/main/java/com/baeldung/blade/sample/configuration/GlobalExceptionHandler.java
new file mode 100644
index 0000000000..ab7b81c0dc
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/configuration/GlobalExceptionHandler.java
@@ -0,0 +1,25 @@
+package com.baeldung.blade.sample.configuration;
+
+import com.blade.ioc.annotation.Bean;
+import com.blade.mvc.WebContext;
+import com.blade.mvc.handler.DefaultExceptionHandler;
+
+@Bean
+public class GlobalExceptionHandler extends DefaultExceptionHandler {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);
+
+ @Override
+ public void handle(Exception e) {
+ if (e instanceof BaeldungException) {
+ Exception baeldungException = (BaeldungException) e;
+ String msg = baeldungException.getMessage();
+ log.error("[GlobalExceptionHandler] Intercepted an exception to threat with additional logic. Error message: " + msg);
+ WebContext.response()
+ .render("index.html");
+
+ } else {
+ super.handle(e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/configuration/LoadConfig.java b/blade/src/main/java/com/baeldung/blade/sample/configuration/LoadConfig.java
new file mode 100644
index 0000000000..0f1aab1b52
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/configuration/LoadConfig.java
@@ -0,0 +1,23 @@
+package com.baeldung.blade.sample.configuration;
+
+import com.blade.Blade;
+import com.blade.ioc.annotation.Bean;
+import com.blade.loader.BladeLoader;
+import com.blade.mvc.WebContext;
+
+@Bean
+public class LoadConfig implements BladeLoader {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoadConfig.class);
+
+ @Override
+ public void load(Blade blade) {
+ String version = WebContext.blade()
+ .env("app.version")
+ .orElse("N/D");
+ String authors = WebContext.blade()
+ .env("app.authors", "Unknown authors");
+
+ log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/configuration/ScheduleExample.java b/blade/src/main/java/com/baeldung/blade/sample/configuration/ScheduleExample.java
new file mode 100644
index 0000000000..c170975818
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/configuration/ScheduleExample.java
@@ -0,0 +1,15 @@
+package com.baeldung.blade.sample.configuration;
+
+import com.blade.ioc.annotation.Bean;
+import com.blade.task.annotation.Schedule;
+
+@Bean
+public class ScheduleExample {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleExample.class);
+
+ @Schedule(name = "baeldungTask", cron = "0 */1 * * * ?")
+ public void runScheduledTask() {
+ log.info("[ScheduleExample] This is a scheduled Task running once per minute.");
+ }
+}
diff --git a/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungHook.java b/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungHook.java
new file mode 100644
index 0000000000..4d0d178b0d
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungHook.java
@@ -0,0 +1,17 @@
+package com.baeldung.blade.sample.interceptors;
+
+import com.blade.ioc.annotation.Bean;
+import com.blade.mvc.RouteContext;
+import com.blade.mvc.hook.WebHook;
+
+@Bean
+public class BaeldungHook implements WebHook {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungHook.class);
+
+ @Override
+ public boolean before(RouteContext ctx) {
+ log.info("[BaeldungHook] called before Route method");
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungMiddleware.java b/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungMiddleware.java
new file mode 100644
index 0000000000..3342cd8b01
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/interceptors/BaeldungMiddleware.java
@@ -0,0 +1,15 @@
+package com.baeldung.blade.sample.interceptors;
+
+import com.blade.mvc.RouteContext;
+import com.blade.mvc.hook.WebHook;
+
+public class BaeldungMiddleware implements WebHook {
+
+ private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungMiddleware.class);
+
+ @Override
+ public boolean before(RouteContext context) {
+ log.info("[BaeldungMiddleware] called before Route method and other WebHooks");
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/java/com/baeldung/blade/sample/vo/User.java b/blade/src/main/java/com/baeldung/blade/sample/vo/User.java
new file mode 100644
index 0000000000..b493dc3663
--- /dev/null
+++ b/blade/src/main/java/com/baeldung/blade/sample/vo/User.java
@@ -0,0 +1,16 @@
+package com.baeldung.blade.sample.vo;
+
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
+
+import lombok.Getter;
+import lombok.Setter;
+
+public class User {
+ @Getter @Setter private String name;
+ @Getter @Setter private String site;
+
+ @Override
+ public String toString() {
+ return ReflectionToStringBuilder.toString(this);
+ }
+}
\ No newline at end of file
diff --git a/blade/src/main/resources/application.properties b/blade/src/main/resources/application.properties
new file mode 100644
index 0000000000..ebf365406a
--- /dev/null
+++ b/blade/src/main/resources/application.properties
@@ -0,0 +1,5 @@
+mvc.statics.show-list=true
+mvc.view.404=my-404.html
+mvc.view.500=my-500.html
+app.version=0.0.1
+app.authors=Andrea Ligios
diff --git a/blade/src/main/resources/custom-static/icon.png b/blade/src/main/resources/custom-static/icon.png
new file mode 100644
index 0000000000..59af395afc
Binary files /dev/null and b/blade/src/main/resources/custom-static/icon.png differ
diff --git a/blade/src/main/resources/favicon.ico b/blade/src/main/resources/favicon.ico
new file mode 100644
index 0000000000..ca63a6a890
Binary files /dev/null and b/blade/src/main/resources/favicon.ico differ
diff --git a/blade/src/main/resources/static/app.css b/blade/src/main/resources/static/app.css
new file mode 100644
index 0000000000..9fff13d9b6
--- /dev/null
+++ b/blade/src/main/resources/static/app.css
@@ -0,0 +1 @@
+/* App CSS */
\ No newline at end of file
diff --git a/core-java/src/test/resources/correctFileNameWithoutProperExtension b/blade/src/main/resources/static/app.js
similarity index 100%
rename from core-java/src/test/resources/correctFileNameWithoutProperExtension
rename to blade/src/main/resources/static/app.js
diff --git a/blade/src/main/resources/static/file-upload.html b/blade/src/main/resources/static/file-upload.html
new file mode 100644
index 0000000000..b805be81b1
--- /dev/null
+++ b/blade/src/main/resources/static/file-upload.html
@@ -0,0 +1,43 @@
+
+
+
+
+Title
+
+
+
+
+
+
File Upload and download test
+
+
+
+ Back
+
+
+
+
\ No newline at end of file
diff --git a/blade/src/main/resources/static/user-post.html b/blade/src/main/resources/static/user-post.html
new file mode 100644
index 0000000000..ccfc4e8d0b
--- /dev/null
+++ b/blade/src/main/resources/static/user-post.html
@@ -0,0 +1,25 @@
+
+
+
+
+Title
+
+
+
+
+
+
User POJO post test
+
+
+
+
+
+ Back
+
+
+
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/allmatch.html b/blade/src/main/resources/templates/allmatch.html
new file mode 100644
index 0000000000..7a4bfa070f
--- /dev/null
+++ b/blade/src/main/resources/templates/allmatch.html
@@ -0,0 +1 @@
+ALLMATCH called
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/delete.html b/blade/src/main/resources/templates/delete.html
new file mode 100644
index 0000000000..1acb4b0b62
--- /dev/null
+++ b/blade/src/main/resources/templates/delete.html
@@ -0,0 +1 @@
+DELETE called
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/get.html b/blade/src/main/resources/templates/get.html
new file mode 100644
index 0000000000..2c37aa1058
--- /dev/null
+++ b/blade/src/main/resources/templates/get.html
@@ -0,0 +1 @@
+GET called
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/index.html b/blade/src/main/resources/templates/index.html
new file mode 100644
index 0000000000..6b7c2e77ad
--- /dev/null
+++ b/blade/src/main/resources/templates/index.html
@@ -0,0 +1,30 @@
+
+
+
+
+Baeldung Blade App • Written by Andrea Ligios
+
+
+
+
Baeldung Blade App - Showcase
+
+
Manual tests
+
The following are tests which are not covered by integration tests, but that can be run manually in order to check the functionality, either in the browser or in the logs, depending on the case.
+
+
+
+
+
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/my-404.html b/blade/src/main/resources/templates/my-404.html
new file mode 100644
index 0000000000..0fa694f241
--- /dev/null
+++ b/blade/src/main/resources/templates/my-404.html
@@ -0,0 +1,10 @@
+
+
+
+
+ 404 Not found
+
+
+ Custom Error 404 Page
+
+
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/my-500.html b/blade/src/main/resources/templates/my-500.html
new file mode 100644
index 0000000000..cc8438bfd6
--- /dev/null
+++ b/blade/src/main/resources/templates/my-500.html
@@ -0,0 +1,12 @@
+
+
+
+
+ 500 Internal Server Error
+
+
+
Custom Error 500 Page
+
The following error occurred: "${message}"
+
${stackTrace}
+
+
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/post.html b/blade/src/main/resources/templates/post.html
new file mode 100644
index 0000000000..b7a8a931cd
--- /dev/null
+++ b/blade/src/main/resources/templates/post.html
@@ -0,0 +1 @@
+POST called
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/put.html b/blade/src/main/resources/templates/put.html
new file mode 100644
index 0000000000..bdbe6d3285
--- /dev/null
+++ b/blade/src/main/resources/templates/put.html
@@ -0,0 +1 @@
+PUT called
\ No newline at end of file
diff --git a/blade/src/main/resources/templates/template-output-test.html b/blade/src/main/resources/templates/template-output-test.html
new file mode 100644
index 0000000000..233b12fb88
--- /dev/null
+++ b/blade/src/main/resources/templates/template-output-test.html
@@ -0,0 +1 @@
+