Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
ee7724345e
|
@ -1,3 +1,5 @@
|
||||||
|
*/bin/*
|
||||||
|
|
||||||
*.class
|
*.class
|
||||||
|
|
||||||
# Package Files #
|
# Package Files #
|
||||||
|
|
|
@ -1,11 +1,13 @@
|
||||||
language: java
|
language: java
|
||||||
|
|
||||||
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
|
install: travis_wait 60 mvn -q test
|
||||||
|
|
||||||
|
before_script:
|
||||||
|
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:MaxPermSize=2048M -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||||
|
|
||||||
jdk:
|
jdk:
|
||||||
- oraclejdk8
|
- oraclejdk8
|
||||||
|
|
||||||
sudo: false
|
|
||||||
addons:
|
addons:
|
||||||
apt:
|
apt:
|
||||||
packages:
|
packages:
|
||||||
|
@ -15,3 +17,5 @@ cache:
|
||||||
directories:
|
directories:
|
||||||
- .autoconf
|
- .autoconf
|
||||||
- $HOME/.m2
|
- $HOME/.m2
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
|
|
@ -0,0 +1,53 @@
|
||||||
|
<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/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.mabsisa</groupId>
|
||||||
|
<artifactId>Twitter4J</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<name>Twitter4J</name>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.twitter4j</groupId>
|
||||||
|
<artifactId>twitter4j-stream</artifactId>
|
||||||
|
<version>4.0.6</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.12</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>${project.artifactId}</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>2.19.1</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/ApplicationTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,116 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import twitter4j.DirectMessage;
|
||||||
|
import twitter4j.Query;
|
||||||
|
import twitter4j.QueryResult;
|
||||||
|
import twitter4j.StallWarning;
|
||||||
|
import twitter4j.Status;
|
||||||
|
import twitter4j.StatusDeletionNotice;
|
||||||
|
import twitter4j.StatusListener;
|
||||||
|
import twitter4j.Twitter;
|
||||||
|
import twitter4j.TwitterException;
|
||||||
|
import twitter4j.TwitterFactory;
|
||||||
|
import twitter4j.TwitterStream;
|
||||||
|
import twitter4j.TwitterStreamFactory;
|
||||||
|
import twitter4j.conf.ConfigurationBuilder;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static Twitter getTwitterinstance() {
|
||||||
|
/**
|
||||||
|
* if not using properties file, we can set access token by following way
|
||||||
|
*/
|
||||||
|
// ConfigurationBuilder cb = new ConfigurationBuilder();
|
||||||
|
// cb.setDebugEnabled(true)
|
||||||
|
// .setOAuthConsumerKey("//TODO")
|
||||||
|
// .setOAuthConsumerSecret("//TODO")
|
||||||
|
// .setOAuthAccessToken("//TODO")
|
||||||
|
// .setOAuthAccessTokenSecret("//TODO");
|
||||||
|
// TwitterFactory tf = new TwitterFactory(cb.build());
|
||||||
|
// Twitter twitter = tf.getSingleton();
|
||||||
|
|
||||||
|
Twitter twitter = TwitterFactory.getSingleton();
|
||||||
|
return twitter;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String createTweet(String tweet) throws TwitterException {
|
||||||
|
Twitter twitter = getTwitterinstance();
|
||||||
|
Status status = twitter.updateStatus("creating baeldung API");
|
||||||
|
return status.getText();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> getTimeLine() throws TwitterException {
|
||||||
|
Twitter twitter = getTwitterinstance();
|
||||||
|
List<Status> statuses = twitter.getHomeTimeline();
|
||||||
|
return statuses.stream().map(
|
||||||
|
item -> item.getText()).collect(
|
||||||
|
Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String sendDirectMessage(String recipientName, String msg) throws TwitterException {
|
||||||
|
Twitter twitter = getTwitterinstance();
|
||||||
|
DirectMessage message = twitter.sendDirectMessage(recipientName, msg);
|
||||||
|
return message.getText();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<String> searchtweets() throws TwitterException {
|
||||||
|
Twitter twitter = getTwitterinstance();
|
||||||
|
Query query = new Query("source:twitter4j baeldung");
|
||||||
|
QueryResult result = twitter.search(query);
|
||||||
|
List<Status> statuses = result.getTweets();
|
||||||
|
return statuses.stream().map(
|
||||||
|
item -> item.getText()).collect(
|
||||||
|
Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void streamFeed() {
|
||||||
|
|
||||||
|
StatusListener listener = new StatusListener(){
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onException(Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDeletionNotice(StatusDeletionNotice arg) {
|
||||||
|
System.out.println("Got a status deletion notice id:" + arg.getStatusId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onScrubGeo(long userId, long upToStatusId) {
|
||||||
|
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onStallWarning(StallWarning warning) {
|
||||||
|
System.out.println("Got stall warning:" + warning);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onStatus(Status status) {
|
||||||
|
System.out.println(status.getUser().getName() + " : " + status.getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
|
||||||
|
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
|
||||||
|
|
||||||
|
twitterStream.addListener(listener);
|
||||||
|
|
||||||
|
twitterStream.sample();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
oauth.consumerKey=//TODO
|
||||||
|
oauth.consumerSecret=//TODO
|
||||||
|
oauth.accessToken=//TODO
|
||||||
|
oauth.accessTokenSecret=//TODO
|
|
@ -0,0 +1,40 @@
|
||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import twitter4j.TwitterException;
|
||||||
|
|
||||||
|
public class ApplicationTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In order run this jUnit test you need to configure your API details in the twitter4j.properties
|
||||||
|
*/
|
||||||
|
|
||||||
|
String tweet = "baeldung is awsome";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenText_updateStatus() throws TwitterException {
|
||||||
|
String text = Application.createTweet(tweet);
|
||||||
|
assertEquals(tweet, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCredential_fetchStatus() throws TwitterException {
|
||||||
|
List<String> statuses = Application.getTimeLine();
|
||||||
|
List<String> expectedStatuses = new ArrayList<String>();
|
||||||
|
expectedStatuses.add(tweet);
|
||||||
|
assertEquals(expectedStatuses, statuses);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRecipientNameAndMessage_sendDirectMessage() throws TwitterException {
|
||||||
|
String msg = Application.sendDirectMessage("YOUR_RECCIPIENT_ID", tweet);
|
||||||
|
assertEquals(msg, tweet);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
/target/
|
|
@ -2,3 +2,6 @@
|
||||||
|
|
||||||
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
||||||
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
||||||
|
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||||
|
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
|
||||||
|
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||||
|
|
|
@ -9,15 +9,33 @@
|
||||||
<junit.version>4.12</junit.version>
|
<junit.version>4.12</junit.version>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||||
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-math3</artifactId>
|
||||||
|
<version>${commons-math3.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
<version>${junit.version}</version>
|
<version>${junit.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.jenetics</groupId>
|
||||||
|
<artifactId>jenetics</artifactId>
|
||||||
|
<version>3.7.0</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|
|
@ -9,13 +9,14 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||||
|
|
||||||
public class RunAlgorithm {
|
public class RunAlgorithm {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||||
Scanner in = new Scanner(System.in);
|
Scanner in = new Scanner(System.in);
|
||||||
System.out.println("Run algorithm:");
|
System.out.println("Run algorithm:");
|
||||||
System.out.println("1 - Simulated Annealing");
|
System.out.println("1 - Simulated Annealing");
|
||||||
System.out.println("2 - Slope One");
|
System.out.println("2 - Slope One");
|
||||||
System.out.println("3 - Simple Genetic Algorithm");
|
System.out.println("3 - Simple Genetic Algorithm");
|
||||||
System.out.println("4 - Ant Colony");
|
System.out.println("4 - Ant Colony");
|
||||||
|
System.out.println("5 - Dijkstra");
|
||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
|
@ -33,6 +34,9 @@ public class RunAlgorithm {
|
||||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||||
antColony.startAntOptimization();
|
antColony.startAntOptimization();
|
||||||
break;
|
break;
|
||||||
|
case 5:
|
||||||
|
System.out.println("Please run the DijkstraAlgorithmTest.");
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
System.out.println("Unknown option");
|
System.out.println("Unknown option");
|
||||||
break;
|
break;
|
|
@ -0,0 +1,203 @@
|
||||||
|
package com.baeldung.algorithms.ga.ant_colony;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.OptionalInt;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class AntColonyOptimization {
|
||||||
|
|
||||||
|
private double c = 1.0;
|
||||||
|
private double alpha = 1;
|
||||||
|
private double beta = 5;
|
||||||
|
private double evaporation = 0.5;
|
||||||
|
private double Q = 500;
|
||||||
|
private double antFactor = 0.8;
|
||||||
|
private double randomFactor = 0.01;
|
||||||
|
|
||||||
|
private int maxIterations = 1000;
|
||||||
|
|
||||||
|
private int numberOfCities;
|
||||||
|
private int numberOfAnts;
|
||||||
|
private double graph[][];
|
||||||
|
private double trails[][];
|
||||||
|
private List<Ant> ants = new ArrayList<>();
|
||||||
|
private Random random = new Random();
|
||||||
|
private double probabilities[];
|
||||||
|
|
||||||
|
private int currentIndex;
|
||||||
|
|
||||||
|
private int[] bestTourOrder;
|
||||||
|
private double bestTourLength;
|
||||||
|
|
||||||
|
public AntColonyOptimization(int noOfCities) {
|
||||||
|
graph = generateRandomMatrix(noOfCities);
|
||||||
|
numberOfCities = graph.length;
|
||||||
|
numberOfAnts = (int) (numberOfCities * antFactor);
|
||||||
|
|
||||||
|
trails = new double[numberOfCities][numberOfCities];
|
||||||
|
probabilities = new double[numberOfCities];
|
||||||
|
IntStream.range(0, numberOfAnts)
|
||||||
|
.forEach(i -> ants.add(new Ant(numberOfCities)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate initial solution
|
||||||
|
*/
|
||||||
|
public double[][] generateRandomMatrix(int n) {
|
||||||
|
double[][] randomMatrix = new double[n][n];
|
||||||
|
IntStream.range(0, n)
|
||||||
|
.forEach(i -> IntStream.range(0, n)
|
||||||
|
.forEach(j -> randomMatrix[i][j] = Math.abs(random.nextInt(100) + 1)));
|
||||||
|
return randomMatrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform ant optimization
|
||||||
|
*/
|
||||||
|
public void startAntOptimization() {
|
||||||
|
IntStream.rangeClosed(1, 3)
|
||||||
|
.forEach(i -> {
|
||||||
|
System.out.println("Attempt #" + i);
|
||||||
|
solve();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use this method to run the main logic
|
||||||
|
*/
|
||||||
|
public int[] solve() {
|
||||||
|
setupAnts();
|
||||||
|
clearTrails();
|
||||||
|
IntStream.range(0, maxIterations)
|
||||||
|
.forEach(i -> {
|
||||||
|
moveAnts();
|
||||||
|
updateTrails();
|
||||||
|
updateBest();
|
||||||
|
});
|
||||||
|
System.out.println("Best tour length: " + (bestTourLength - numberOfCities));
|
||||||
|
System.out.println("Best tour order: " + Arrays.toString(bestTourOrder));
|
||||||
|
return bestTourOrder.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare ants for the simulation
|
||||||
|
*/
|
||||||
|
private void setupAnts() {
|
||||||
|
IntStream.range(0, numberOfAnts)
|
||||||
|
.forEach(i -> {
|
||||||
|
ants.forEach(ant -> {
|
||||||
|
ant.clear();
|
||||||
|
ant.visitCity(-1, random.nextInt(numberOfCities));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
currentIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* At each iteration, move ants
|
||||||
|
*/
|
||||||
|
private void moveAnts() {
|
||||||
|
IntStream.range(currentIndex, numberOfCities - 1)
|
||||||
|
.forEach(i -> {
|
||||||
|
ants.forEach(ant -> ant.visitCity(currentIndex, selectNextCity(ant)));
|
||||||
|
currentIndex++;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Select next city for each ant
|
||||||
|
*/
|
||||||
|
private int selectNextCity(Ant ant) {
|
||||||
|
int t = random.nextInt(numberOfCities - currentIndex);
|
||||||
|
if (random.nextDouble() < randomFactor) {
|
||||||
|
OptionalInt cityIndex = IntStream.range(0, numberOfCities)
|
||||||
|
.filter(i -> i == t && !ant.visited(i))
|
||||||
|
.findFirst();
|
||||||
|
if (cityIndex.isPresent()) {
|
||||||
|
return cityIndex.getAsInt();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
calculateProbabilities(ant);
|
||||||
|
double r = random.nextDouble();
|
||||||
|
double total = 0;
|
||||||
|
for (int i = 0; i < numberOfCities; i++) {
|
||||||
|
total += probabilities[i];
|
||||||
|
if (total >= r) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new RuntimeException("There are no other cities");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the next city picks probabilites
|
||||||
|
*/
|
||||||
|
public void calculateProbabilities(Ant ant) {
|
||||||
|
int i = ant.trail[currentIndex];
|
||||||
|
double pheromone = 0.0;
|
||||||
|
for (int l = 0; l < numberOfCities; l++) {
|
||||||
|
if (!ant.visited(l)) {
|
||||||
|
pheromone += Math.pow(trails[i][l], alpha) * Math.pow(1.0 / graph[i][l], beta);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int j = 0; j < numberOfCities; j++) {
|
||||||
|
if (ant.visited(j)) {
|
||||||
|
probabilities[j] = 0.0;
|
||||||
|
} else {
|
||||||
|
double numerator = Math.pow(trails[i][j], alpha) * Math.pow(1.0 / graph[i][j], beta);
|
||||||
|
probabilities[j] = numerator / pheromone;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update trails that ants used
|
||||||
|
*/
|
||||||
|
private void updateTrails() {
|
||||||
|
for (int i = 0; i < numberOfCities; i++) {
|
||||||
|
for (int j = 0; j < numberOfCities; j++) {
|
||||||
|
trails[i][j] *= evaporation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (Ant a : ants) {
|
||||||
|
double contribution = Q / a.trailLength(graph);
|
||||||
|
for (int i = 0; i < numberOfCities - 1; i++) {
|
||||||
|
trails[a.trail[i]][a.trail[i + 1]] += contribution;
|
||||||
|
}
|
||||||
|
trails[a.trail[numberOfCities - 1]][a.trail[0]] += contribution;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the best solution
|
||||||
|
*/
|
||||||
|
private void updateBest() {
|
||||||
|
if (bestTourOrder == null) {
|
||||||
|
bestTourOrder = ants.get(0).trail;
|
||||||
|
bestTourLength = ants.get(0)
|
||||||
|
.trailLength(graph);
|
||||||
|
}
|
||||||
|
for (Ant a : ants) {
|
||||||
|
if (a.trailLength(graph) < bestTourLength) {
|
||||||
|
bestTourLength = a.trailLength(graph);
|
||||||
|
bestTourOrder = a.trail.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear trails after simulation
|
||||||
|
*/
|
||||||
|
private void clearTrails() {
|
||||||
|
IntStream.range(0, numberOfCities)
|
||||||
|
.forEach(i -> {
|
||||||
|
IntStream.range(0, numberOfCities)
|
||||||
|
.forEach(j -> trails[i][j] = c);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms.dijkstra;
|
package com.baeldung.algorithms.ga.dijkstra;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms.dijkstra;
|
package com.baeldung.algorithms.ga.dijkstra;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms.dijkstra;
|
package com.baeldung.algorithms.ga.dijkstra;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
|
@ -0,0 +1,47 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
|
||||||
|
import static org.jenetics.engine.limit.bySteadyFitness;
|
||||||
|
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.jenetics.BitChromosome;
|
||||||
|
import org.jenetics.BitGene;
|
||||||
|
import org.jenetics.Mutator;
|
||||||
|
import org.jenetics.Phenotype;
|
||||||
|
import org.jenetics.RouletteWheelSelector;
|
||||||
|
import org.jenetics.SinglePointCrossover;
|
||||||
|
import org.jenetics.TournamentSelector;
|
||||||
|
import org.jenetics.engine.Engine;
|
||||||
|
import org.jenetics.engine.EvolutionStatistics;
|
||||||
|
|
||||||
|
//The main class.
|
||||||
|
public class Knapsack {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int nItems = 15;
|
||||||
|
double ksSize = nItems * 100.0 / 3.0;
|
||||||
|
|
||||||
|
KnapsackFF ff = new KnapsackFF(Stream.generate(KnapsackItem::random)
|
||||||
|
.limit(nItems)
|
||||||
|
.toArray(KnapsackItem[]::new), ksSize);
|
||||||
|
|
||||||
|
Engine<BitGene, Double> engine = Engine.builder(ff, BitChromosome.of(nItems, 0.5))
|
||||||
|
.populationSize(500)
|
||||||
|
.survivorsSelector(new TournamentSelector<>(5))
|
||||||
|
.offspringSelector(new RouletteWheelSelector<>())
|
||||||
|
.alterers(new Mutator<>(0.115), new SinglePointCrossover<>(0.16))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
|
||||||
|
|
||||||
|
Phenotype<BitGene, Double> best = engine.stream()
|
||||||
|
.limit(bySteadyFitness(7))
|
||||||
|
.limit(100)
|
||||||
|
.peek(statistics)
|
||||||
|
.collect(toBestPhenotype());
|
||||||
|
|
||||||
|
System.out.println(statistics);
|
||||||
|
System.out.println(best);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import org.jenetics.BitChromosome;
|
||||||
|
import org.jenetics.BitGene;
|
||||||
|
import org.jenetics.Genotype;
|
||||||
|
|
||||||
|
public class KnapsackFF implements Function<Genotype<BitGene>, Double> {
|
||||||
|
private KnapsackItem[] items;
|
||||||
|
private double size;
|
||||||
|
|
||||||
|
public KnapsackFF(KnapsackItem[] items, double size) {
|
||||||
|
this.items = items;
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Double apply(Genotype<BitGene> gt) {
|
||||||
|
KnapsackItem sum = ((BitChromosome) gt.getChromosome()).ones()
|
||||||
|
.mapToObj(i -> items[i])
|
||||||
|
.collect(KnapsackItem.toSum());
|
||||||
|
return sum.size <= this.size ? sum.value : 0;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.stream.Collector;
|
||||||
|
|
||||||
|
import org.jenetics.util.RandomRegistry;
|
||||||
|
|
||||||
|
public class KnapsackItem {
|
||||||
|
|
||||||
|
public double size;
|
||||||
|
public double value;
|
||||||
|
|
||||||
|
public KnapsackItem(double size, double value) {
|
||||||
|
this.size = size;
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static KnapsackItem random() {
|
||||||
|
Random r = RandomRegistry.getRandom();
|
||||||
|
return new KnapsackItem(r.nextDouble() * 100, r.nextDouble() * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static Collector<KnapsackItem, ?, KnapsackItem> toSum() {
|
||||||
|
return Collector.of(() -> new double[2], (a, b) -> {
|
||||||
|
a[0] += b.size;
|
||||||
|
a[1] += b.value;
|
||||||
|
} , (a, b) -> {
|
||||||
|
a[0] += b[0];
|
||||||
|
a[1] += b[1];
|
||||||
|
return a;
|
||||||
|
} , r -> new KnapsackItem(r[0], r[1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import org.jenetics.BitChromosome;
|
||||||
|
import org.jenetics.BitGene;
|
||||||
|
import org.jenetics.Genotype;
|
||||||
|
import org.jenetics.engine.Engine;
|
||||||
|
import org.jenetics.engine.EvolutionResult;
|
||||||
|
import org.jenetics.util.Factory;
|
||||||
|
|
||||||
|
public class SimpleGeneticAlgorithm {
|
||||||
|
|
||||||
|
private static Integer eval(Genotype<BitGene> gt) {
|
||||||
|
return gt.getChromosome()
|
||||||
|
.as(BitChromosome.class)
|
||||||
|
.bitCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Factory<Genotype<BitGene>> gtf = Genotype.of(BitChromosome.of(10, 0.5));
|
||||||
|
System.out.println("Before the evolution:\n" + gtf);
|
||||||
|
|
||||||
|
Engine<BitGene, Integer> engine = Engine.builder(SimpleGeneticAlgorithm::eval, gtf)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Genotype<BitGene> result = engine.stream()
|
||||||
|
.limit(500)
|
||||||
|
.collect(EvolutionResult.toBestGenotype());
|
||||||
|
|
||||||
|
System.out.println("After the evolution:\n" + result);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,86 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import static java.util.Objects.requireNonNull;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.jenetics.BitGene;
|
||||||
|
import org.jenetics.engine.Codec;
|
||||||
|
import org.jenetics.engine.Engine;
|
||||||
|
import org.jenetics.engine.EvolutionResult;
|
||||||
|
import org.jenetics.engine.Problem;
|
||||||
|
import org.jenetics.engine.codecs;
|
||||||
|
import org.jenetics.util.ISeq;
|
||||||
|
|
||||||
|
public class SpringsteenProblem implements Problem<ISeq<SpringsteenRecord>, BitGene, Double> {
|
||||||
|
|
||||||
|
private ISeq<SpringsteenRecord> records;
|
||||||
|
private double maxPricePerUniqueSong;
|
||||||
|
|
||||||
|
public SpringsteenProblem(ISeq<SpringsteenRecord> records, double maxPricePerUniqueSong) {
|
||||||
|
this.records = requireNonNull(records);
|
||||||
|
this.maxPricePerUniqueSong = maxPricePerUniqueSong;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Function<ISeq<SpringsteenRecord>, Double> fitness() {
|
||||||
|
return SpringsteenRecords -> {
|
||||||
|
double cost = SpringsteenRecords.stream()
|
||||||
|
.mapToDouble(r -> r.price)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
int uniqueSongCount = SpringsteenRecords.stream()
|
||||||
|
.flatMap(r -> r.songs.stream())
|
||||||
|
.collect(Collectors.toSet())
|
||||||
|
.size();
|
||||||
|
|
||||||
|
double pricePerUniqueSong = cost / uniqueSongCount;
|
||||||
|
|
||||||
|
return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Codec<ISeq<SpringsteenRecord>, BitGene> codec() {
|
||||||
|
return codecs.ofSubSet(records);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
double maxPricePerUniqueSong = 2.5;
|
||||||
|
|
||||||
|
SpringsteenProblem springsteen = new SpringsteenProblem(
|
||||||
|
ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")),
|
||||||
|
new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")),
|
||||||
|
new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))),
|
||||||
|
maxPricePerUniqueSong);
|
||||||
|
|
||||||
|
Engine<BitGene, Double> engine = Engine.builder(springsteen)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
ISeq<SpringsteenRecord> result = springsteen.codec()
|
||||||
|
.decoder()
|
||||||
|
.apply(engine.stream()
|
||||||
|
.limit(10)
|
||||||
|
.collect(EvolutionResult.toBestGenotype()));
|
||||||
|
|
||||||
|
double cost = result.stream()
|
||||||
|
.mapToDouble(r -> r.price)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
int uniqueSongCount = result.stream()
|
||||||
|
.flatMap(r -> r.songs.stream())
|
||||||
|
.collect(Collectors.toSet())
|
||||||
|
.size();
|
||||||
|
|
||||||
|
double pricePerUniqueSong = cost / uniqueSongCount;
|
||||||
|
|
||||||
|
System.out.println("Overall cost: " + cost);
|
||||||
|
System.out.println("Unique songs: " + uniqueSongCount);
|
||||||
|
System.out.println("Cost per song: " + pricePerUniqueSong);
|
||||||
|
System.out.println("Records: " + result.map(r -> r.name)
|
||||||
|
.toString(", "));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import static java.util.Objects.requireNonNull;
|
||||||
|
|
||||||
|
import org.jenetics.util.ISeq;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
public class SpringsteenRecord {
|
||||||
|
|
||||||
|
String name;
|
||||||
|
double price;
|
||||||
|
ISeq<String> songs;
|
||||||
|
|
||||||
|
public SpringsteenRecord(String name, double price, ISeq<String> songs) {
|
||||||
|
this.name = requireNonNull(name);
|
||||||
|
this.price = price;
|
||||||
|
this.songs = requireNonNull(songs);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,66 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import static java.util.Objects.requireNonNull;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import org.jenetics.EnumGene;
|
||||||
|
import org.jenetics.Mutator;
|
||||||
|
import org.jenetics.PartiallyMatchedCrossover;
|
||||||
|
import org.jenetics.Phenotype;
|
||||||
|
import org.jenetics.engine.Codec;
|
||||||
|
import org.jenetics.engine.Engine;
|
||||||
|
import org.jenetics.engine.EvolutionResult;
|
||||||
|
import org.jenetics.engine.Problem;
|
||||||
|
import org.jenetics.engine.codecs;
|
||||||
|
import org.jenetics.engine.limit;
|
||||||
|
import org.jenetics.util.ISeq;
|
||||||
|
import org.jenetics.util.LCG64ShiftRandom;
|
||||||
|
|
||||||
|
public class SubsetSum implements Problem<ISeq<Integer>, EnumGene<Integer>, Integer> {
|
||||||
|
|
||||||
|
private ISeq<Integer> basicSet;
|
||||||
|
private int size;
|
||||||
|
|
||||||
|
public SubsetSum(ISeq<Integer> basicSet, int size) {
|
||||||
|
this.basicSet = requireNonNull(basicSet);
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Function<ISeq<Integer>, Integer> fitness() {
|
||||||
|
return subset -> Math.abs(subset.stream()
|
||||||
|
.mapToInt(Integer::intValue)
|
||||||
|
.sum());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Codec<ISeq<Integer>, EnumGene<Integer>> codec() {
|
||||||
|
return codecs.ofSubSet(basicSet, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SubsetSum of(int n, int k, Random random) {
|
||||||
|
return new SubsetSum(random.doubles()
|
||||||
|
.limit(n)
|
||||||
|
.mapToObj(d -> (int) ((d - 0.5) * n))
|
||||||
|
.collect(ISeq.toISeq()), k);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
SubsetSum problem = of(500, 15, new LCG64ShiftRandom(101010));
|
||||||
|
|
||||||
|
Engine<EnumGene<Integer>, Integer> engine = Engine.builder(problem)
|
||||||
|
.minimizing()
|
||||||
|
.maximalPhenotypeAge(5)
|
||||||
|
.alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Phenotype<EnumGene<Integer>, Integer> result = engine.stream()
|
||||||
|
.limit(limit.bySteadyFitness(55))
|
||||||
|
.collect(EvolutionResult.toBestPhenotype());
|
||||||
|
|
||||||
|
System.out.print(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
package com.baeldung.algorithms.ga.jenetics;
|
||||||
|
|
||||||
|
import static java.lang.Math.PI;
|
||||||
|
import static java.lang.Math.abs;
|
||||||
|
import static java.lang.Math.sin;
|
||||||
|
import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
|
||||||
|
import static org.jenetics.engine.limit.bySteadyFitness;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.jenetics.EnumGene;
|
||||||
|
import org.jenetics.Optimize;
|
||||||
|
import org.jenetics.PartiallyMatchedCrossover;
|
||||||
|
import org.jenetics.Phenotype;
|
||||||
|
import org.jenetics.SwapMutator;
|
||||||
|
import org.jenetics.engine.Engine;
|
||||||
|
import org.jenetics.engine.EvolutionStatistics;
|
||||||
|
import org.jenetics.engine.codecs;
|
||||||
|
|
||||||
|
public class TravelingSalesman {
|
||||||
|
|
||||||
|
private static final int STOPS = 50;
|
||||||
|
private static final double[][] ADJACENCE = matrix(STOPS);
|
||||||
|
|
||||||
|
private static double[][] matrix(int stops) {
|
||||||
|
final double radius = 100.0;
|
||||||
|
double[][] matrix = new double[stops][stops];
|
||||||
|
|
||||||
|
for (int i = 0; i < stops; ++i) {
|
||||||
|
for (int j = 0; j < stops; ++j) {
|
||||||
|
matrix[i][j] = chord(stops, abs(i - j), radius);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double chord(int stops, int i, double r) {
|
||||||
|
return 2.0 * r * abs(sin(PI * i / stops));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double dist(final int[] path) {
|
||||||
|
return IntStream.range(0, STOPS)
|
||||||
|
.mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]])
|
||||||
|
.sum();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
final Engine<EnumGene<Integer>, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS))
|
||||||
|
.optimize(Optimize.MINIMUM)
|
||||||
|
.maximalPhenotypeAge(11)
|
||||||
|
.populationSize(500)
|
||||||
|
.alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
|
||||||
|
|
||||||
|
final Phenotype<EnumGene<Integer>, Double> best = engine.stream()
|
||||||
|
.limit(bySteadyFitness(15))
|
||||||
|
.limit(250)
|
||||||
|
.peek(statistics)
|
||||||
|
.collect(toBestPhenotype());
|
||||||
|
|
||||||
|
System.out.println(statistics);
|
||||||
|
System.out.println(best);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
public class BigIntegerPrimeChecker implements PrimeChecker<Long>{
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isPrime(Long number) {
|
||||||
|
BigInteger bigInt = BigInteger.valueOf(number);
|
||||||
|
return bigInt.isProbablePrime(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.LongStream;
|
||||||
|
|
||||||
|
public class BruteForcePrimeChecker implements PrimeChecker<Integer>{
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isPrime(Integer number) {
|
||||||
|
|
||||||
|
return number > 2 ? IntStream.range(2, number)
|
||||||
|
.noneMatch(n -> (number % n == 0)) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.stream.LongStream;
|
||||||
|
|
||||||
|
public class OptimisedPrimeChecker implements PrimeChecker<Integer>{
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isPrime(Integer number) {
|
||||||
|
return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number))
|
||||||
|
.noneMatch(n -> (number % n == 0)) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
public interface PrimeChecker <T> {
|
||||||
|
|
||||||
|
public boolean isPrime( T number );
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import org.apache.commons.math3.primes.Primes;
|
||||||
|
|
||||||
|
public class PrimesPrimeChecker implements PrimeChecker<Integer>{
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isPrime(Integer number) {
|
||||||
|
return Primes.isPrime(number);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finite state machine.
|
||||||
|
*/
|
||||||
|
public interface FiniteStateMachine {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Follow a transition, switch the state of the machine.
|
||||||
|
* @param c Char.
|
||||||
|
* @return A new finite state machine with the new state.
|
||||||
|
*/
|
||||||
|
FiniteStateMachine switchState(final CharSequence c);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Is the current state a final one?
|
||||||
|
* @return true or false.
|
||||||
|
*/
|
||||||
|
boolean canStop();
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default implementation of a finite state machine.
|
||||||
|
* This class is immutable and thread-safe.
|
||||||
|
*/
|
||||||
|
public final class RtFiniteStateMachine implements FiniteStateMachine {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Current state.
|
||||||
|
*/
|
||||||
|
private State current;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ctor.
|
||||||
|
* @param initial Initial state of this machine.
|
||||||
|
*/
|
||||||
|
public RtFiniteStateMachine(final State initial) {
|
||||||
|
this.current = initial;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FiniteStateMachine switchState(final CharSequence c) {
|
||||||
|
return new RtFiniteStateMachine(this.current.transit(c));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean canStop() {
|
||||||
|
return this.current.isFinal();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* State in a finite state machine.
|
||||||
|
*/
|
||||||
|
public final class RtState implements State {
|
||||||
|
|
||||||
|
private List<Transition> transitions;
|
||||||
|
private boolean isFinal;
|
||||||
|
|
||||||
|
public RtState() {
|
||||||
|
this(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RtState(final boolean isFinal) {
|
||||||
|
this.transitions = new ArrayList<>();
|
||||||
|
this.isFinal = isFinal;
|
||||||
|
}
|
||||||
|
|
||||||
|
public State transit(final CharSequence c) {
|
||||||
|
return transitions
|
||||||
|
.stream()
|
||||||
|
.filter(t -> t.isPossible(c))
|
||||||
|
.map(Transition::state)
|
||||||
|
.findAny()
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Input not accepted: " + c));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFinal() {
|
||||||
|
return this.isFinal;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public State with(Transition tr) {
|
||||||
|
this.transitions.add(tr);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transition in finite state machine.
|
||||||
|
*/
|
||||||
|
public final class RtTransition implements Transition {
|
||||||
|
|
||||||
|
private String rule;
|
||||||
|
private State next;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ctor.
|
||||||
|
* @param rule Rule that a character has to meet
|
||||||
|
* in order to get to the next state.
|
||||||
|
* @param next Next state.
|
||||||
|
*/
|
||||||
|
public RtTransition (String rule, State next) {
|
||||||
|
this.rule = rule;
|
||||||
|
this.next = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public State state() {
|
||||||
|
return this.next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPossible(CharSequence c) {
|
||||||
|
return this.rule.equalsIgnoreCase(String.valueOf(c));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* State. Part of a finite state machine.
|
||||||
|
*/
|
||||||
|
public interface State {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a Transition to this state.
|
||||||
|
* @param tr Given transition.
|
||||||
|
* @return Modified State.
|
||||||
|
*/
|
||||||
|
State with(final Transition tr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Follow one of the transitions, to get
|
||||||
|
* to the next state.
|
||||||
|
* @param c Character.
|
||||||
|
* @return State.
|
||||||
|
* @throws IllegalStateException if the char is not accepted.
|
||||||
|
*/
|
||||||
|
State transit(final CharSequence c);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Can the automaton stop on this state?
|
||||||
|
* @return true or false
|
||||||
|
*/
|
||||||
|
boolean isFinal();
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.automata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transition in a finite State machine.
|
||||||
|
*/
|
||||||
|
public interface Transition {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Is the transition possible with the given character?
|
||||||
|
* @param c char.
|
||||||
|
* @return true or false.
|
||||||
|
*/
|
||||||
|
boolean isPossible(final CharSequence c);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The state to which this transition leads.
|
||||||
|
* @return State.
|
||||||
|
*/
|
||||||
|
State state();
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
@ -16,7 +16,7 @@ public class AntColonyOptimizationTest {
|
||||||
@Test
|
@Test
|
||||||
public void testStartAntOptimization() {
|
public void testStartAntOptimization() {
|
||||||
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
||||||
Assert.assertNotNull(antTSP.startAntOptimization());
|
Assert.assertNotNull(antTSP.solve());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
|
@ -1,10 +1,11 @@
|
||||||
package algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import com.baeldung.algorithms.dijkstra.Dijkstra;
|
|
||||||
import com.baeldung.algorithms.dijkstra.Graph;
|
|
||||||
import com.baeldung.algorithms.dijkstra.Node;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
|
||||||
|
import com.baeldung.algorithms.ga.dijkstra.Graph;
|
||||||
|
import com.baeldung.algorithms.ga.dijkstra.Node;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,82 @@
|
||||||
|
package algorithms;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.baeldung.automata.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for {@link RtFiniteStateMachine}
|
||||||
|
*/
|
||||||
|
public final class RtFiniteStateMachineTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void acceptsSimplePair() {
|
||||||
|
String json = "{\"key\":\"value\"}";
|
||||||
|
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||||
|
for (int i=0;i<json.length();i++) {
|
||||||
|
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||||
|
}
|
||||||
|
assertTrue(machine.canStop());
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void acceptsMorePairs() {
|
||||||
|
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
|
||||||
|
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||||
|
for (int i=0;i<json.length();i++) {
|
||||||
|
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||||
|
}
|
||||||
|
assertTrue(machine.canStop());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void missingColon() {
|
||||||
|
String json = "{\"key\"\"value\"}";
|
||||||
|
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||||
|
for (int i=0;i<json.length();i++) {
|
||||||
|
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a finite state machine to validate a simple
|
||||||
|
* Json object.
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private FiniteStateMachine buildJsonStateMachine() {
|
||||||
|
State first = new RtState();
|
||||||
|
State second = new RtState();
|
||||||
|
State third = new RtState();
|
||||||
|
State fourth = new RtState();
|
||||||
|
State fifth = new RtState();
|
||||||
|
State sixth = new RtState();
|
||||||
|
State seventh = new RtState();
|
||||||
|
State eighth = new RtState(true);
|
||||||
|
|
||||||
|
first.with(new RtTransition("{", second));
|
||||||
|
second.with(new RtTransition("\"", third));
|
||||||
|
//Add transitions with chars 0-9 and a-z
|
||||||
|
for (int i = 0; i < 26; i++) {
|
||||||
|
if(i<10) {
|
||||||
|
third = third.with(
|
||||||
|
new RtTransition(String.valueOf(i), third)
|
||||||
|
);
|
||||||
|
sixth = sixth.with(
|
||||||
|
new RtTransition(String.valueOf(i), sixth)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
third = third.with(
|
||||||
|
new RtTransition(String.valueOf((char) ('a' + i)), third)
|
||||||
|
);
|
||||||
|
sixth = sixth.with(
|
||||||
|
new RtTransition(String.valueOf((char) ('a' + i)), sixth)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
third.with(new RtTransition("\"", fourth));
|
||||||
|
fourth.with(new RtTransition(":", fifth));
|
||||||
|
fifth.with(new RtTransition("\"", sixth));
|
||||||
|
sixth.with(new RtTransition("\"", seventh));
|
||||||
|
seventh.with(new RtTransition(",", second));
|
||||||
|
seventh.with(new RtTransition("}", eighth));
|
||||||
|
return new RtFiniteStateMachine(first);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms;
|
package algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.primechecker.BigIntegerPrimeChecker;
|
||||||
|
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||||
|
|
||||||
|
public class BigIntegerPrimeCheckerTest {
|
||||||
|
|
||||||
|
BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||||
|
assertTrue(primeChecker.isPrime(13l));
|
||||||
|
assertTrue(primeChecker.isPrime(1009L));
|
||||||
|
assertTrue(primeChecker.isPrime(74207281L));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||||
|
assertTrue(!primeChecker.isPrime(50L));
|
||||||
|
assertTrue(!primeChecker.isPrime(1001L));
|
||||||
|
assertTrue(!primeChecker.isPrime(74207282L));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.primechecker.BruteForcePrimeChecker;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
public class BruteForcePrimeCheckerTest {
|
||||||
|
|
||||||
|
BruteForcePrimeChecker primeChecker = new BruteForcePrimeChecker();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||||
|
assertTrue(primeChecker.isPrime(13));
|
||||||
|
assertTrue(primeChecker.isPrime(1009));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||||
|
assertTrue(!primeChecker.isPrime(50));
|
||||||
|
assertTrue(!primeChecker.isPrime(1001));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.primechecker.OptimisedPrimeChecker;
|
||||||
|
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||||
|
|
||||||
|
public class OptimisedPrimeCheckerTest {
|
||||||
|
|
||||||
|
OptimisedPrimeChecker primeChecker = new OptimisedPrimeChecker();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrimeNumber_whenCheckIsPrime_thenTrue(){
|
||||||
|
assertTrue(primeChecker.isPrime(13));
|
||||||
|
assertTrue(primeChecker.isPrime(1009));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse(){
|
||||||
|
assertTrue(!primeChecker.isPrime(50));
|
||||||
|
assertTrue(!primeChecker.isPrime(1001));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.algorithms.primechecker;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.primechecker.PrimeChecker;
|
||||||
|
import com.baeldung.algorithms.primechecker.PrimesPrimeChecker;
|
||||||
|
|
||||||
|
public class PrimesPrimeCheckerTest {
|
||||||
|
PrimesPrimeChecker primeChecker = new PrimesPrimeChecker();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPrimeNumber_whenCheckIsPrime_thenTrue() {
|
||||||
|
assertTrue(primeChecker.isPrime(13));
|
||||||
|
assertTrue(primeChecker.isPrime(1009));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonPrimeNumber_whenCheckIsPrime_thenFalse() {
|
||||||
|
assertTrue(!primeChecker.isPrime(50));
|
||||||
|
assertTrue(!primeChecker.isPrime(1001));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -101,9 +101,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.dbdoclet</groupId>
|
<groupId>org.dbdoclet</groupId>
|
||||||
<artifactId>herold</artifactId>
|
<artifactId>herold</artifactId>
|
||||||
<version>6.1.0</version>
|
<version>8.0.4</version>
|
||||||
<scope>system</scope>
|
|
||||||
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -140,6 +138,8 @@
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
|
<forkCount>3</forkCount>
|
||||||
|
<reuseForks>true</reuseForks>
|
||||||
<excludes>
|
<excludes>
|
||||||
<exclude>**/*IntegrationTest.java</exclude>
|
<exclude>**/*IntegrationTest.java</exclude>
|
||||||
<exclude>**/*LiveTest.java</exclude>
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
|
|
@ -19,21 +19,21 @@ import javax.xml.transform.stream.StreamSource;
|
||||||
import org.apache.fop.apps.Fop;
|
import org.apache.fop.apps.Fop;
|
||||||
import org.apache.fop.apps.FopFactory;
|
import org.apache.fop.apps.FopFactory;
|
||||||
import org.apache.xmlgraphics.util.MimeConstants;
|
import org.apache.xmlgraphics.util.MimeConstants;
|
||||||
import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
|
import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
|
||||||
import org.dbdoclet.trafo.script.Script;
|
import org.dbdoclet.trafo.script.Script;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
import org.w3c.tidy.Tidy;
|
import org.w3c.tidy.Tidy;
|
||||||
|
|
||||||
public class ApacheFOPConvertHTMLIntegrationTest {
|
public class ApacheFOPConvertHTMLIntegrationTest {
|
||||||
private String inputFile = "src/test/resources/input.html";
|
private final String inputFile = "src/test/resources/input.html";
|
||||||
private String style = "src/test/resources/xhtml2fo.xsl";
|
private final String style = "src/test/resources/xhtml2fo.xsl";
|
||||||
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
private final String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||||
private String output_jtidy = "src/test/resources/output_jtidy.pdf";
|
private final String output_jtidy = "src/test/resources/output_jtidy.pdf";
|
||||||
private String output_html2fo = "src/test/resources/output_html2fo.pdf";
|
private final String output_html2fo = "src/test/resources/output_html2fo.pdf";
|
||||||
private String output_herold = "src/test/resources/output_herold.pdf";
|
private final String output_herold = "src/test/resources/output_herold.pdf";
|
||||||
private String foFile = "src/test/resources/input.fo";
|
private final String foFile = "src/test/resources/input.fo";
|
||||||
private String xmlFile = "src/test/resources/input.xml";
|
private final String xmlFile = "src/test/resources/input.xml";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenTransformHTMLToPDFUsingJTidy_thenCorrect() throws Exception {
|
public void whenTransformHTMLToPDFUsingJTidy_thenCorrect() throws Exception {
|
||||||
|
@ -114,8 +114,9 @@ public class ApacheFOPConvertHTMLIntegrationTest {
|
||||||
|
|
||||||
private void fromHTMLTOXMLUsingHerold() throws Exception {
|
private void fromHTMLTOXMLUsingHerold() throws Exception {
|
||||||
final Script script = new Script();
|
final Script script = new Script();
|
||||||
final DocBookTransformer transformer = new DocBookTransformer();
|
final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
|
||||||
transformer.setScript(script);
|
transformer.setInputStream(new FileInputStream(inputFile));
|
||||||
transformer.convert(new FileInputStream(inputFile), new FileOutputStream(xmlFile));
|
transformer.setOutputStream(new FileOutputStream(xmlFile));
|
||||||
|
transformer.transform(script);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,7 @@ import java.io.FileWriter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
|
||||||
import javax.xml.transform.Result;
|
import javax.xml.transform.Result;
|
||||||
|
@ -25,19 +26,15 @@ import org.apache.fop.apps.Fop;
|
||||||
import org.apache.fop.apps.FopFactory;
|
import org.apache.fop.apps.FopFactory;
|
||||||
import org.apache.xmlgraphics.util.MimeConstants;
|
import org.apache.xmlgraphics.util.MimeConstants;
|
||||||
import org.dbdoclet.trafo.TrafoScriptManager;
|
import org.dbdoclet.trafo.TrafoScriptManager;
|
||||||
import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
|
import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
|
||||||
import org.dbdoclet.trafo.script.Script;
|
import org.dbdoclet.trafo.script.Script;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.w3c.dom.Document;
|
import org.w3c.dom.Document;
|
||||||
|
|
||||||
public class ApacheFOPHeroldLiveTest {
|
public class ApacheFOPHeroldLiveTest {
|
||||||
private String[] inputUrls = {// @formatter:off
|
private final String[] inputUrls = {// @formatter:off
|
||||||
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
|
// "http://www.baeldung.com/spring-security-basic-authentication",
|
||||||
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
|
"http://www.baeldung.com/spring-security-digest-authentication"
|
||||||
"http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/",
|
|
||||||
"http://www.baeldung.com/spring-security-basic-authentication",
|
|
||||||
"http://www.baeldung.com/spring-security-digest-authentication",
|
|
||||||
"http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/",
|
|
||||||
//"http://www.baeldung.com/spring-httpmessageconverter-rest",
|
//"http://www.baeldung.com/spring-httpmessageconverter-rest",
|
||||||
//"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/",
|
//"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/",
|
||||||
//"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/",
|
//"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/",
|
||||||
|
@ -49,10 +46,10 @@ public class ApacheFOPHeroldLiveTest {
|
||||||
//"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/"
|
//"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/"
|
||||||
}; // @formatter:on
|
}; // @formatter:on
|
||||||
|
|
||||||
private String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
private final String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||||
private String output_file = "src/test/resources/final_output.pdf";
|
private final String output_file = "src/test/resources/final_output.pdf";
|
||||||
private String xmlInput = "src/test/resources/input.xml";
|
private final String xmlInput = "src/test/resources/input.xml";
|
||||||
private String xmlOutput = "src/test/resources/output.xml";
|
private final String xmlOutput = "src/test/resources/output.xml";
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
||||||
|
@ -75,10 +72,11 @@ public class ApacheFOPHeroldLiveTest {
|
||||||
final TrafoScriptManager mgr = new TrafoScriptManager();
|
final TrafoScriptManager mgr = new TrafoScriptManager();
|
||||||
final File profileFile = new File("src/test/resources/default.her");
|
final File profileFile = new File("src/test/resources/default.her");
|
||||||
script = mgr.parseScript(profileFile);
|
script = mgr.parseScript(profileFile);
|
||||||
final DocBookTransformer transformer = new DocBookTransformer();
|
final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
|
||||||
transformer.setScript(script);
|
transformer.setInputStream(getInputStream(input));
|
||||||
|
transformer.setOutputStream(new FileOutputStream(xmlInput, append));
|
||||||
|
|
||||||
transformer.convert(getInputStream(input), new FileOutputStream(xmlInput, append));
|
transformer.transform(script);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Document fromXMLFileToFO() throws Exception {
|
private Document fromXMLFileToFO() throws Exception {
|
||||||
|
@ -112,7 +110,9 @@ public class ApacheFOPHeroldLiveTest {
|
||||||
|
|
||||||
private InputStream getInputStream(final String input) throws IOException {
|
private InputStream getInputStream(final String input) throws IOException {
|
||||||
final URL url = new URL(input);
|
final URL url = new URL(input);
|
||||||
return url.openStream();
|
final HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
|
||||||
|
httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
|
||||||
|
return httpcon.getInputStream();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void fixXML(final String input, final String output) throws IOException {
|
private void fixXML(final String input, final String output) throws IOException {
|
||||||
|
@ -127,7 +127,7 @@ public class ApacheFOPHeroldLiveTest {
|
||||||
|
|
||||||
if (line.contains("info>")) {
|
if (line.contains("info>")) {
|
||||||
writer.write(line.replace("info>", "section>"));
|
writer.write(line.replace("info>", "section>"));
|
||||||
} else if (!((line.startsWith("<?xml") || line.startsWith("<article") || line.startsWith("</article")) && count > 4)) {
|
} else if (!((line.startsWith("<?xml") || line.startsWith("<article") || line.startsWith("</article")) && (count > 4))) {
|
||||||
writer.write(line.replaceAll("xml:id=\"", "xml:id=\"" + count));
|
writer.write(line.replaceAll("xml:id=\"", "xml:id=\"" + count));
|
||||||
}
|
}
|
||||||
writer.write("\n");
|
writer.write("\n");
|
||||||
|
|
Binary file not shown.
|
@ -1 +1,3 @@
|
||||||
*.docx
|
*.docx
|
||||||
|
temp.xls
|
||||||
|
temp.xlsx
|
||||||
|
|
Binary file not shown.
|
@ -0,0 +1,4 @@
|
||||||
|
## Apache Solrj Tutorials Project
|
||||||
|
|
||||||
|
### Relevant Articles
|
||||||
|
- [Guide to Solr in Java with Apache Solrj](http://www.baeldung.com/apache-solrj)
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.solrjava;
|
||||||
|
|
||||||
|
import org.apache.solr.client.solrj.beans.Field;
|
||||||
|
|
||||||
|
public class ProductBean {
|
||||||
|
|
||||||
|
String id;
|
||||||
|
String name;
|
||||||
|
String price;
|
||||||
|
|
||||||
|
public ProductBean(String id, String name, String price) {
|
||||||
|
super();
|
||||||
|
this.id = id;
|
||||||
|
this.name = name;
|
||||||
|
this.price = price;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Field("id")
|
||||||
|
protected void setId(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Field("name")
|
||||||
|
protected void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPrice() {
|
||||||
|
return price;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Field("price")
|
||||||
|
protected void setPrice(String price) {
|
||||||
|
this.price = price;
|
||||||
|
}
|
||||||
|
}
|
|
@ -17,6 +17,12 @@ public class SolrJavaIntegration {
|
||||||
solrClient.setParser(new XMLResponseParser());
|
solrClient.setParser(new XMLResponseParser());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
|
||||||
|
|
||||||
|
solrClient.addBean(pBean);
|
||||||
|
solrClient.commit();
|
||||||
|
}
|
||||||
|
|
||||||
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
|
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
|
||||||
|
|
||||||
SolrInputDocument document = new SolrInputDocument();
|
SolrInputDocument document = new SolrInputDocument();
|
||||||
|
@ -27,12 +33,18 @@ public class SolrJavaIntegration {
|
||||||
solrClient.commit();
|
solrClient.commit();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
|
public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
|
||||||
|
|
||||||
solrClient.deleteById(documentId);
|
solrClient.deleteById(documentId);
|
||||||
solrClient.commit();
|
solrClient.commit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
|
||||||
|
|
||||||
|
solrClient.deleteByQuery(query);
|
||||||
|
solrClient.commit();
|
||||||
|
}
|
||||||
|
|
||||||
protected HttpSolrClient getSolrClient() {
|
protected HttpSolrClient getSolrClient() {
|
||||||
return solrClient;
|
return solrClient;
|
||||||
}
|
}
|
||||||
|
@ -40,4 +52,5 @@ public class SolrJavaIntegration {
|
||||||
protected void setSolrClient(HttpSolrClient solrClient) {
|
protected void setSolrClient(HttpSolrClient solrClient) {
|
||||||
this.solrClient = solrClient;
|
this.solrClient = solrClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,7 @@ public class SolrJavaIntegrationTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
|
public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
|
||||||
|
|
||||||
SolrQuery query = new SolrQuery();
|
SolrQuery query = new SolrQuery();
|
||||||
query.set("q", "id:123456");
|
query.set("q", "id:123456");
|
||||||
|
@ -33,18 +33,68 @@ public class SolrJavaIntegrationTest {
|
||||||
response = solrJavaIntegration.getSolrClient().query(query);
|
response = solrJavaIntegration.getSolrClient().query(query);
|
||||||
|
|
||||||
SolrDocumentList docList = response.getResults();
|
SolrDocumentList docList = response.getResults();
|
||||||
assertEquals(docList.getNumFound(), 1);
|
assertEquals(1, docList.getNumFound());
|
||||||
|
|
||||||
for (SolrDocument doc : docList) {
|
for (SolrDocument doc : docList) {
|
||||||
assertEquals((String) doc.getFieldValue("id"), "123456");
|
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||||
assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99);
|
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
|
public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
|
||||||
|
|
||||||
solrJavaIntegration.deleteSolrDocument("123456");
|
SolrQuery query = new SolrQuery();
|
||||||
|
query.set("q", "price:599.99");
|
||||||
|
QueryResponse response = null;
|
||||||
|
|
||||||
|
response = solrJavaIntegration.getSolrClient().query(query);
|
||||||
|
|
||||||
|
SolrDocumentList docList = response.getResults();
|
||||||
|
assertEquals(1, docList.getNumFound());
|
||||||
|
|
||||||
|
for (SolrDocument doc : docList) {
|
||||||
|
assertEquals("123456", (String) doc.getFieldValue("id"));
|
||||||
|
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||||
|
|
||||||
|
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
|
||||||
|
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||||
|
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||||
|
|
||||||
|
ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
|
||||||
|
solrJavaIntegration.addProductBean(pBean);
|
||||||
|
|
||||||
|
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
|
||||||
|
assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
|
||||||
|
assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||||
|
|
||||||
|
solrJavaIntegration.deleteSolrDocumentById("123456");
|
||||||
|
|
||||||
|
SolrQuery query = new SolrQuery();
|
||||||
|
query.set("q", "id:123456");
|
||||||
|
QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
|
||||||
|
|
||||||
|
SolrDocumentList docList = response.getResults();
|
||||||
|
assertEquals(0, docList.getNumFound());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||||
|
|
||||||
|
solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
|
||||||
|
|
||||||
SolrQuery query = new SolrQuery();
|
SolrQuery query = new SolrQuery();
|
||||||
query.set("q", "id:123456");
|
query.set("q", "id:123456");
|
||||||
|
@ -53,6 +103,6 @@ public class SolrJavaIntegrationTest {
|
||||||
response = solrJavaIntegration.getSolrClient().query(query);
|
response = solrJavaIntegration.getSolrClient().query(query);
|
||||||
|
|
||||||
SolrDocumentList docList = response.getResults();
|
SolrDocumentList docList = response.getResults();
|
||||||
assertEquals(docList.getNumFound(), 0);
|
assertEquals(0, docList.getNumFound());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant articles
|
||||||
|
|
||||||
|
- [A Guide to the Axon Framework](http://www.baeldung.com/axon-cqrs-event-sourcing)
|
|
@ -0,0 +1,52 @@
|
||||||
|
<?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">
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<artifactId>axon</artifactId>
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<axon.version>3.0.2</axon.version>
|
||||||
|
<junit.version>4.12</junit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,54 @@
|
||||||
|
package com.baeldung.axon;
|
||||||
|
|
||||||
|
import com.baeldung.axon.aggregates.MessagesAggregate;
|
||||||
|
import com.baeldung.axon.commands.CreateMessageCommand;
|
||||||
|
import com.baeldung.axon.commands.MarkReadMessageCommand;
|
||||||
|
import com.baeldung.axon.eventhandlers.MessagesEventHandler;
|
||||||
|
import org.axonframework.commandhandling.AggregateAnnotationCommandHandler;
|
||||||
|
import org.axonframework.commandhandling.CommandBus;
|
||||||
|
import org.axonframework.commandhandling.SimpleCommandBus;
|
||||||
|
import org.axonframework.commandhandling.gateway.CommandGateway;
|
||||||
|
import org.axonframework.commandhandling.gateway.DefaultCommandGateway;
|
||||||
|
import org.axonframework.eventhandling.AnnotationEventListenerAdapter;
|
||||||
|
import org.axonframework.eventsourcing.EventSourcingRepository;
|
||||||
|
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
|
||||||
|
import org.axonframework.eventsourcing.eventstore.EventStore;
|
||||||
|
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class MessagesRunner {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
CommandBus commandBus = new SimpleCommandBus();
|
||||||
|
|
||||||
|
CommandGateway commandGateway = new DefaultCommandGateway(commandBus);
|
||||||
|
|
||||||
|
EventStore eventStore = new EmbeddedEventStore(new InMemoryEventStorageEngine());
|
||||||
|
|
||||||
|
EventSourcingRepository<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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.baeldung.axon.aggregates;
|
||||||
|
|
||||||
|
import com.baeldung.axon.commands.CreateMessageCommand;
|
||||||
|
import com.baeldung.axon.commands.MarkReadMessageCommand;
|
||||||
|
import com.baeldung.axon.events.MessageCreatedEvent;
|
||||||
|
import com.baeldung.axon.events.MessageReadEvent;
|
||||||
|
import org.axonframework.commandhandling.CommandHandler;
|
||||||
|
import org.axonframework.commandhandling.model.AggregateIdentifier;
|
||||||
|
import org.axonframework.eventhandling.EventHandler;
|
||||||
|
|
||||||
|
import static org.axonframework.commandhandling.model.AggregateLifecycle.apply;
|
||||||
|
|
||||||
|
|
||||||
|
public class MessagesAggregate {
|
||||||
|
|
||||||
|
@AggregateIdentifier
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
public MessagesAggregate() {
|
||||||
|
}
|
||||||
|
|
||||||
|
@CommandHandler
|
||||||
|
public MessagesAggregate(CreateMessageCommand command) {
|
||||||
|
apply(new MessageCreatedEvent(command.getId(), command.getText()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void on(MessageCreatedEvent event) {
|
||||||
|
this.id = event.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@CommandHandler
|
||||||
|
public void markRead(MarkReadMessageCommand command) {
|
||||||
|
apply(new MessageReadEvent(id));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.axon.commands;
|
||||||
|
|
||||||
|
|
||||||
|
import org.axonframework.commandhandling.TargetAggregateIdentifier;
|
||||||
|
|
||||||
|
public class CreateMessageCommand {
|
||||||
|
|
||||||
|
@TargetAggregateIdentifier
|
||||||
|
private final String id;
|
||||||
|
private final String text;
|
||||||
|
|
||||||
|
public CreateMessageCommand(String id, String text) {
|
||||||
|
this.id = id;
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getText() {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.axon.commands;
|
||||||
|
|
||||||
|
|
||||||
|
import org.axonframework.commandhandling.TargetAggregateIdentifier;
|
||||||
|
|
||||||
|
public class MarkReadMessageCommand {
|
||||||
|
|
||||||
|
@TargetAggregateIdentifier
|
||||||
|
private final String id;
|
||||||
|
|
||||||
|
public MarkReadMessageCommand(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.axon.eventhandlers;
|
||||||
|
|
||||||
|
import com.baeldung.axon.events.MessageReadEvent;
|
||||||
|
import com.baeldung.axon.events.MessageCreatedEvent;
|
||||||
|
import org.axonframework.eventhandling.EventHandler;
|
||||||
|
|
||||||
|
|
||||||
|
public class MessagesEventHandler {
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void handle(MessageCreatedEvent event) {
|
||||||
|
System.out.println("Message received: " + event.getText() + " (" + event.getId() + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventHandler
|
||||||
|
public void handle(MessageReadEvent event) {
|
||||||
|
System.out.println("Message read: " + event.getId());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.axon.events;
|
||||||
|
|
||||||
|
public class MessageCreatedEvent {
|
||||||
|
|
||||||
|
private final String id;
|
||||||
|
private final String text;
|
||||||
|
|
||||||
|
public MessageCreatedEvent(String id, String text) {
|
||||||
|
this.id = id;
|
||||||
|
this.text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getText() {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.axon.events;
|
||||||
|
|
||||||
|
public class MessageReadEvent {
|
||||||
|
|
||||||
|
private final String id;
|
||||||
|
|
||||||
|
public MessageReadEvent(String id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.axon;
|
||||||
|
|
||||||
|
import com.baeldung.axon.aggregates.MessagesAggregate;
|
||||||
|
import com.baeldung.axon.commands.CreateMessageCommand;
|
||||||
|
import com.baeldung.axon.commands.MarkReadMessageCommand;
|
||||||
|
import com.baeldung.axon.events.MessageCreatedEvent;
|
||||||
|
import com.baeldung.axon.events.MessageReadEvent;
|
||||||
|
import org.axonframework.test.aggregate.AggregateTestFixture;
|
||||||
|
import org.axonframework.test.aggregate.FixtureConfiguration;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class MessagesAggregateTest {
|
||||||
|
|
||||||
|
private FixtureConfiguration<MessagesAggregate> fixture;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() throws Exception {
|
||||||
|
fixture = new AggregateTestFixture<MessagesAggregate>(MessagesAggregate.class);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveAggregateRoot_whenCreateMessageCommand_thenShouldProduceMessageCreatedEvent() throws Exception {
|
||||||
|
String eventText = "Hello, how is your day?";
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
fixture.given()
|
||||||
|
.when(new CreateMessageCommand(id, eventText))
|
||||||
|
.expectEvents(new MessageCreatedEvent(id, eventText));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMessageCreatedEvent_whenReadMessageCommand_thenShouldProduceMessageReadEvent() throws Exception {
|
||||||
|
String id = UUID.randomUUID().toString();
|
||||||
|
|
||||||
|
fixture.given(new MessageCreatedEvent(id, "Hello :-)"))
|
||||||
|
.when(new MarkReadMessageCommand(id))
|
||||||
|
.expectEvents(new MessageReadEvent(id));
|
||||||
|
}
|
||||||
|
}
|
|
@ -8,3 +8,7 @@
|
||||||
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
|
- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
|
||||||
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
|
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
|
||||||
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
|
||||||
|
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java9-completablefuture-api-improvements/)
|
||||||
|
- [Spring Security – Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
|
||||||
|
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||||
|
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
javac -d mods --module-source-path src/modules $(find src/modules -name "*.java")
|
|
@ -0,0 +1,3 @@
|
||||||
|
javac --module-path mods -d mods/com.baeldung.student.client^
|
||||||
|
src/modules/com.baeldung.student.client/module-info.java^
|
||||||
|
src/modules/com.baeldung.student.client/com/baeldung/student/client/StudentClient.java
|
|
@ -0,0 +1,2 @@
|
||||||
|
javac -d mods/com.baeldung.student.model src/modules/com.baeldung.student.model/module-info.java^
|
||||||
|
src/modules/com.baeldung.student.model/com/baeldung/student/model/Student.java
|
|
@ -0,0 +1,3 @@
|
||||||
|
javac --module-path mods -d mods/com.baeldung.student.service.dbimpl^
|
||||||
|
src/modules/com.baeldung.student.service.dbimpl/module-info.java^
|
||||||
|
src/modules/com.baeldung.student.service.dbimpl/com/baeldung/student/service/dbimpl/StudentDbService.java
|
|
@ -0,0 +1,3 @@
|
||||||
|
javac --module-path mods -d mods/com.baeldung.student.service^
|
||||||
|
src/modules/com.baeldung.student.service/module-info.java^
|
||||||
|
src/modules/com.baeldung.student.service/com/baeldung/student/service/StudentService.java
|
|
@ -0,0 +1 @@
|
||||||
|
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
|
|
@ -0,0 +1 @@
|
||||||
|
java --module-path mods -m com.baeldung.student.client/com.baeldung.student.client.StudentClient
|
|
@ -0,0 +1,82 @@
|
||||||
|
package com.baeldung.java9.reactive;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.concurrent.Flow.Subscriber;
|
||||||
|
import java.util.concurrent.Flow.Subscription;
|
||||||
|
|
||||||
|
public class BaeldungBatchSubscriberImpl<T> implements Subscriber<String> {
|
||||||
|
private Subscription subscription;
|
||||||
|
private boolean completed = false;
|
||||||
|
private int counter;
|
||||||
|
private ArrayList<String> buffer;
|
||||||
|
public static final int BUFFER_SIZE = 5;
|
||||||
|
|
||||||
|
public BaeldungBatchSubscriberImpl() {
|
||||||
|
buffer = new ArrayList<String>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCompleted() {
|
||||||
|
return completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCompleted(boolean completed) {
|
||||||
|
this.completed = completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCounter() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCounter(int counter) {
|
||||||
|
this.counter = counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onSubscribe(Subscription subscription) {
|
||||||
|
this.subscription = subscription;
|
||||||
|
subscription.request(BUFFER_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onNext(String item) {
|
||||||
|
buffer.add(item);
|
||||||
|
// if buffer is full, process the items.
|
||||||
|
if (buffer.size() >= BUFFER_SIZE) {
|
||||||
|
processBuffer();
|
||||||
|
}
|
||||||
|
//request more items.
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void processBuffer() {
|
||||||
|
if (buffer.isEmpty())
|
||||||
|
return;
|
||||||
|
// Process all items in the buffer. Here, we just print it and sleep for 1 second.
|
||||||
|
System.out.print("Processed items: ");
|
||||||
|
buffer.stream()
|
||||||
|
.forEach(item -> {
|
||||||
|
System.out.print(" " + item);
|
||||||
|
});
|
||||||
|
System.out.println();
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
counter = counter + buffer.size();
|
||||||
|
buffer.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onError(Throwable t) {
|
||||||
|
t.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onComplete() {
|
||||||
|
completed = true;
|
||||||
|
// process any remaining items in buffer before
|
||||||
|
processBuffer();
|
||||||
|
subscription.cancel();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
package com.baeldung.java9.reactive;
|
||||||
|
|
||||||
|
import java.util.concurrent.Flow.Subscriber;
|
||||||
|
import java.util.concurrent.Flow.Subscription;
|
||||||
|
|
||||||
|
public class BaeldungSubscriberImpl<T> implements Subscriber<String> {
|
||||||
|
private Subscription subscription;
|
||||||
|
private boolean completed = false;
|
||||||
|
private int counter;
|
||||||
|
|
||||||
|
public boolean isCompleted() {
|
||||||
|
return completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCompleted(boolean completed) {
|
||||||
|
this.completed = completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCounter() {
|
||||||
|
return counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCounter(int counter) {
|
||||||
|
this.counter = counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onSubscribe(Subscription subscription) {
|
||||||
|
this.subscription = subscription;
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onNext(String item) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
counter++;
|
||||||
|
System.out.println("Processed item : " + item);
|
||||||
|
subscription.request(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onError(Throwable t) {
|
||||||
|
t.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onComplete() {
|
||||||
|
completed = true;
|
||||||
|
subscription.cancel();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,84 @@
|
||||||
|
package com.baeldung.java9.stackwalker;
|
||||||
|
|
||||||
|
import java.lang.StackWalker.StackFrame;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class StackWalkerDemo {
|
||||||
|
|
||||||
|
public void methodOne() {
|
||||||
|
this.methodTwo();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void methodTwo() {
|
||||||
|
this.methodThree();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void methodThree() {
|
||||||
|
List<StackFrame> stackTrace = StackWalker.getInstance()
|
||||||
|
.walk(this::walkExample);
|
||||||
|
|
||||||
|
printStackTrace(stackTrace);
|
||||||
|
|
||||||
|
System.out.println("---------------------------------------------");
|
||||||
|
|
||||||
|
stackTrace = StackWalker.getInstance()
|
||||||
|
.walk(this::walkExample2);
|
||||||
|
|
||||||
|
printStackTrace(stackTrace);
|
||||||
|
|
||||||
|
System.out.println("---------------------------------------------");
|
||||||
|
|
||||||
|
String line = StackWalker.getInstance().walk(this::walkExample3);
|
||||||
|
System.out.println(line);
|
||||||
|
|
||||||
|
System.out.println("---------------------------------------------");
|
||||||
|
|
||||||
|
stackTrace = StackWalker.getInstance(StackWalker.Option.SHOW_REFLECT_FRAMES)
|
||||||
|
.walk(this::walkExample);
|
||||||
|
|
||||||
|
printStackTrace(stackTrace);
|
||||||
|
|
||||||
|
System.out.println("---------------------------------------------");
|
||||||
|
|
||||||
|
Runnable r = () -> {
|
||||||
|
List<StackFrame> stackTrace2 = StackWalker.getInstance(StackWalker.Option.SHOW_HIDDEN_FRAMES)
|
||||||
|
.walk(this::walkExample);
|
||||||
|
printStackTrace(stackTrace2);
|
||||||
|
};
|
||||||
|
r.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<StackFrame> walkExample(Stream<StackFrame> stackFrameStream) {
|
||||||
|
return stackFrameStream.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<StackFrame> walkExample2(Stream<StackFrame> stackFrameStream) {
|
||||||
|
return stackFrameStream.filter(frame -> frame.getClassName()
|
||||||
|
.contains("com.baeldung"))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String walkExample3(Stream<StackFrame> stackFrameStream) {
|
||||||
|
return stackFrameStream.filter(frame -> frame.getClassName()
|
||||||
|
.contains("com.baeldung")
|
||||||
|
&& frame.getClassName()
|
||||||
|
.endsWith("Test"))
|
||||||
|
.findFirst()
|
||||||
|
.map(frame -> frame.getClassName() + "#" + frame.getMethodName() + ", Line " + frame.getLineNumber())
|
||||||
|
.orElse("Unknown caller");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void findCaller() {
|
||||||
|
Class<?> caller = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
|
||||||
|
System.out.println(caller.getCanonicalName());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void printStackTrace(List<StackFrame> stackTrace) {
|
||||||
|
for (StackFrame stackFrame : stackTrace) {
|
||||||
|
System.out.println(stackFrame.getClassName()
|
||||||
|
.toString() + "#" + stackFrame.getMethodName() + ", Line " + stackFrame.getLineNumber());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.student.client;
|
||||||
|
|
||||||
|
import com.baeldung.student.service.StudentService;
|
||||||
|
import com.baeldung.student.service.dbimpl.StudentDbService;
|
||||||
|
import com.baeldung.student.model.Student;
|
||||||
|
|
||||||
|
public class StudentClient {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
StudentService service = new StudentDbService();
|
||||||
|
service.create(new Student());
|
||||||
|
service.read("17SS0001");
|
||||||
|
service.update(new Student());
|
||||||
|
service.delete("17SS0001");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
module com.baeldung.student.client{
|
||||||
|
requires com.baeldung.student.service.dbimpl;
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.student.model;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class Student {
|
||||||
|
private String registrationId;
|
||||||
|
|
||||||
|
public String getRegistrationId() {
|
||||||
|
return registrationId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRegistrationId(String registrationId) {
|
||||||
|
this.registrationId = registrationId;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
module com.baeldung.student.model{
|
||||||
|
exports com.baeldung.student.model;
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.student.service.dbimpl;
|
||||||
|
|
||||||
|
import com.baeldung.student.service.StudentService;
|
||||||
|
import com.baeldung.student.model.Student;
|
||||||
|
import java.util.logging.*;
|
||||||
|
|
||||||
|
public class StudentDbService implements StudentService {
|
||||||
|
|
||||||
|
private static Logger logger = Logger.getLogger("StudentDbService");
|
||||||
|
|
||||||
|
public String create(Student student) {
|
||||||
|
logger.log(Level.INFO, "Creating student in DB...");
|
||||||
|
return student.getRegistrationId();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student read(String registrationId) {
|
||||||
|
logger.log(Level.INFO, "Reading student from DB...");
|
||||||
|
return new Student();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Student update(Student student) {
|
||||||
|
logger.log(Level.INFO, "Updating sutdent in DB...");
|
||||||
|
return student;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String delete(String registrationId) {
|
||||||
|
logger.log(Level.INFO, "Deleteing sutdent in DB...");
|
||||||
|
return registrationId;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
module com.baeldung.student.service.dbimpl{
|
||||||
|
requires transitive com.baeldung.student.service;
|
||||||
|
exports com.baeldung.student.service.dbimpl;
|
||||||
|
requires java.logging;
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.student.service;
|
||||||
|
|
||||||
|
import com.baeldung.student.model.Student;
|
||||||
|
|
||||||
|
public interface StudentService {
|
||||||
|
|
||||||
|
public String create(Student student);
|
||||||
|
|
||||||
|
public Student read(String registrationId);
|
||||||
|
|
||||||
|
public Student update(Student student);
|
||||||
|
|
||||||
|
public String delete(String registrationId);
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
module com.baeldung.student.service{
|
||||||
|
requires transitive com.baeldung.student.model;
|
||||||
|
exports com.baeldung.student.service;
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java8;
|
package com.baeldung.java9;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@ -8,7 +8,6 @@ import java.util.Optional;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class Java9OptionalsStreamTest {
|
public class Java9OptionalsStreamTest {
|
||||||
|
|
|
@ -0,0 +1,74 @@
|
||||||
|
package com.baeldung.java9.concurrent.future;
|
||||||
|
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertSame;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CompletableFutureTest {
|
||||||
|
@Test
|
||||||
|
public void testDelay () throws Exception {
|
||||||
|
Object input = new Object();
|
||||||
|
CompletableFuture<Object> future = new CompletableFuture<>();
|
||||||
|
future.completeAsync(() -> input, CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
|
||||||
|
|
||||||
|
Thread.sleep(100);
|
||||||
|
|
||||||
|
assertFalse(future.isDone());
|
||||||
|
|
||||||
|
Thread.sleep(1000);
|
||||||
|
assertTrue(future.isDone());
|
||||||
|
assertSame(input, future.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTimeoutTriggered () throws Exception {
|
||||||
|
CompletableFuture<Object> future = new CompletableFuture<>();
|
||||||
|
future.orTimeout(1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
Thread.sleep(1100);
|
||||||
|
|
||||||
|
assertTrue(future.isDone());
|
||||||
|
|
||||||
|
try {
|
||||||
|
future.get();
|
||||||
|
} catch (ExecutionException e) {
|
||||||
|
assertTrue(e.getCause() instanceof TimeoutException);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testTimeoutNotTriggered () throws Exception {
|
||||||
|
Object input = new Object();
|
||||||
|
CompletableFuture<Object> future = new CompletableFuture<>();
|
||||||
|
|
||||||
|
future.orTimeout(1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
Thread.sleep(100);
|
||||||
|
|
||||||
|
future.complete(input);
|
||||||
|
|
||||||
|
Thread.sleep(1000);
|
||||||
|
|
||||||
|
assertTrue(future.isDone());
|
||||||
|
assertSame(input, future.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void completeOnTimeout () throws Exception {
|
||||||
|
Object input = new Object();
|
||||||
|
CompletableFuture<Object> future = new CompletableFuture<>();
|
||||||
|
future.completeOnTimeout(input, 1, TimeUnit.SECONDS);
|
||||||
|
|
||||||
|
Thread.sleep(1100);
|
||||||
|
|
||||||
|
assertTrue(future.isDone());
|
||||||
|
assertSame(input, future.get());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,75 @@
|
||||||
|
package com.baeldung.java9.reactive;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
import java.util.concurrent.SubmissionPublisher;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.rules.Stopwatch;
|
||||||
|
|
||||||
|
public class BaeldungBatchSubscriberImplTest {
|
||||||
|
|
||||||
|
private static final int ITEM_SIZE = 10;
|
||||||
|
private SubmissionPublisher<String> publisher;
|
||||||
|
private BaeldungBatchSubscriberImpl<String> subscriber;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initialize() {
|
||||||
|
this.publisher = new SubmissionPublisher<String>(ForkJoinPool.commonPool(), 6);
|
||||||
|
this.subscriber = new BaeldungBatchSubscriberImpl<String>();
|
||||||
|
publisher.subscribe(subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public Stopwatch stopwatch = new Stopwatch() {
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testReactiveStreamCount() {
|
||||||
|
IntStream.range(0, ITEM_SIZE)
|
||||||
|
.forEach(item -> publisher.submit(item + ""));
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
do {
|
||||||
|
// wait for subscribers to complete all processing.
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (!subscriber.isCompleted());
|
||||||
|
|
||||||
|
int count = subscriber.getCounter();
|
||||||
|
|
||||||
|
assertEquals(ITEM_SIZE, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testReactiveStreamTime() {
|
||||||
|
IntStream.range(0, ITEM_SIZE)
|
||||||
|
.forEach(item -> publisher.submit(item + ""));
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
do {
|
||||||
|
// wait for subscribers to complete all processing.
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (!subscriber.isCompleted());
|
||||||
|
|
||||||
|
// The runtime in seconds should be equal to the number of items in each batch.
|
||||||
|
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) >= (ITEM_SIZE / subscriber.BUFFER_SIZE));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,100 @@
|
||||||
|
package com.baeldung.java9.reactive;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
import java.util.concurrent.SubmissionPublisher;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Rule;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.rules.Stopwatch;
|
||||||
|
|
||||||
|
public class BaeldungSubscriberImplTest {
|
||||||
|
|
||||||
|
private static final int ITEM_SIZE = 10;
|
||||||
|
private SubmissionPublisher<String> publisher;
|
||||||
|
private BaeldungSubscriberImpl<String> subscriber;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initialize() {
|
||||||
|
// create Publisher with max buffer capacity 3.
|
||||||
|
this.publisher = new SubmissionPublisher<String>(ForkJoinPool.commonPool(), 3);
|
||||||
|
this.subscriber = new BaeldungSubscriberImpl<String>();
|
||||||
|
publisher.subscribe(subscriber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Rule
|
||||||
|
public Stopwatch stopwatch = new Stopwatch() {
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testReactiveStreamCount() {
|
||||||
|
IntStream.range(0, ITEM_SIZE)
|
||||||
|
.forEach(item -> publisher.submit(item + ""));
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
do {
|
||||||
|
// wait for subscribers to complete all processing.
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (!subscriber.isCompleted());
|
||||||
|
|
||||||
|
int count = subscriber.getCounter();
|
||||||
|
|
||||||
|
assertEquals(ITEM_SIZE, count);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testReactiveStreamTime() {
|
||||||
|
IntStream.range(0, ITEM_SIZE)
|
||||||
|
.forEach(item -> publisher.submit(item + ""));
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
do {
|
||||||
|
// wait for subscribers to complete all processing.
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (!subscriber.isCompleted());
|
||||||
|
|
||||||
|
// The runtime in seconds should be equal to the number of items.
|
||||||
|
assertTrue(stopwatch.runtime(TimeUnit.SECONDS) >= ITEM_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testReactiveStreamOffer() {
|
||||||
|
IntStream.range(0, ITEM_SIZE)
|
||||||
|
.forEach(item -> publisher.offer(item + "", (subscriber, string) -> {
|
||||||
|
// Returning false means this item will be dropped (no retry), if blocked.
|
||||||
|
return false;
|
||||||
|
}));
|
||||||
|
publisher.close();
|
||||||
|
|
||||||
|
do {
|
||||||
|
// wait for subscribers to complete all processing.
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} while (!subscriber.isCompleted());
|
||||||
|
|
||||||
|
int count = subscriber.getCounter();
|
||||||
|
// Because 10 items were offered and the buffer capacity was 3, few items will not be processed.
|
||||||
|
assertTrue(ITEM_SIZE > count);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.java9.stackwalker;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class StackWalkerDemoTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveStalkWalker_whenWalkingTheStack_thenShowStackFrames() {
|
||||||
|
new StackWalkerDemo().methodOne();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveStalkWalker_whenInvokingFindCaller_thenFindCallingClass() {
|
||||||
|
new StackWalkerDemo().findCaller();
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue