Merge pull request #1 from eugenp/master

Update fork with main repo
This commit is contained in:
Steven van Beelen 2019-07-10 12:32:59 +02:00 committed by GitHub
commit 26f8cd1c8d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5186 changed files with 187859 additions and 15248 deletions

13
.gitignore vendored
View File

@ -19,6 +19,7 @@
.idea/
*.iml
*.iws
out/
# Mac
.DS_Store
@ -27,6 +28,9 @@
log/
target/
# Gradle
.gradle/
spring-openid/src/main/resources/application.properties
.recommenders/
/spring-hibernate4/nbproject/
@ -66,3 +70,12 @@ 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/
/report-*.json
transaction.log

View File

@ -5,9 +5,9 @@
<groupId>com.baeldung</groupId>
<artifactId>JGit</artifactId>
<version>1.0-SNAPSHOT</version>
<name>JGit</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<name>JGit</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -14,23 +14,28 @@ 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`.
Building the project
====================
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
To do the full build, do: `mvn clean install`
Building a single module
====================
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
To build a specific module run the command: `mvn clean install` in the module directory
Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
#Running Tests
The command `mvn clean install` will run the unit tests in a module.
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`

View File

@ -2,8 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>Twitter4J</artifactId>
<packaging>jar</packaging>
<name>Twitter4J</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

3
akka-http/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Introduction to Akka HTTP](https://www.baeldung.com/akka-http)

47
akka-http/pom.xml Normal file
View File

@ -0,0 +1,47 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-http</artifactId>
<name>akka-http</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.12</artifactId>
<version>${akka.stream.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-jackson_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-testkit_2.12</artifactId>
<version>${akka.http.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>
</project>

View File

@ -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;
}
}

View File

@ -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<CreateUserMessage> handleCreateUser() {
return createUserMessageMessage -> {
userService.createUser(createUserMessageMessage.getUser());
sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser()
.getName())), getSelf());
};
}
private FI.UnitApply<GetUserMessage> handleGetUser() {
return getUserMessageMessage -> {
sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf());
};
}
}

View File

@ -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;
}
}
}

View File

@ -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<Optional<User>> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout)
.thenApply(obj -> (Optional<User>) 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<ActionPerformed> 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);
}
}

View File

@ -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<User> 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<User> getUser(Long id) {
return users.stream()
.filter(user -> user.getId()
.equals(id))
.findFirst();
}
public void createUser(User user) {
users.add(user);
}
public List<User> getUsers(){
return users;
}
}

View File

@ -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\"}";
}
}

View File

@ -14,18 +14,19 @@
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.11</artifactId>
<artifactId>akka-stream_${scala.version}</artifactId>
<version>${akkastreams.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream-testkit_2.11</artifactId>
<artifactId>akka-stream-testkit_${scala.version}</artifactId>
<version>${akkastreams.version}</version>
</dependency>
</dependencies>
<properties>
<akkastreams.version>2.5.2</akkastreams.version>
<scala.version>2.11</scala.version>
</properties>
</project>

View File

@ -54,7 +54,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -10,4 +10,9 @@
- [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)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [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)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)

View File

@ -39,6 +39,11 @@
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dpaukov</groupId>
<artifactId>combinatoricslib3</artifactId>
<version>${combinatoricslib3.version}</version>
</dependency>
</dependencies>
<build>
@ -74,11 +79,11 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<guava.version>25.1-jre</guava.version>
<guava.version>27.0.1-jre</guava.version>
<combinatoricslib3.version>3.3.0</combinatoricslib3.version>
</properties>
</project>

View File

@ -0,0 +1,123 @@
package com.baeldung.algorithms.permutation;
import java.util.Arrays;
import java.util.Collections;
public class Permutation {
public static <T> void printAllRecursive(T[] elements, char delimiter) {
printAllRecursive(elements.length, elements, delimiter);
}
public static <T> 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 <T> 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 <T extends Comparable<T>> 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 <T> void printRandom(T[] elements, char delimiter) {
Collections.shuffle(Arrays.asList(elements));
printArray(elements, delimiter);
}
private static <T> void swap(T[] elements, int a, int b) {
T tmp = elements[a];
elements[a] = elements[b];
elements[b] = tmp;
}
private static <T> 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, ';');
}
}

View File

@ -8,9 +8,6 @@
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [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)
- [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)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
@ -18,3 +15,5 @@
- [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)
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)

View File

@ -68,7 +68,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<version>${cobertura-maven-plugin.version}</version>
<configuration>
<instrumentation>
<ignores>
@ -84,13 +84,13 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<cobertura-maven-plugin.version>2.7</cobertura-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.algorithms.relativelyprime;
import java.math.BigInteger;
class RelativelyPrime {
static boolean iterativeRelativelyPrime(int a, int b) {
return iterativeGCD(a, b) == 1;
}
static boolean recursiveRelativelyPrime(int a, int b) {
return recursiveGCD(a, b) == 1;
}
static boolean bigIntegerRelativelyPrime(int a, int b) {
return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE);
}
private static int iterativeGCD(int a, int b) {
int tmp;
while (b != 0) {
if (a < b) {
tmp = a;
a = b;
b = tmp;
}
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
private static int recursiveGCD(int a, int b) {
if (b == 0) {
return a;
}
if (a < b) {
return recursiveGCD(b, a);
}
return recursiveGCD(b, a % b);
}
}

View File

@ -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 leftChild, TreeNode rightChild) {
this.value = value;
this.rightChild = rightChild;
this.leftChild = leftChild;
}
public TreeNode(int value) {
this.value = value;
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.algorithms.reversingtree;
import java.util.LinkedList;
public class TreeReverser {
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<TreeNode> queue = new LinkedList<TreeNode>();
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();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.algorithms.relativelyprime;
import org.junit.Test;
import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
import static org.assertj.core.api.Assertions.assertThat;
public class RelativelyPrimeUnitTest {
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
boolean result = iterativeRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
boolean result = iterativeRelativelyPrime(500, 501);
assertThat(result).isTrue();
}
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
boolean result = recursiveRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
boolean result = recursiveRelativelyPrime(500, 501);
assertThat(result).isTrue();
}
@Test
public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
boolean result = bigIntegerRelativelyPrime(45, 35);
assertThat(result).isFalse();
}
@Test
public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
boolean result = bigIntegerRelativelyPrime(500, 501);
assertThat(result).isTrue();
}
}

View File

@ -0,0 +1,47 @@
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 = 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 = createBinaryTree();
reverser.reverseIterative(treeNode);
assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
.trim());
}
private TreeNode createBinaryTree() {
TreeNode leaf1 = new TreeNode(1);
TreeNode leaf2 = new TreeNode(3);
TreeNode leaf3 = new TreeNode(6);
TreeNode leaf4 = new TreeNode(9);
TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
TreeNode root = new TreeNode(4, nodeLeft, nodeRight);
return root;
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

4
algorithms-miscellaneous-3/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,9 @@
## Relevant articles:
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
- [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)
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
- [A Guide to the Folding Technique](https://www.baeldung.com/folding-hashing-technique)

View File

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" 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">
<modelVersion>4.0.0</modelVersion>
<artifactId>algorithms-miscellaneous-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-3</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-collections4.version>4.3</commons-collections4.version>
<guava.version>28.0-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.checksortedlist;
public class Employee {
long id;
String name;
public Employee() {
}
public Employee(long id, String name) {
super();
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.algorithms.checksortedlist;
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Comparators;
import com.google.common.collect.Ordering;;
public class SortedListChecker {
private SortedListChecker() {
throw new AssertionError();
}
public static boolean checkIfSortedUsingIterativeApproach(List<String> listOfStrings) {
if (isEmpty(listOfStrings) || listOfStrings.size() == 1) {
return true;
}
Iterator<String> iter = listOfStrings.iterator();
String current, previous = iter.next();
while (iter.hasNext()) {
current = iter.next();
if (previous.compareTo(current) > 0) {
return false;
}
previous = current;
}
return true;
}
public static boolean checkIfSortedUsingIterativeApproach(List<Employee> employees, Comparator<Employee> employeeComparator) {
if (isEmpty(employees) || employees.size() == 1) {
return true;
}
Iterator<Employee> iter = employees.iterator();
Employee current, previous = iter.next();
while (iter.hasNext()) {
current = iter.next();
if (employeeComparator.compare(previous, current) > 0) {
return false;
}
previous = current;
}
return true;
}
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) {
return isSortedRecursive(listOfStrings, listOfStrings.size());
}
public static boolean isSortedRecursive(List<String> listOfStrings, int index) {
if (index < 2) {
return true;
} else if (listOfStrings.get(index - 2)
.compareTo(listOfStrings.get(index - 1)) > 0) {
return false;
} else {
return isSortedRecursive(listOfStrings, index - 1);
}
}
public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) {
return Ordering.<String> natural()
.isOrdered(listOfStrings);
}
public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) {
return Ordering.from(employeeComparator)
.isOrdered(employees);
}
public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) {
return Ordering.<String> natural()
.nullsLast()
.isOrdered(listOfStrings);
}
public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) {
return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder());
}
}

View File

@ -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();
}

View File

@ -0,0 +1,51 @@
package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Graph {
private List<Vertex> vertices;
public Graph() {
this.vertices = new ArrayList<>();
}
public Graph(List<Vertex> vertices) {
this.vertices = vertices;
}
public void addVertex(Vertex vertex) {
this.vertices.add(vertex);
}
public void addEdge(Vertex from, Vertex to) {
from.addNeighbour(to);
}
public boolean hasCycle() {
for (Vertex vertex : vertices) {
if (!vertex.isVisited() && hasCycle(vertex)) {
return true;
}
}
return false;
}
public boolean hasCycle(Vertex sourceVertex) {
sourceVertex.setBeingVisited(true);
for (Vertex neighbour : sourceVertex.getAdjacencyList()) {
if (neighbour.isBeingVisited()) {
// backward edge exists
return true;
} else if (!neighbour.isVisited() && hasCycle(neighbour)) {
return true;
}
}
sourceVertex.setBeingVisited(false);
sourceVertex.setVisited(true);
return false;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
private String label;
private boolean visited;
private boolean beingVisited;
private List<Vertex> adjacencyList;
public Vertex(String label) {
this.label = label;
this.adjacencyList = new ArrayList<>();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isBeingVisited() {
return beingVisited;
}
public void setBeingVisited(boolean beingVisited) {
this.beingVisited = beingVisited;
}
public List<Vertex> getAdjacencyList() {
return adjacencyList;
}
public void setAdjacencyList(List<Vertex> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public void addNeighbour(Vertex adjacent) {
this.adjacencyList.add(adjacent);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.algorithms.twopointertechnique;
public class LinkedListFindMiddle {
public <T> T findMiddle(MyNode<T> head) {
MyNode<T> slowPointer = head;
MyNode<T> fastPointer = head;
while (fastPointer.next != null && fastPointer.next.next != null) {
fastPointer = fastPointer.next.next;
slowPointer = slowPointer.next;
}
return slowPointer.data;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.twopointertechnique;
public class MyNode<E> {
MyNode<E> next;
E data;
public MyNode(E value) {
data = value;
next = null;
}
public MyNode(E value, MyNode<E> n) {
data = value;
next = n;
}
public void setNext(MyNode<E> n) {
next = n;
}
}

View File

@ -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--;
}
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.folding;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Calculate a hash value for the strings using the folding technique.
*
* The implementation serves only to the illustration purposes and is far
* from being the most efficient.
*
* @author A.Shcherbakov
*
*/
public class FoldingHash {
/**
* Calculate the hash value of a given string.
*
* @param str Assume it is not null
* @param groupSize the group size in the folding technique
* @param maxValue defines a max value that the hash may acquire (exclusive)
* @return integer value from 0 (inclusive) to maxValue (exclusive)
*/
public int hash(String str, int groupSize, int maxValue) {
final int[] codes = this.toAsciiCodes(str);
return IntStream.range(0, str.length())
.filter(i -> i % groupSize == 0)
.mapToObj(i -> extract(codes, i, groupSize))
.map(block -> concatenate(block))
.reduce(0, (a, b) -> (a + b) % maxValue);
}
/**
* Returns a new array of given length whose elements are take from
* the original one starting from the offset.
*
* If the original array has not enough elements, the returning array will contain
* element from the offset till the end of the original array.
*
* @param numbers original array. Assume it is not null.
* @param offset index of the element to start from. Assume it is less than the size of the array
* @param length max size of the resulting array
* @return
*/
public int[] extract(int[] numbers, int offset, int length) {
final int defect = numbers.length - (offset + length);
final int s = defect < 0 ? length + defect : length;
int[] result = new int[s];
for (int index = 0; index < s; index++) {
result[index] = numbers[index + offset];
}
return result;
}
/**
* Concatenate the numbers into a single number as if they were strings.
* Assume that the procedure does not suffer from the overflow.
* @param numbers integers to concatenate
* @return
*/
public int concatenate(int[] numbers) {
final String merged = IntStream.of(numbers)
.mapToObj(number -> "" + number)
.collect(Collectors.joining());
return Integer.parseInt(merged, 10);
}
/**
* Convert the string into its characters' ASCII codes.
* @param str input string
* @return
*/
private int[] toAsciiCodes(String str) {
return str.chars()
.toArray();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.folding;
/**
* Code snippet for article "A Guide to the Folding Technique".
*
* @author A.Shcherbakov
*
*/
public class Main {
public static void main(String... arg) {
FoldingHash hasher = new FoldingHash();
final String str = "Java language";
System.out.println(hasher.hash(str, 2, 100_000));
System.out.println(hasher.hash(str, 3, 1_000));
}
}

View File

@ -0,0 +1,106 @@
package com.baeldung.algorithms.checksortedlist;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class SortedListCheckerUnitTest {
private List<String> sortedListOfString;
private List<String> unsortedListOfString;
private List<String> singletonList;
private List<Employee> employeesSortedByName;
private List<Employee> employeesNotSortedByName;
@Before
public void setUp() {
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
singletonList = Collections.singletonList("NY");
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
}
@Test
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
}
@Test
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
}
@Test
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
}
@Test
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
}
@Test
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
}
@Test
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
}
@Test
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.algorithms.graphcycledetection;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
public class GraphCycleDetectionUnitTest {
@Test
public void givenGraph_whenCycleExists_thenReturnTrue() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexC, vertexA);
graph.addEdge(vertexD, vertexC);
assertTrue(graph.hasCycle());
}
@Test
public void givenGraph_whenNoCycleExists_thenReturnFalse() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexA, vertexC);
graph.addEdge(vertexD, vertexC);
assertFalse(graph.hasCycle());
}
}

View File

@ -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<String> head = createNodesList(8);
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("4");
head = createNodesList(9);
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("5");
}
private static MyNode<String> createNodesList(int n) {
MyNode<String> head = new MyNode<String>("1");
MyNode<String> current = head;
for (int i = 2; i <= n; i++) {
MyNode<String> newNode = new MyNode<String>(String.valueOf(i));
current.setNext(newNode);
current = newNode;
}
return head;
}
}

View File

@ -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 });
}
}

View File

@ -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));
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.folding;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FoldingHashUnitTest {
@Test
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int value = hasher.hash("Java language", 2, 100_000);
assertEquals(value, 48933);
}
@Test
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int java = hasher.hash("Java language", 2, 100_000);
final int vaja = hasher.hash("vaJa language", 2, 100_000);
assertTrue(java == vaja);
}
@Test
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
assertArrayEquals(new int[] { 5 }, value);
}
@Test
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
assertArrayEquals(new int[] { 1, 2, 3 }, value);
}
@Test
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
assertArrayEquals(new int[] { 2, 3 }, value);
}
@Test
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
final FoldingHash hasher = new FoldingHash();
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
assertArrayEquals(new int[] { 3, 4, 5 }, value);
}
}

View File

@ -49,7 +49,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>

View File

@ -3,9 +3,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>animal-sniffer-mvn-plugin</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>

View File

@ -3,8 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId>
<packaging>pom</packaging>
<name>annotations</name>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -10,6 +10,14 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -44,13 +52,7 @@
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>${antlr.version}</version>
</dependency>
</dependencies>
<properties>
<antlr.version>4.7.1</antlr.version>
<mojo.version>3.0.0</mojo.version>

View File

@ -7,14 +7,6 @@
<version>0.0.1-SNAPSHOT</version>
<name>apache-avro</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<java.version>1.8</java.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -25,7 +17,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -85,4 +77,12 @@
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
</project>

View File

@ -3,8 +3,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-curator</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -39,7 +39,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@ -59,7 +59,6 @@
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.4</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

View File

@ -12,9 +12,18 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<cxf-version>3.2.0</cxf-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-sse</artifactId>
<version>${cxf-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
@ -45,17 +54,8 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-sse</artifactId>
<version>${cxf-version}</version>
</dependency>
</dependencies>
<properties>
<cxf-version>3.2.0</cxf-version>
</properties>
</project>

View File

@ -13,11 +13,28 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
<openliberty-version>18.0.0.2</openliberty-version>
</properties>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
@ -59,27 +76,10 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
<openliberty-version>18.0.0.2</openliberty-version>
</properties>
</project>

View File

@ -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)

View File

@ -12,22 +12,6 @@
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
@ -38,8 +22,24 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
</project>

View File

@ -21,7 +21,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class GeodeSamplesIntegrationTest {
public class GeodeSamplesLiveTest {
ClientCache cache = null;
Region<String, String> region = null;

View File

@ -6,52 +6,64 @@
<version>0.0.1</version>
<name>apache-meecrowave</name>
<description>A sample REST API application with Meecrowave</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-core</artifactId>
<version>1.2.1</version>
<version>${meecrowave-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-jpa</artifactId>
<version>1.2.1</version>
<version>${meecrowave-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-junit</artifactId>
<version>1.2.0</version>
<version>${meecrowave-junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-maven-plugin</artifactId>
<version>1.2.1</version>
<version>${meecrowave-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
<okhttp.version>3.10.0</okhttp.version>
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
<meecrowave-core.version>1.2.1</meecrowave-core.version>
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
</properties>
</project>

View File

@ -17,7 +17,7 @@ import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
public class ArticleEndpointsTest {
public class ArticleEndpointsUnitTest {
@ConfigurationInject
private Meecrowave.Builder config;

3
apache-olingo/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [OData Protocol Guide](https://www.baeldung.com/odata)

21
apache-olingo/Samples.md Normal file
View File

@ -0,0 +1,21 @@
## OData test URLs
This following table contains test URLs that can be used with the Olingo V2 demo project.
| URL | Description |
|------------------------------------------|-------------------------------------------------|
| `http://localhost:8180/odata/$metadata` | fetch OData metadata document |
| `http://localhost:8180/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
| `http://localhost:8180/odata/CarMakers?$count` | Return total count of entities in this set |
| `http://localhost:8180/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
| `http://localhost:8180/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
| `http://localhost:8180/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
| `http://localhost:8180/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
| `http://localhost:8180/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
| `http://localhost:8180/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|

29
apache-olingo/olingo2/.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
HELP.md
/target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung.examples.olingo2</groupId>
<artifactId>olingo2-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>olingo2-sample</name>
<description>Sample Olingo 2 Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Olingo 2 Dependencies -->
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-core</artifactId>
<version>${olingo2.version}</version>
<!-- Avoid jax-rs version conflict by excluding Olingo's version -->
<exclusions>
<exclusion>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-jpa-processor-core</artifactId>
<version>${olingo2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.olingo</groupId>
<artifactId>olingo-odata2-jpa-processor-ref</artifactId>
<version>${olingo2.version}</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<olingo2.version>2.0.11</olingo2.version>
</properties>
</project>

View File

@ -0,0 +1,298 @@
package org.baeldung.examples.olingo2;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
import javax.persistence.SynchronizationType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.metamodel.Metamodel;
import javax.servlet.http.HttpServletRequest;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import org.baeldung.examples.olingo2.JerseyConfig.EntityManagerFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;
/**
* ODataJPAServiceFactory implementation for our sample domain
* @author Philippe
*
*/
@Component
public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
private static final Logger log = LoggerFactory.getLogger(CarsODataJPAServiceFactory.class);
public CarsODataJPAServiceFactory() {
// Enable detailed error messages (useful for debugging)
setDetailErrors(true);
}
/**
* This method will be called by Olingo on every request to
* initialize the ODataJPAContext that will be used.
*/
@Override
public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
log.info("[I32] >>> initializeODataJPAContext()");
ODataJPAContext ctx = getODataJPAContext();
ODataContext octx = ctx.getODataContext();
HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
EntityManager em = (EntityManager)request.getAttribute(EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
// Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig)
ctx.setEntityManager(new EntityManagerWrapper(em));
ctx.setPersistenceUnitName("default");
// We're managing the EM's lifecycle, so we must inform Olingo that it should not
// try to manage transactions and/or persistence sessions
ctx.setContainerManaged(true);
return ctx;
}
static class EntityManagerWrapper implements EntityManager {
private EntityManager delegate;
public void persist(Object entity) {
log.info("[I68] persist: entity.class=" + entity.getClass()
.getSimpleName());
delegate.persist(entity);
// delegate.flush();
}
public <T> T merge(T entity) {
log.info("[I74] merge: entity.class=" + entity.getClass()
.getSimpleName());
return delegate.merge(entity);
}
public void remove(Object entity) {
log.info("[I78] remove: entity.class=" + entity.getClass()
.getSimpleName());
delegate.remove(entity);
}
public <T> T find(Class<T> entityClass, Object primaryKey) {
return delegate.find(entityClass, primaryKey);
}
public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties) {
return delegate.find(entityClass, primaryKey, properties);
}
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) {
return delegate.find(entityClass, primaryKey, lockMode);
}
public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode, Map<String, Object> properties) {
return delegate.find(entityClass, primaryKey, lockMode, properties);
}
public <T> T getReference(Class<T> entityClass, Object primaryKey) {
return delegate.getReference(entityClass, primaryKey);
}
public void flush() {
delegate.flush();
}
public void setFlushMode(FlushModeType flushMode) {
delegate.setFlushMode(flushMode);
}
public FlushModeType getFlushMode() {
return delegate.getFlushMode();
}
public void lock(Object entity, LockModeType lockMode) {
delegate.lock(entity, lockMode);
}
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
delegate.lock(entity, lockMode, properties);
}
public void refresh(Object entity) {
delegate.refresh(entity);
}
public void refresh(Object entity, Map<String, Object> properties) {
delegate.refresh(entity, properties);
}
public void refresh(Object entity, LockModeType lockMode) {
delegate.refresh(entity, lockMode);
}
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
delegate.refresh(entity, lockMode, properties);
}
public void clear() {
delegate.clear();
}
public void detach(Object entity) {
delegate.detach(entity);
}
public boolean contains(Object entity) {
return delegate.contains(entity);
}
public LockModeType getLockMode(Object entity) {
return delegate.getLockMode(entity);
}
public void setProperty(String propertyName, Object value) {
delegate.setProperty(propertyName, value);
}
public Map<String, Object> getProperties() {
return delegate.getProperties();
}
public Query createQuery(String qlString) {
return delegate.createQuery(qlString);
}
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) {
return delegate.createQuery(criteriaQuery);
}
public Query createQuery(CriteriaUpdate updateQuery) {
return delegate.createQuery(updateQuery);
}
public Query createQuery(CriteriaDelete deleteQuery) {
return delegate.createQuery(deleteQuery);
}
public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) {
return delegate.createQuery(qlString, resultClass);
}
public Query createNamedQuery(String name) {
return delegate.createNamedQuery(name);
}
public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass) {
return delegate.createNamedQuery(name, resultClass);
}
public Query createNativeQuery(String sqlString) {
return delegate.createNativeQuery(sqlString);
}
public Query createNativeQuery(String sqlString, Class resultClass) {
return delegate.createNativeQuery(sqlString, resultClass);
}
public Query createNativeQuery(String sqlString, String resultSetMapping) {
return delegate.createNativeQuery(sqlString, resultSetMapping);
}
public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
return delegate.createNamedStoredProcedureQuery(name);
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName) {
return delegate.createStoredProcedureQuery(procedureName);
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) {
return delegate.createStoredProcedureQuery(procedureName, resultClasses);
}
public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) {
return delegate.createStoredProcedureQuery(procedureName, resultSetMappings);
}
public void joinTransaction() {
delegate.joinTransaction();
}
public boolean isJoinedToTransaction() {
return delegate.isJoinedToTransaction();
}
public <T> T unwrap(Class<T> cls) {
return delegate.unwrap(cls);
}
public Object getDelegate() {
return delegate.getDelegate();
}
public void close() {
log.info("[I229] close");
delegate.close();
}
public boolean isOpen() {
boolean isOpen = delegate.isOpen();
log.info("[I236] isOpen: " + isOpen);
return isOpen;
}
public EntityTransaction getTransaction() {
log.info("[I240] getTransaction()");
return delegate.getTransaction();
}
public EntityManagerFactory getEntityManagerFactory() {
return delegate.getEntityManagerFactory();
}
public CriteriaBuilder getCriteriaBuilder() {
return delegate.getCriteriaBuilder();
}
public Metamodel getMetamodel() {
return delegate.getMetamodel();
}
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return delegate.createEntityGraph(rootType);
}
public EntityGraph<?> createEntityGraph(String graphName) {
return delegate.createEntityGraph(graphName);
}
public EntityGraph<?> getEntityGraph(String graphName) {
return delegate.getEntityGraph(graphName);
}
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return delegate.getEntityGraphs(entityClass);
}
public EntityManagerWrapper(EntityManager delegate) {
this.delegate = delegate;
}
}
}

View File

@ -0,0 +1,125 @@
package org.baeldung.examples.olingo2;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.core.rest.ODataRootLocator;
import org.apache.olingo.odata2.core.rest.app.ODataApplication;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Jersey JAX-RS configuration
* @author Philippe
*
*/
@Component
@ApplicationPath("/odata")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
ODataApplication app = new ODataApplication();
app
.getClasses()
.forEach( c -> {
// Avoid using the default RootLocator, as we want
// a Spring Managed one
if ( !ODataRootLocator.class.isAssignableFrom(c)) {
register(c);
}
});
register(new CarsRootLocator(serviceFactory));
register( new EntityManagerFilter(emf));
}
/**
* This filter handles the EntityManager transaction lifecycle.
* @author Philippe
*
*/
@Provider
public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final Logger log = LoggerFactory.getLogger(EntityManagerFilter.class);
public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER";
private final EntityManagerFactory emf;
@Context
private HttpServletRequest httpRequest;
public EntityManagerFilter(EntityManagerFactory emf) {
this.emf = emf;
}
@Override
public void filter(ContainerRequestContext ctx) throws IOException {
log.info("[I60] >>> filter");
EntityManager em = this.emf.createEntityManager();
httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em);
// Start a new transaction unless we have a simple GET
if (!"GET".equalsIgnoreCase(ctx.getMethod())) {
em.getTransaction()
.begin();
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
log.info("[I68] <<< filter");
EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);
if (!"GET".equalsIgnoreCase(requestContext.getMethod())) {
EntityTransaction t = em.getTransaction();
if (t.isActive()) {
if (!t.getRollbackOnly()) {
t.commit();
}
}
}
em.close();
}
}
@Path("/")
public static class CarsRootLocator extends ODataRootLocator {
private CarsODataJPAServiceFactory serviceFactory;
public CarsRootLocator(CarsODataJPAServiceFactory serviceFactory) {
this.serviceFactory = serviceFactory;
}
@Override
public ODataServiceFactory getServiceFactory() {
return this.serviceFactory;
}
}
}

View File

@ -0,0 +1,14 @@
package org.baeldung.examples.olingo2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class Olingo2SampleApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Olingo2SampleApplication.class);
}
}

View File

@ -0,0 +1,115 @@
package org.baeldung.examples.olingo2.domain;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "car_maker")
public class CarMaker {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL)
private List<CarModel> models;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the models
*/
public List<CarModel> getModels() {
return models;
}
/**
* @param models the models to set
*/
public void setModels(List<CarModel> models) {
this.models = models;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((models == null) ? 0 : models.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarMaker other = (CarMaker) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (models == null) {
if (other.models != null)
return false;
} else if (!models.equals(other.models))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@ -0,0 +1,159 @@
package org.baeldung.examples.olingo2.domain;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "car_model")
public class CarModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String name;
@NotNull
private Integer year;
@NotNull
private String sku;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "maker_fk")
private CarMaker maker;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the year
*/
public Integer getYear() {
return year;
}
/**
* @param year the year to set
*/
public void setYear(Integer year) {
this.year = year;
}
/**
* @return the sku
*/
public String getSku() {
return sku;
}
/**
* @param sku the sku to set
*/
public void setSku(String sku) {
this.sku = sku;
}
/**
* @return the maker
*/
public CarMaker getMaker() {
return maker;
}
/**
* @param maker the maker to set
*/
public void setMaker(CarMaker maker) {
this.maker = maker;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((maker == null) ? 0 : maker.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sku == null) ? 0 : sku.hashCode());
result = prime * result + ((year == null) ? 0 : year.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarModel other = (CarModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (maker == null) {
if (other.maker != null)
return false;
} else if (!maker.equals(other.maker))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
}

View File

@ -0,0 +1,12 @@
server:
port: 8080
spring:
jersey:
application-path: /odata
jpa:
show-sql: true
open-in-view: false
hibernate:
ddl-auto: update

View File

@ -0,0 +1,12 @@
insert into car_maker(id,name) values (1,'Special Motors');
insert into car_maker(id,name) values (2,'BWM');
insert into car_maker(id,name) values (3,'Dolores');
insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018);
insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008);
insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008);
insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009);
insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008);
alter sequence hibernate_sequence restart with 100;

View File

@ -0,0 +1,16 @@
package org.baeldung.examples.olingo2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Olingo2SampleApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@ -0,0 +1,256 @@
{
"info": {
"_postman_id": "afa8e1e5-ab0e-4f1d-8b99-b7d1f091f975",
"name": "OLingo2 - Cars",
"schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
},
"item": [
{
"name": "GET Metadata",
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": "http://localhost:8080/odata/$metadata"
},
"response": []
},
{
"name": "GET All CarMakers",
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": "http://localhost:8080/odata/CarMakers"
},
"response": []
},
{
"name": "GET Makers with Pagination",
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8080/odata/CarMakers?$top=1&$orderby=Name&$skip=3",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"odata",
"CarMakers"
],
"query": [
{
"key": "$top",
"value": "1"
},
{
"key": "$orderby",
"value": "Name"
},
{
"key": "$skip",
"value": "3"
}
]
}
},
"response": []
},
{
"name": "GET Makers and Models",
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8080/odata/CarMakers?$expand=CarModelDetails",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"odata",
"CarMakers"
],
"query": [
{
"key": "$expand",
"value": "CarModelDetails"
}
]
}
},
"response": []
},
{
"name": "GET Makers with filter",
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": ""
},
"url": {
"raw": "http://localhost:8080/odata/CarMakers?$filter=Name eq 'BWM'&$expand=CarModelDetails",
"protocol": "http",
"host": [
"localhost"
],
"port": "8080",
"path": [
"odata",
"CarMakers"
],
"query": [
{
"key": "$filter",
"value": "Name eq 'BWM'"
},
{
"key": "$expand",
"value": "CarModelDetails"
}
]
}
},
"response": []
},
{
"name": "Create CarMaker",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"value": "application/atom+xml",
"type": "text"
},
{
"key": "Accept",
"value": "application/atom+xml",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "<?xml version=\"1.0\" encoding=\"utf-8\" ?> \r\n<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"\r\n xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" \r\n xmlns=\"http://www.w3.org/2005/Atom\">\r\n <title type=\"text\"></title> \r\n <updated>2019-04-02T21:36:47Z</updated>\r\n <author> \r\n <name /> \r\n </author> \r\n <category term=\"default.CarMaker\"\r\n scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" /> \r\n <content type=\"application/xml\"> \r\n <m:properties>\r\n <d:Name>Lucien</d:Name>\r\n </m:properties> \r\n </content> \r\n</entry>"
},
"url": "http://localhost:8080/odata/CarMakers"
},
"response": []
},
{
"name": "Create CarModel",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"type": "text",
"value": "application/atom+xml"
},
{
"key": "Accept",
"type": "text",
"value": "application/atom+xml"
}
],
"body": {
"mode": "raw",
"raw": "<?xml version=\"1.0\" encoding=\"utf-8\" ?> \r\n<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"\r\n xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" \r\n xmlns=\"http://www.w3.org/2005/Atom\">\r\n <title type=\"text\"></title> \r\n <updated>2019-04-02T21:36:47Z</updated>\r\n <author> \r\n <name /> \r\n </author> \r\n <link href=\"CarModels(1L)/CarMakerDetails\" \r\n rel=\"http://schemas.microsoft.com/ado/2007/08/dataservices/related/CarMakerDetails\" \r\n title=\"CarMakerDetails\" \r\n type=\"application/atom+xml;type=entry\"></link> \r\n <category term=\"default.CarModel\"\r\n scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" /> \r\n <content type=\"application/xml\"> \r\n <m:properties>\r\n\t <d:Name>Tata</d:Name>\r\n\t <d:Sku>TT101</d:Sku>\r\n\t <d:Year>2018</d:Year>\r\n </m:properties> \r\n </content> \r\n</entry>"
},
"url": "http://localhost:8080/odata/CarModels"
},
"response": []
},
{
"name": "Update CarMaker",
"request": {
"method": "PUT",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"type": "text",
"value": "application/atom+xml"
},
{
"key": "Accept",
"type": "text",
"value": "application/atom+xml"
}
],
"body": {
"mode": "raw",
"raw": "<?xml version=\"1.0\" encoding=\"utf-8\" ?> \r\n<entry xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\"\r\n xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" \r\n xmlns=\"http://www.w3.org/2005/Atom\">\r\n <title type=\"text\"></title> \r\n <updated>2019-04-02T21:36:47Z</updated>\r\n <author> \r\n <name /> \r\n </author> \r\n <category term=\"default.CarMaker\"\r\n scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" /> \r\n <content type=\"application/xml\"> \r\n <m:properties>\r\n <d:Id>5</d:Id>\r\n <d:Name>KaiserWagen</d:Name>\r\n </m:properties> \r\n </content> \r\n</entry>"
},
"url": "http://localhost:8080/odata/CarMakers(5L)"
},
"response": []
},
{
"name": "All CarModels",
"request": {
"method": "GET",
"header": [],
"body": {
"mode": "raw",
"raw": ""
},
"url": "http://localhost:8080/odata/CarModels"
},
"response": []
},
{
"name": "Delete CarModel",
"request": {
"method": "DELETE",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"type": "text",
"value": "application/atom+xml"
},
{
"key": "Accept",
"type": "text",
"value": "application/atom+xml"
}
],
"body": {
"mode": "raw",
"raw": ""
},
"url": "http://localhost:8080/odata/CarModels(100L)"
},
"response": []
}
]
}

View File

@ -11,12 +11,14 @@
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.1.1-incubating</version>
<version>${pulsar-client.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
</properties>
</project>

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-solrj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-solrj</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -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)

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-spark</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
@ -15,16 +15,79 @@
</parent>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<artifactId>spark-core_2.11</artifactId>
<version>${org.apache.spark.spark-core.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>${org.apache.spark.spark-sql.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>${org.apache.spark.spark-streaming.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
<version>${org.apache.spark.spark-streaming-kafka.version}</version>
</dependency>
<dependency>
<groupId>com.datastax.spark</groupId>
<artifactId>spark-cassandra-connector_2.11</artifactId>
<version>${com.datastax.spark.spark-cassandra-connector.version}</version>
</dependency>
<dependency>
<groupId>com.datastax.spark</groupId>
<artifactId>spark-cassandra-connector-java_2.11</artifactId>
<version>${com.datastax.spark.spark-cassandra-connector-java.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.apache.spark.spark-core.version>2.2.0</org.apache.spark.spark-core.version>
<org.apache.spark.spark-core.version>2.3.0</org.apache.spark.spark-core.version>
<org.apache.spark.spark-sql.version>2.3.0</org.apache.spark.spark-sql.version>
<org.apache.spark.spark-streaming.version>2.3.0</org.apache.spark.spark-streaming.version>
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -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;
}
}

View File

@ -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<String, Object> 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<String> 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<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
.iterator());
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((i1, i2) -> i1 + i2);
wordCounts.foreachRDD(javaRdd -> {
Map<String, Integer> wordCountMap = javaRdd.collectAsMap();
for (String key : wordCountMap.keySet()) {
List<Word> wordList = Arrays.asList(new Word(key, wordCountMap.get(key)));
JavaRDD<Word> rdd = streamingContext.sparkContext()
.parallelize(wordList);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
});
streamingContext.start();
streamingContext.awaitTermination();
}
}

View File

@ -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<String, Object> 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<String> 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<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(streamingContext, LocationStrategies.PreferConsistent(), ConsumerStrategies.<String, String> Subscribe(topics, kafkaParams));
JavaPairDStream<String, String> results = messages.mapToPair(record -> new Tuple2<>(record.key(), record.value()));
JavaDStream<String> lines = results.map(tuple2 -> tuple2._2());
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split("\\s+"))
.iterator());
JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
.reduceByKey((Function2<Integer, Integer, Integer>) (i1, i2) -> i1 + i2);
JavaMapWithStateDStream<String, Integer, Integer, Tuple2<String, Integer>> cumulativeWordCounts = wordCounts.mapWithState(StateSpec.function((word, one, state) -> {
int sum = one.orElse(0) + (state.exists() ? state.get() : 0);
Tuple2<String, Integer> output = new Tuple2<>(word, sum);
state.update(sum);
return output;
}));
cumulativeWordCounts.foreachRDD(javaRdd -> {
List<Tuple2<String, Integer>> wordCountList = javaRdd.collect();
for (Tuple2<String, Integer> tuple : wordCountList) {
List<Word> wordList = Arrays.asList(new Word(tuple._1, tuple._2));
JavaRDD<Word> rdd = sparkContext.parallelize(wordList);
javaFunctions(rdd).writerBuilder("vocabulary", "words", mapToRow(Word.class))
.saveToCassandra();
}
});
streamingContext.start();
streamingContext.awaitTermination();
}
}

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<version>0.1-SNAPSHOT</version>
<artifactId>apache-velocity</artifactId>
<packaging>war</packaging>
<name>apache-velocity</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -59,7 +59,6 @@
</build>
<properties>
<jstl.version>1.2</jstl.version>
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)
- [Introduction to AutoFactory](http://www.baeldung.com/autofactory)
- [Google AutoService](https://www.baeldung.com/google-autoservice)

View File

@ -29,6 +29,12 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>${auto-service.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
@ -40,6 +46,7 @@
<properties>
<auto-value.version>1.3</auto-value.version>
<auto-factory.version>1.0-beta5</auto-factory.version>
<auto-service.version>1.0-rc5</auto-service.version>
<guice.version>4.2.0</guice.version>
</properties>

View File

@ -1,8 +1,9 @@
package com.baeldung.autofactory.provided;
import com.baeldung.autofactory.model.Camera;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
import javafx.scene.Camera;
import javax.inject.Provider;

View File

@ -0,0 +1,14 @@
package com.baeldung.autoservice;
import com.google.auto.service.AutoService;
import java.util.Locale;
@AutoService(TranslationService.class)
public class BingTranslationServiceProvider implements TranslationService {
@Override
public String translate(String message, Locale from, Locale to) {
// implementation details
return message + " (translated by Bing)";
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.autoservice;
import com.google.auto.service.AutoService;
import java.util.Locale;
@AutoService(TranslationService.class)
public class GoogleTranslationServiceProvider implements TranslationService {
@Override
public String translate(String message, Locale from, Locale to) {
// implementation details
return message + " (translated by Google)";
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.autoservice;
import java.util.Locale;
public interface TranslationService {
String translate(String message, Locale from, Locale to);
}

View File

@ -0,0 +1,37 @@
package com.baeldung.autoservice;
import com.baeldung.autoservice.TranslationService;
import org.junit.Before;
import org.junit.Test;
import java.util.ServiceLoader;
import java.util.stream.StreamSupport;
import static org.junit.Assert.assertEquals;
public class TranslationServiceUnitTest {
private ServiceLoader<TranslationService> loader;
@Before
public void setUp() {
loader = ServiceLoader.load(TranslationService.class);
}
@Test
public void whenServiceLoaderLoads_thenLoadsAllProviders() {
long count = StreamSupport.stream(loader.spliterator(), false).count();
assertEquals(2, count);
}
@Test
public void whenServiceLoaderLoadsGoogleService_thenGoogleIsLoaded() {
TranslationService googleService = StreamSupport.stream(loader.spliterator(), false)
.filter(p -> p.getClass().getSimpleName().equals("GoogleTranslationServiceProvider"))
.findFirst()
.get();
String message = "message";
assertEquals(message + " (translated by Google)", googleService.translate(message, null, null));
}
}

View File

@ -5,8 +5,8 @@
<groupId>com.baeldung</groupId>
<artifactId>aws-lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aws-lambda</name>
<packaging>jar</packaging>
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -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)

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>aws</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aws</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -4,29 +4,61 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>axon</artifactId>
<name>axon</name>
<description>Basic Axon Framework with Spring Boot configuration tutorial</description>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-spring-boot-starter</artifactId>
<version>${axon.version}</version>
<exclusions>
<exclusion>
<groupId>org.axonframework</groupId>
<artifactId>axon-server-connector</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-test</artifactId>
<version>${axon.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.axonframework</groupId>
<artifactId>axon-core</artifactId>
<version>${axon.version}</version>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<axon.version>3.0.2</axon.version>
<axon.version>4.0.3</axon.version>
</properties>
</project>

View File

@ -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<MessagesAggregate> repository =
new EventSourcingRepository<>(MessagesAggregate.class, eventStore);
AggregateAnnotationCommandHandler<MessagesAggregate> messagesAggregateAggregateAnnotationCommandHandler =
new AggregateAnnotationCommandHandler<MessagesAggregate>(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));
}
}

View File

@ -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);
}
}

View File

@ -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));
}
}

View File

@ -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
}
}

Some files were not shown because too many files have changed in this diff Show More