commit
7b7f8bed8e
|
@ -1,3 +1,5 @@
|
|||
*/bin/*
|
||||
|
||||
*.class
|
||||
|
||||
# Package Files #
|
||||
|
@ -29,3 +31,5 @@ spring-openid/src/main/resources/application.properties
|
|||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
spring-security-openid/src/main/resources/application.properties
|
||||
|
||||
spring-all/*.log
|
||||
|
|
16
.travis.yml
16
.travis.yml
|
@ -1,11 +1,19 @@
|
|||
language: java
|
||||
|
||||
install: travis_wait 40 mvn -q clean install -Dgib.enabled=true
|
||||
before_install:
|
||||
- export MAVEN_OPTS="-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit"
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: travis_wait 60 mvn -q test -fae
|
||||
|
||||
sudo: required
|
||||
|
||||
before_script:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
sudo: false
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
|
@ -14,4 +22,6 @@ addons:
|
|||
cache:
|
||||
directories:
|
||||
- .autoconf
|
||||
- $HOME/.m2
|
||||
- $HOME/.m2
|
||||
|
||||
|
||||
|
|
26
JGit/pom.xml
26
JGit/pom.xml
|
@ -6,6 +6,13 @@
|
|||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
|
@ -40,24 +47,5 @@
|
|||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>1.7.21</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.2</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,31 @@
|
|||
import com.baeldung.jgit.helper.Helper;
|
||||
import org.eclipse.jgit.lib.ObjectLoader;
|
||||
import org.eclipse.jgit.lib.ObjectReader;
|
||||
import org.eclipse.jgit.lib.Ref;
|
||||
import org.eclipse.jgit.lib.Repository;
|
||||
import org.eclipse.jgit.revwalk.RevWalk;
|
||||
import org.junit.Test;
|
||||
import java.io.IOException;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* Tests which show issues with JGit that we reported upstream.
|
||||
*/
|
||||
public class JGitBugIntegrationTest {
|
||||
@Test
|
||||
public void testRevWalkDisposeClosesReader() throws IOException {
|
||||
try (Repository repo = Helper.openJGitRepository()) {
|
||||
try (ObjectReader reader = repo.newObjectReader()) {
|
||||
try (RevWalk walk = new RevWalk(reader)) {
|
||||
walk.dispose();
|
||||
|
||||
Ref head = repo.exactRef("refs/heads/master");
|
||||
System.out.println("Found head: " + head);
|
||||
|
||||
ObjectLoader loader = reader.open(head.getObjectId());
|
||||
assertNotNull(loader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
import com.baeldung.jgit.helper.Helper;
|
||||
import org.eclipse.jgit.lib.ObjectLoader;
|
||||
import org.eclipse.jgit.lib.ObjectReader;
|
||||
import org.eclipse.jgit.lib.Ref;
|
||||
import org.eclipse.jgit.lib.Repository;
|
||||
import org.eclipse.jgit.revwalk.RevWalk;
|
||||
import org.junit.Test;
|
||||
import java.io.IOException;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
/**
|
||||
* Tests which show issues with JGit that we reported upstream.
|
||||
*/
|
||||
public class JGitBugTest {
|
||||
@Test
|
||||
public void testRevWalkDisposeClosesReader() throws IOException {
|
||||
try (Repository repo = Helper.openJGitRepository()) {
|
||||
try (ObjectReader reader = repo.newObjectReader()) {
|
||||
try (RevWalk walk = new RevWalk(reader)) {
|
||||
walk.dispose();
|
||||
|
||||
Ref head = repo.exactRef("refs/heads/master");
|
||||
System.out.println("Found head: " + head);
|
||||
|
||||
ObjectLoader loader = reader.open(head.getObjectId());
|
||||
assertNotNull(loader);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
package com.baeldung.jgit.porcelain;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PorcelainTest {
|
||||
@Test
|
||||
public void runSamples() throws Exception {
|
||||
// simply call all the samples to see any severe problems with the samples
|
||||
AddFile.main(null);
|
||||
|
||||
CommitAll.main(null);
|
||||
|
||||
CreateAndDeleteTag.main(null);
|
||||
|
||||
Log.main(null);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.jgit.porcelain;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PorcelainUnitTest {
|
||||
@Test
|
||||
public void runSamples() throws Exception {
|
||||
// simply call all the samples to see any severe problems with the samples
|
||||
AddFile.main(null);
|
||||
|
||||
CommitAll.main(null);
|
||||
|
||||
CreateAndDeleteTag.main(null);
|
||||
|
||||
Log.main(null);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
|
|
@ -0,0 +1,52 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/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>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.twitter4j</groupId>
|
||||
<artifactId>twitter4j-stream</artifactId>
|
||||
<version>4.0.6</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>${maven-surefire-plugin.version}</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 ApplicationIntegrationTest {
|
||||
|
||||
/**
|
||||
* In order run this jUnit test you need to configure your API details in the twitter4j.properties
|
||||
*/
|
||||
|
||||
String tweet = "baeldung is awsome";
|
||||
|
||||
@Test
|
||||
public void givenText_updateStatus() throws TwitterException {
|
||||
String text = Application.createTweet(tweet);
|
||||
assertEquals(tweet, text);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCredential_fetchStatus() throws TwitterException {
|
||||
List<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,7 @@
|
|||
|
||||
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
||||
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
|
||||
|
|
|
@ -1,63 +1,69 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>algorithms</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<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>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<instrumentation>
|
||||
<ignores>
|
||||
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
|
||||
</ignores>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
|
||||
</excludes>
|
||||
</instrumentation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</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>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<instrumentation>
|
||||
<ignores>
|
||||
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
|
||||
</ignores>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
|
||||
</excludes>
|
||||
</instrumentation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.algorithms;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
System.out.println("3 - Simple Genetic Algorithm");
|
||||
System.out.println("4 - Ant Colony");
|
||||
System.out.println("5 - Dijkstra");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println(
|
||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 3:
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
case 4:
|
||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||
antColony.startAntOptimization();
|
||||
break;
|
||||
case 5:
|
||||
System.out.println("Please run the DijkstraAlgorithmTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
import lombok.Data;
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
public class SimulatedAnnealing {
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.algorithms.annealing;
|
||||
package com.baeldung.algorithms.ga.annealing;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.algorithms.ga.ant_colony;
|
||||
|
||||
public class Ant {
|
||||
|
||||
protected int trailSize;
|
||||
protected int trail[];
|
||||
protected boolean visited[];
|
||||
|
||||
public Ant(int tourSize) {
|
||||
this.trailSize = tourSize;
|
||||
this.trail = new int[tourSize];
|
||||
this.visited = new boolean[tourSize];
|
||||
}
|
||||
|
||||
protected void visitCity(int currentIndex, int city) {
|
||||
trail[currentIndex + 1] = city;
|
||||
visited[city] = true;
|
||||
}
|
||||
|
||||
protected boolean visited(int i) {
|
||||
return visited[i];
|
||||
}
|
||||
|
||||
protected double trailLength(double graph[][]) {
|
||||
double length = graph[trail[trailSize - 1]][trail[0]];
|
||||
for (int i = 0; i < trailSize - 1; i++) {
|
||||
length += graph[trail[i]][trail[i + 1]];
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
protected void clear() {
|
||||
for (int i = 0; i < trailSize; i++)
|
||||
visited[i] = false;
|
||||
}
|
||||
|
||||
}
|
|
@ -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,57 +1,57 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class Dijkstra {
|
||||
|
||||
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
|
||||
|
||||
source.setDistance(0);
|
||||
|
||||
Set<Node> settledNodes = new HashSet<>();
|
||||
Set<Node> unsettledNodes = new HashSet<>();
|
||||
unsettledNodes.add(source);
|
||||
|
||||
while (unsettledNodes.size() != 0) {
|
||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||
unsettledNodes.remove(currentNode);
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||
Node adjacentNode = adjacencyPair.getKey();
|
||||
Integer edgeWeigh = adjacencyPair.getValue();
|
||||
|
||||
if (!settledNodes.contains(adjacentNode)) {
|
||||
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
|
||||
unsettledNodes.add(adjacentNode);
|
||||
}
|
||||
}
|
||||
settledNodes.add(currentNode);
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
|
||||
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
|
||||
Integer sourceDistance = sourceNode.getDistance();
|
||||
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
|
||||
evaluationNode.setDistance(sourceDistance + edgeWeigh);
|
||||
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
|
||||
shortestPath.add(sourceNode);
|
||||
evaluationNode.setShortestPath(shortestPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
|
||||
Node lowestDistanceNode = null;
|
||||
int lowestDistance = Integer.MAX_VALUE;
|
||||
for (Node node : unsettledNodes) {
|
||||
int nodeDistance = node.getDistance();
|
||||
if (nodeDistance < lowestDistance) {
|
||||
lowestDistance = nodeDistance;
|
||||
lowestDistanceNode = node;
|
||||
}
|
||||
}
|
||||
return lowestDistanceNode;
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.ga.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class Dijkstra {
|
||||
|
||||
public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
|
||||
|
||||
source.setDistance(0);
|
||||
|
||||
Set<Node> settledNodes = new HashSet<>();
|
||||
Set<Node> unsettledNodes = new HashSet<>();
|
||||
unsettledNodes.add(source);
|
||||
|
||||
while (unsettledNodes.size() != 0) {
|
||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||
unsettledNodes.remove(currentNode);
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||
Node adjacentNode = adjacencyPair.getKey();
|
||||
Integer edgeWeigh = adjacencyPair.getValue();
|
||||
|
||||
if (!settledNodes.contains(adjacentNode)) {
|
||||
CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
|
||||
unsettledNodes.add(adjacentNode);
|
||||
}
|
||||
}
|
||||
settledNodes.add(currentNode);
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
|
||||
private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
|
||||
Integer sourceDistance = sourceNode.getDistance();
|
||||
if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
|
||||
evaluationNode.setDistance(sourceDistance + edgeWeigh);
|
||||
LinkedList<Node> shortestPath = new LinkedList<>(sourceNode.getShortestPath());
|
||||
shortestPath.add(sourceNode);
|
||||
evaluationNode.setShortestPath(shortestPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static Node getLowestDistanceNode(Set<Node> unsettledNodes) {
|
||||
Node lowestDistanceNode = null;
|
||||
int lowestDistance = Integer.MAX_VALUE;
|
||||
for (Node node : unsettledNodes) {
|
||||
int nodeDistance = node.getDistance();
|
||||
if (nodeDistance < lowestDistance) {
|
||||
lowestDistance = nodeDistance;
|
||||
lowestDistanceNode = node;
|
||||
}
|
||||
}
|
||||
return lowestDistanceNode;
|
||||
}
|
||||
}
|
|
@ -1,21 +1,21 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private Set<Node> nodes = new HashSet<>();
|
||||
|
||||
public void addNode(Node nodeA) {
|
||||
nodes.add(nodeA);
|
||||
}
|
||||
|
||||
public Set<Node> getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public void setNodes(Set<Node> nodes) {
|
||||
this.nodes = nodes;
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.ga.dijkstra;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Graph {
|
||||
|
||||
private Set<Node> nodes = new HashSet<>();
|
||||
|
||||
public void addNode(Node nodeA) {
|
||||
nodes.add(nodeA);
|
||||
}
|
||||
|
||||
public Set<Node> getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
|
||||
public void setNodes(Set<Node> nodes) {
|
||||
this.nodes = nodes;
|
||||
}
|
||||
}
|
|
@ -1,58 +1,58 @@
|
|||
package com.baeldung.algorithms.dijkstra;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Node {
|
||||
|
||||
private String name;
|
||||
|
||||
private LinkedList<Node> shortestPath = new LinkedList<>();
|
||||
|
||||
private Integer distance = Integer.MAX_VALUE;
|
||||
|
||||
private Map<Node, Integer> adjacentNodes = new HashMap<>();
|
||||
|
||||
public Node(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void addDestination(Node destination, int distance) {
|
||||
adjacentNodes.put(destination, distance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Map<Node, Integer> getAdjacentNodes() {
|
||||
return adjacentNodes;
|
||||
}
|
||||
|
||||
public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) {
|
||||
this.adjacentNodes = adjacentNodes;
|
||||
}
|
||||
|
||||
public Integer getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Integer distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
public List<Node> getShortestPath() {
|
||||
return shortestPath;
|
||||
}
|
||||
|
||||
public void setShortestPath(LinkedList<Node> shortestPath) {
|
||||
this.shortestPath = shortestPath;
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.ga.dijkstra;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class Node {
|
||||
|
||||
private String name;
|
||||
|
||||
private LinkedList<Node> shortestPath = new LinkedList<>();
|
||||
|
||||
private Integer distance = Integer.MAX_VALUE;
|
||||
|
||||
private Map<Node, Integer> adjacentNodes = new HashMap<>();
|
||||
|
||||
public Node(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void addDestination(Node destination, int distance) {
|
||||
adjacentNodes.put(destination, distance);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Map<Node, Integer> getAdjacentNodes() {
|
||||
return adjacentNodes;
|
||||
}
|
||||
|
||||
public void setAdjacentNodes(Map<Node, Integer> adjacentNodes) {
|
||||
this.adjacentNodes = adjacentNodes;
|
||||
}
|
||||
|
||||
public Integer getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Integer distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
public List<Node> getShortestPath() {
|
||||
return shortestPath;
|
||||
}
|
||||
|
||||
public void setShortestPath(LinkedList<Node> shortestPath) {
|
||||
this.shortestPath = shortestPath;
|
||||
}
|
||||
|
||||
}
|
|
@ -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();
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
|
||||
public class AntColonyOptimizationLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void testGenerateRandomMatrix() {
|
||||
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
||||
Assert.assertNotNull(antTSP.generateRandomMatrix(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartAntOptimization() {
|
||||
AntColonyOptimization antTSP = new AntColonyOptimization(5);
|
||||
Assert.assertNotNull(antTSP.solve());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
|
||||
public class BinaryGeneticAlgorithmLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void testGA() {
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
package algorithms;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.ga.dijkstra.Node;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DijkstraAlgorithmLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSPPSolved_thenCorrect() {
|
||||
|
||||
Node nodeA = new Node("A");
|
||||
Node nodeB = new Node("B");
|
||||
Node nodeC = new Node("C");
|
||||
Node nodeD = new Node("D");
|
||||
Node nodeE = new Node("E");
|
||||
Node nodeF = new Node("F");
|
||||
|
||||
nodeA.addDestination(nodeB, 10);
|
||||
nodeA.addDestination(nodeC, 15);
|
||||
|
||||
nodeB.addDestination(nodeD, 12);
|
||||
nodeB.addDestination(nodeF, 15);
|
||||
|
||||
nodeC.addDestination(nodeE, 10);
|
||||
|
||||
nodeD.addDestination(nodeE, 2);
|
||||
nodeD.addDestination(nodeF, 1);
|
||||
|
||||
nodeF.addDestination(nodeE, 5);
|
||||
|
||||
Graph graph = new Graph();
|
||||
|
||||
graph.addNode(nodeA);
|
||||
graph.addNode(nodeB);
|
||||
graph.addNode(nodeC);
|
||||
graph.addNode(nodeD);
|
||||
graph.addNode(nodeE);
|
||||
graph.addNode(nodeF);
|
||||
|
||||
graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
|
||||
|
||||
List<Node> shortestPathForNodeB = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeC = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
|
||||
List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
|
||||
for (Node node : graph.getNodes()) {
|
||||
switch (node.getName()) {
|
||||
case "B":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeB));
|
||||
break;
|
||||
case "C":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeC));
|
||||
break;
|
||||
case "D":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeD));
|
||||
break;
|
||||
case "E":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeE));
|
||||
break;
|
||||
case "F":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeF));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,75 +0,0 @@
|
|||
package algorithms;
|
||||
|
||||
import com.baeldung.algorithms.dijkstra.Dijkstra;
|
||||
import com.baeldung.algorithms.dijkstra.Graph;
|
||||
import com.baeldung.algorithms.dijkstra.Node;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class DijkstraAlgorithmTest {
|
||||
|
||||
@Test
|
||||
public void whenSPPSolved_thenCorrect() {
|
||||
|
||||
Node nodeA = new Node("A");
|
||||
Node nodeB = new Node("B");
|
||||
Node nodeC = new Node("C");
|
||||
Node nodeD = new Node("D");
|
||||
Node nodeE = new Node("E");
|
||||
Node nodeF = new Node("F");
|
||||
|
||||
nodeA.addDestination(nodeB, 10);
|
||||
nodeA.addDestination(nodeC, 15);
|
||||
|
||||
nodeB.addDestination(nodeD, 12);
|
||||
nodeB.addDestination(nodeF, 15);
|
||||
|
||||
nodeC.addDestination(nodeE, 10);
|
||||
|
||||
nodeD.addDestination(nodeE, 2);
|
||||
nodeD.addDestination(nodeF, 1);
|
||||
|
||||
nodeF.addDestination(nodeE, 5);
|
||||
|
||||
Graph graph = new Graph();
|
||||
|
||||
graph.addNode(nodeA);
|
||||
graph.addNode(nodeB);
|
||||
graph.addNode(nodeC);
|
||||
graph.addNode(nodeD);
|
||||
graph.addNode(nodeE);
|
||||
graph.addNode(nodeF);
|
||||
|
||||
graph = Dijkstra.calculateShortestPathFromSource(graph, nodeA);
|
||||
|
||||
List<Node> shortestPathForNodeB = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeC = Arrays.asList(nodeA);
|
||||
List<Node> shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
|
||||
List<Node> shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
List<Node> shortestPathForNodeF = Arrays.asList(nodeA, nodeB, nodeD);
|
||||
|
||||
for (Node node : graph.getNodes()) {
|
||||
switch (node.getName()) {
|
||||
case "B":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||
break;
|
||||
case "C":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||
break;
|
||||
case "D":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||
break;
|
||||
case "E":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||
break;
|
||||
case "F":
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package algorithms;
|
||||
|
||||
import com.baeldung.automata.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public final class RtFiniteStateMachineLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void acceptsSimplePair() {
|
||||
String json = "{\"key\":\"value\"}";
|
||||
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||
}
|
||||
assertTrue(machine.canStop());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void acceptsMorePairs() {
|
||||
String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
|
||||
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||
}
|
||||
assertTrue(machine.canStop());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void missingColon() {
|
||||
String json = "{\"key\"\"value\"}";
|
||||
FiniteStateMachine machine = this.buildJsonStateMachine();
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
machine = machine.switchState(String.valueOf(json.charAt(i)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a finite state machine to validate a simple
|
||||
* Json object.
|
||||
* @return
|
||||
*/
|
||||
private FiniteStateMachine buildJsonStateMachine() {
|
||||
State first = new RtState();
|
||||
State second = new RtState();
|
||||
State third = new RtState();
|
||||
State fourth = new RtState();
|
||||
State fifth = new RtState();
|
||||
State sixth = new RtState();
|
||||
State seventh = new RtState();
|
||||
State eighth = new RtState(true);
|
||||
|
||||
first.with(new RtTransition("{", second));
|
||||
second.with(new RtTransition("\"", third));
|
||||
//Add transitions with chars 0-9 and a-z
|
||||
for (int i = 0; i < 26; i++) {
|
||||
if (i < 10) {
|
||||
third = third.with(new RtTransition(String.valueOf(i), third));
|
||||
sixth = sixth.with(new RtTransition(String.valueOf(i), sixth));
|
||||
}
|
||||
third = third.with(new RtTransition(String.valueOf((char) ('a' + i)), third));
|
||||
sixth = sixth.with(new RtTransition(String.valueOf((char) ('a' + i)), sixth));
|
||||
}
|
||||
third.with(new RtTransition("\"", fourth));
|
||||
fourth.with(new RtTransition(":", fifth));
|
||||
fifth.with(new RtTransition("\"", sixth));
|
||||
sixth.with(new RtTransition("\"", seventh));
|
||||
seventh.with(new RtTransition(",", second));
|
||||
seventh.with(new RtTransition("}", eighth));
|
||||
return new RtFiniteStateMachine(first);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package algorithms;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
|
||||
public class SimulatedAnnealingLongRunningUnitTest {
|
||||
|
||||
@Test
|
||||
public void testSimulateAnnealing() {
|
||||
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.algorithms.primechecker;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PrimeCheckerUnitTest {
|
||||
|
||||
private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenCheckIsPrime_thenTrue(){
|
||||
assertTrue(primeChecker.isPrime(13l));
|
||||
assertTrue(primeChecker.isPrime(1009L));
|
||||
assertTrue(primeChecker.isPrime(74207281L));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCheckIsPrime_thenFalse(){
|
||||
assertTrue(!primeChecker.isPrime(50L));
|
||||
assertTrue(!primeChecker.isPrime(1001L));
|
||||
assertTrue(!primeChecker.isPrime(74207282L));
|
||||
}
|
||||
|
||||
private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenBFCheckIsPrime_thenTrue(){
|
||||
assertTrue(bfPrimeChecker.isPrime(13));
|
||||
assertTrue(bfPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBFCheckIsPrime_thenFalse(){
|
||||
assertFalse(bfPrimeChecker.isPrime(50));
|
||||
assertFalse(bfPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
|
||||
private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenOptCheckIsPrime_thenTrue(){
|
||||
assertTrue(optimisedPrimeChecker.isPrime(13));
|
||||
assertTrue(optimisedPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptCheckIsPrime_thenFalse(){
|
||||
assertFalse(optimisedPrimeChecker.isPrime(50));
|
||||
assertFalse(optimisedPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker();
|
||||
|
||||
@Test
|
||||
public void whenPrimesCheckIsPrime_thenTrue() {
|
||||
assertTrue(primesPrimeChecker.isPrime(13));
|
||||
assertTrue(primesPrimeChecker.isPrime(1009));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPrimesCheckIsPrime_thenFalse() {
|
||||
assertFalse(primesPrimeChecker.isPrime(50));
|
||||
assertFalse(primesPrimeChecker.isPrime(1001));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<?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">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
|
@ -13,11 +12,6 @@
|
|||
|
||||
<artifactId>annotation-user</artifactId>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
|
@ -26,31 +20,6 @@
|
|||
<version>${project.parent.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
</project>
|
|
@ -1,19 +0,0 @@
|
|||
package com.baeldung.annotation;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PersonBuilderTest {
|
||||
|
||||
@Test
|
||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||
|
||||
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||
|
||||
assertEquals(25, person.getAge());
|
||||
assertEquals("John", person.getName());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.annotation;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class PersonBuilderUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||
|
||||
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||
|
||||
assertEquals(25, person.getAge());
|
||||
assertEquals("John", person.getName());
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -5,6 +5,11 @@
|
|||
<artifactId>apache-bval</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.bval</groupId>
|
||||
|
@ -21,31 +26,9 @@
|
|||
<artifactId>bval-extras</artifactId>
|
||||
<version>${bval.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<bval.version>1.1.2</bval.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,97 @@
|
|||
package com.baeldung.validation;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.apache.bval.jsr.ApacheValidationProvider;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
|
||||
public class ValidationIntegrationTest {
|
||||
private static ValidatorFactory validatorFactory;
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
|
||||
.configure()
|
||||
.buildValidatorFactory();
|
||||
validator = validatorFactory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUser_whenValidate_thenValidationViolations() {
|
||||
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertTrue("no violations", violations.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
|
||||
|
||||
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
|
||||
assertEquals("size is not 1", 1, propertyViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
|
||||
|
||||
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
|
||||
assertEquals("size is not 0", 0, valueViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateNonJSR_thenCorrect() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
|
||||
user.setCardNumber("1234");
|
||||
user.setIban("1234");
|
||||
user.setWebsite("10.0.2.50");
|
||||
user.setMainDirectory(new File("."));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
|
||||
assertEquals("size is not 1", 1, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "website");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "mainDirectory");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password", "Ana", 20);
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("message incorrect", "Invalid password", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void close() {
|
||||
if (validatorFactory != null) {
|
||||
validatorFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
package com.baeldung.validation;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import javax.validation.ValidatorFactory;
|
||||
|
||||
import org.apache.bval.jsr.ApacheValidationProvider;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import com.baeldung.model.User;
|
||||
|
||||
public class ValidationTest {
|
||||
private static ValidatorFactory validatorFactory;
|
||||
private static Validator validator;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
validatorFactory = Validation.byProvider(ApacheValidationProvider.class)
|
||||
.configure()
|
||||
.buildValidatorFactory();
|
||||
validator = validatorFactory.getValidator();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUser_whenValidate_thenValidationViolations() {
|
||||
User user = new User("ana@yahoo.com", "pass", "nameTooLong_______________", 15);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validate(user);
|
||||
assertTrue("no violations", violations.size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAge_whenValidateProperty_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 12);
|
||||
|
||||
Set<ConstraintViolation<User>> propertyViolations = validator.validateProperty(user, "age");
|
||||
assertEquals("size is not 1", 1, propertyViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidAge_whenValidateValue_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 18);
|
||||
|
||||
Set<ConstraintViolation<User>> valueViolations = validator.validateValue(User.class, "age", 20);
|
||||
assertEquals("size is not 0", 0, valueViolations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidateNonJSR_thenCorrect() {
|
||||
User user = new User("ana@yahoo.com", "pass", "Ana", 20);
|
||||
user.setCardNumber("1234");
|
||||
user.setIban("1234");
|
||||
user.setWebsite("10.0.2.50");
|
||||
user.setMainDirectory(new File("."));
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "iban");
|
||||
assertEquals("size is not 1", 1, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "website");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
|
||||
violations = validator.validateProperty(user, "mainDirectory");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidPassword_whenValidatePassword_thenConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password", "Ana", 20);
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("message incorrect", "Invalid password", violations.iterator()
|
||||
.next()
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidPassword_whenValidatePassword_thenNoConstraintViolation() {
|
||||
User user = new User("ana@yahoo.com", "password#", "Ana", 20);
|
||||
|
||||
Set<ConstraintViolation<User>> violations = validator.validateProperty(user, "password");
|
||||
assertEquals("size is not 0", 0, violations.size());
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void close() {
|
||||
if (validatorFactory != null) {
|
||||
validatorFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -8,7 +8,7 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
|
|
@ -0,0 +1,103 @@
|
|||
package com.baeldung.cxf.aegis;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.xml.namespace.QName;
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLOutputFactory;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
import javax.xml.stream.XMLStreamWriter;
|
||||
|
||||
import org.apache.cxf.aegis.AegisContext;
|
||||
import org.apache.cxf.aegis.AegisReader;
|
||||
import org.apache.cxf.aegis.AegisWriter;
|
||||
import org.apache.cxf.aegis.type.AegisType;
|
||||
|
||||
public class BaeldungIntegrationTest {
|
||||
private AegisContext context;
|
||||
private String fileName = "baeldung.xml";
|
||||
|
||||
@Test
|
||||
public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
|
||||
initializeContext();
|
||||
CourseRepo inputRepo = initCourseRepo();
|
||||
marshalCourseRepo(inputRepo);
|
||||
CourseRepo outputRepo = unmarshalCourseRepo();
|
||||
Course restCourse = outputRepo.getCourses().get(1);
|
||||
Course securityCourse = outputRepo.getCourses().get(2);
|
||||
assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
|
||||
assertEquals("REST with Spring", restCourse.getName());
|
||||
assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
|
||||
assertNull(restCourse.getInstructor());
|
||||
assertEquals("Learn Spring Security", securityCourse.getName());
|
||||
assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
|
||||
assertNull(securityCourse.getInstructor());
|
||||
}
|
||||
|
||||
private void initializeContext() {
|
||||
context = new AegisContext();
|
||||
Set<Type> rootClasses = new HashSet<Type>();
|
||||
rootClasses.add(CourseRepo.class);
|
||||
context.setRootClasses(rootClasses);
|
||||
Map<Class<?>, String> beanImplementationMap = new HashMap<>();
|
||||
beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
|
||||
context.setBeanImplementationMap(beanImplementationMap);
|
||||
context.setWriteXsiTypes(true);
|
||||
context.initialize();
|
||||
}
|
||||
|
||||
private CourseRepoImpl initCourseRepo() {
|
||||
Course restCourse = new Course();
|
||||
restCourse.setId(1);
|
||||
restCourse.setName("REST with Spring");
|
||||
restCourse.setInstructor("Eugen");
|
||||
restCourse.setEnrolmentDate(new Date(1234567890000L));
|
||||
Course securityCourse = new Course();
|
||||
securityCourse.setId(2);
|
||||
securityCourse.setName("Learn Spring Security");
|
||||
securityCourse.setInstructor("Eugen");
|
||||
securityCourse.setEnrolmentDate(new Date(1456789000000L));
|
||||
CourseRepoImpl courseRepo = new CourseRepoImpl();
|
||||
courseRepo.setGreeting("Welcome to Beldung!");
|
||||
courseRepo.addCourse(restCourse);
|
||||
courseRepo.addCourse(securityCourse);
|
||||
return courseRepo;
|
||||
}
|
||||
|
||||
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
|
||||
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
|
||||
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
|
||||
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
|
||||
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
|
||||
xmlWriter.close();
|
||||
}
|
||||
|
||||
private CourseRepo unmarshalCourseRepo() throws Exception {
|
||||
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
|
||||
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
|
||||
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
|
||||
xmlReader.close();
|
||||
return courseRepo;
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup(){
|
||||
File testFile = new File(fileName);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
package com.baeldung.cxf.aegis;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.xml.namespace.QName;
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLOutputFactory;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
import javax.xml.stream.XMLStreamWriter;
|
||||
|
||||
import org.apache.cxf.aegis.AegisContext;
|
||||
import org.apache.cxf.aegis.AegisReader;
|
||||
import org.apache.cxf.aegis.AegisWriter;
|
||||
import org.apache.cxf.aegis.type.AegisType;
|
||||
|
||||
public class BaeldungTest {
|
||||
private AegisContext context;
|
||||
private String fileName = "baeldung.xml";
|
||||
|
||||
@Test
|
||||
public void whenMarshalingAndUnmarshalingCourseRepo_thenCorrect() throws Exception {
|
||||
initializeContext();
|
||||
CourseRepo inputRepo = initCourseRepo();
|
||||
marshalCourseRepo(inputRepo);
|
||||
CourseRepo outputRepo = unmarshalCourseRepo();
|
||||
Course restCourse = outputRepo.getCourses().get(1);
|
||||
Course securityCourse = outputRepo.getCourses().get(2);
|
||||
assertEquals("Welcome to Beldung!", outputRepo.getGreeting());
|
||||
assertEquals("REST with Spring", restCourse.getName());
|
||||
assertEquals(new Date(1234567890000L), restCourse.getEnrolmentDate());
|
||||
assertNull(restCourse.getInstructor());
|
||||
assertEquals("Learn Spring Security", securityCourse.getName());
|
||||
assertEquals(new Date(1456789000000L), securityCourse.getEnrolmentDate());
|
||||
assertNull(securityCourse.getInstructor());
|
||||
}
|
||||
|
||||
private void initializeContext() {
|
||||
context = new AegisContext();
|
||||
Set<Type> rootClasses = new HashSet<Type>();
|
||||
rootClasses.add(CourseRepo.class);
|
||||
context.setRootClasses(rootClasses);
|
||||
Map<Class<?>, String> beanImplementationMap = new HashMap<>();
|
||||
beanImplementationMap.put(CourseRepoImpl.class, "CourseRepo");
|
||||
context.setBeanImplementationMap(beanImplementationMap);
|
||||
context.setWriteXsiTypes(true);
|
||||
context.initialize();
|
||||
}
|
||||
|
||||
private CourseRepoImpl initCourseRepo() {
|
||||
Course restCourse = new Course();
|
||||
restCourse.setId(1);
|
||||
restCourse.setName("REST with Spring");
|
||||
restCourse.setInstructor("Eugen");
|
||||
restCourse.setEnrolmentDate(new Date(1234567890000L));
|
||||
Course securityCourse = new Course();
|
||||
securityCourse.setId(2);
|
||||
securityCourse.setName("Learn Spring Security");
|
||||
securityCourse.setInstructor("Eugen");
|
||||
securityCourse.setEnrolmentDate(new Date(1456789000000L));
|
||||
CourseRepoImpl courseRepo = new CourseRepoImpl();
|
||||
courseRepo.setGreeting("Welcome to Beldung!");
|
||||
courseRepo.addCourse(restCourse);
|
||||
courseRepo.addCourse(securityCourse);
|
||||
return courseRepo;
|
||||
}
|
||||
|
||||
private void marshalCourseRepo(CourseRepo courseRepo) throws Exception {
|
||||
AegisWriter<XMLStreamWriter> writer = context.createXMLStreamWriter();
|
||||
AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class);
|
||||
XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName));
|
||||
writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType);
|
||||
xmlWriter.close();
|
||||
}
|
||||
|
||||
private CourseRepo unmarshalCourseRepo() throws Exception {
|
||||
AegisReader<XMLStreamReader> reader = context.createXMLStreamReader();
|
||||
XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName));
|
||||
CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class));
|
||||
xmlReader.close();
|
||||
return courseRepo;
|
||||
}
|
||||
}
|
|
@ -4,18 +4,18 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-introduction</artifactId>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -36,7 +36,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
|
|
|
@ -4,20 +4,20 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-jaxrs-implementation</artifactId>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<httpclient.version>4.5.2</httpclient.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
</properties>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -38,7 +38,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
|
@ -54,6 +54,12 @@
|
|||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
<artifactId>apache-cxf</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
|
@ -24,6 +24,12 @@
|
|||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
|
@ -36,7 +42,7 @@
|
|||
<version>${javax.servlet-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
|
@ -57,7 +63,7 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>live</id>
|
||||
|
@ -96,7 +102,7 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${surefire.version}</version>
|
||||
|
@ -117,17 +123,17 @@
|
|||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
|
||||
</profiles>
|
||||
|
||||
|
||||
<properties>
|
||||
<cxf.version>3.1.8</cxf.version>
|
||||
<spring.version>4.3.4.RELEASE</spring.version>
|
||||
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
|
||||
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<surefire.version>2.19.1</surefire.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>cxf-introduction</module>
|
||||
<module>cxf-spring</module>
|
||||
|
@ -14,33 +20,13 @@
|
|||
</modules>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
|
|
|
@ -7,64 +7,14 @@
|
|||
|
||||
<name>apache-fop</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- logging -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
<!-- <scope>runtime</scope> -->
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
|
||||
</dependency>
|
||||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-library</artifactId>
|
||||
<version>${org.hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-core</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- new dependencies -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.xmlgraphics</groupId>
|
||||
<artifactId>fop</artifactId>
|
||||
|
@ -78,6 +28,10 @@
|
|||
<groupId>org.apache.avalon.framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
|
@ -90,6 +44,12 @@
|
|||
<groupId>avalon-framework</groupId>
|
||||
<artifactId>avalon-framework-impl</artifactId>
|
||||
<version>${avalon-framework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -101,9 +61,7 @@
|
|||
<dependency>
|
||||
<groupId>org.dbdoclet</groupId>
|
||||
<artifactId>herold</artifactId>
|
||||
<version>6.1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
|
||||
<version>8.0.4</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -122,33 +80,6 @@
|
|||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
|
@ -192,19 +123,6 @@
|
|||
<avalon-framework.version>4.3</avalon-framework.version>
|
||||
<dbdoclet.version>8.0.2</dbdoclet.version>
|
||||
<jtidy.version>r938</jtidy.version>
|
||||
<!-- logging -->
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- testing -->
|
||||
<org.hamcrest.version>1.3</org.hamcrest.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<mockito.version>1.10.19</mockito.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,5 +1,5 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
|
@ -7,10 +7,13 @@
|
|||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- <logger name="org.springframework" level="WARN" /> -->
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -19,21 +19,21 @@ import javax.xml.transform.stream.StreamSource;
|
|||
import org.apache.fop.apps.Fop;
|
||||
import org.apache.fop.apps.FopFactory;
|
||||
import org.apache.xmlgraphics.util.MimeConstants;
|
||||
import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
|
||||
import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
|
||||
import org.dbdoclet.trafo.script.Script;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.tidy.Tidy;
|
||||
|
||||
public class ApacheFOPConvertHTMLIntegrationTest {
|
||||
private String inputFile = "src/test/resources/input.html";
|
||||
private String style = "src/test/resources/xhtml2fo.xsl";
|
||||
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||
private String output_jtidy = "src/test/resources/output_jtidy.pdf";
|
||||
private String output_html2fo = "src/test/resources/output_html2fo.pdf";
|
||||
private String output_herold = "src/test/resources/output_herold.pdf";
|
||||
private String foFile = "src/test/resources/input.fo";
|
||||
private String xmlFile = "src/test/resources/input.xml";
|
||||
private final String inputFile = "src/test/resources/input.html";
|
||||
private final String style = "src/test/resources/xhtml2fo.xsl";
|
||||
private final String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||
private final String output_jtidy = "src/test/resources/output_jtidy.pdf";
|
||||
private final String output_html2fo = "src/test/resources/output_html2fo.pdf";
|
||||
private final String output_herold = "src/test/resources/output_herold.pdf";
|
||||
private final String foFile = "src/test/resources/input.fo";
|
||||
private final String xmlFile = "src/test/resources/input.xml";
|
||||
|
||||
@Test
|
||||
public void whenTransformHTMLToPDFUsingJTidy_thenCorrect() throws Exception {
|
||||
|
@ -114,8 +114,9 @@ public class ApacheFOPConvertHTMLIntegrationTest {
|
|||
|
||||
private void fromHTMLTOXMLUsingHerold() throws Exception {
|
||||
final Script script = new Script();
|
||||
final DocBookTransformer transformer = new DocBookTransformer();
|
||||
transformer.setScript(script);
|
||||
transformer.convert(new FileInputStream(inputFile), new FileOutputStream(xmlFile));
|
||||
final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
|
||||
transformer.setInputStream(new FileInputStream(inputFile));
|
||||
transformer.setOutputStream(new FileOutputStream(xmlFile));
|
||||
transformer.transform(script);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@ import java.io.FileWriter;
|
|||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
import javax.xml.transform.Result;
|
||||
|
@ -25,19 +26,15 @@ import org.apache.fop.apps.Fop;
|
|||
import org.apache.fop.apps.FopFactory;
|
||||
import org.apache.xmlgraphics.util.MimeConstants;
|
||||
import org.dbdoclet.trafo.TrafoScriptManager;
|
||||
import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
|
||||
import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
|
||||
import org.dbdoclet.trafo.script.Script;
|
||||
import org.junit.Test;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
public class ApacheFOPHeroldLiveTest {
|
||||
private String[] inputUrls = {// @formatter:off
|
||||
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
|
||||
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
|
||||
"http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/",
|
||||
"http://www.baeldung.com/spring-security-basic-authentication",
|
||||
"http://www.baeldung.com/spring-security-digest-authentication",
|
||||
"http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/",
|
||||
private final String[] inputUrls = {// @formatter:off
|
||||
// "http://www.baeldung.com/spring-security-basic-authentication",
|
||||
"http://www.baeldung.com/spring-security-digest-authentication"
|
||||
//"http://www.baeldung.com/spring-httpmessageconverter-rest",
|
||||
//"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/",
|
||||
//"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/",
|
||||
|
@ -49,10 +46,10 @@ public class ApacheFOPHeroldLiveTest {
|
|||
//"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/"
|
||||
}; // @formatter:on
|
||||
|
||||
private String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||
private String output_file = "src/test/resources/final_output.pdf";
|
||||
private String xmlInput = "src/test/resources/input.xml";
|
||||
private String xmlOutput = "src/test/resources/output.xml";
|
||||
private final String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
|
||||
private final String output_file = "src/test/resources/final_output.pdf";
|
||||
private final String xmlInput = "src/test/resources/input.xml";
|
||||
private final String xmlOutput = "src/test/resources/output.xml";
|
||||
|
||||
// tests
|
||||
|
||||
|
@ -75,10 +72,11 @@ public class ApacheFOPHeroldLiveTest {
|
|||
final TrafoScriptManager mgr = new TrafoScriptManager();
|
||||
final File profileFile = new File("src/test/resources/default.her");
|
||||
script = mgr.parseScript(profileFile);
|
||||
final DocBookTransformer transformer = new DocBookTransformer();
|
||||
transformer.setScript(script);
|
||||
final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
|
||||
transformer.setInputStream(getInputStream(input));
|
||||
transformer.setOutputStream(new FileOutputStream(xmlInput, append));
|
||||
|
||||
transformer.convert(getInputStream(input), new FileOutputStream(xmlInput, append));
|
||||
transformer.transform(script);
|
||||
}
|
||||
|
||||
private Document fromXMLFileToFO() throws Exception {
|
||||
|
@ -112,7 +110,9 @@ public class ApacheFOPHeroldLiveTest {
|
|||
|
||||
private InputStream getInputStream(final String input) throws IOException {
|
||||
final URL url = new URL(input);
|
||||
return url.openStream();
|
||||
final HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
|
||||
httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
|
||||
return httpcon.getInputStream();
|
||||
}
|
||||
|
||||
private void fixXML(final String input, final String output) throws IOException {
|
||||
|
@ -127,7 +127,7 @@ public class ApacheFOPHeroldLiveTest {
|
|||
|
||||
if (line.contains("info>")) {
|
||||
writer.write(line.replace("info>", "section>"));
|
||||
} else if (!((line.startsWith("<?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("\n");
|
||||
|
|
Binary file not shown.
|
@ -1 +1,3 @@
|
|||
*.docx
|
||||
temp.xls
|
||||
temp.xlsx
|
||||
|
|
|
@ -5,34 +5,18 @@
|
|||
<artifactId>apache-poi</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<poi.version>3.15</poi.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
<jexcel.version>1.0.6</jexcel.version>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
|
@ -42,6 +26,12 @@
|
|||
<groupId>org.jxls</groupId>
|
||||
<artifactId>jxls-jexcel</artifactId>
|
||||
<version>${jexcel.version}</version>
|
||||
</dependency>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
package com.baeldung.jexcel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jexcel.JExcelHelper;
|
||||
|
||||
import jxl.write.WriteException;
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
import org.junit.After;
|
||||
|
||||
public class JExcelIntegrationTest {
|
||||
|
||||
private JExcelHelper jExcelHelper;
|
||||
private static String FILE_NAME = "temp.xls";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException, WriteException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
jExcelHelper = new JExcelHelper();
|
||||
jExcelHelper.writeJExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = jExcelHelper.readJExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(2)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup(){
|
||||
File testFile = new File(fileLocation);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,56 +0,0 @@
|
|||
package com.baeldung.jexcel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jexcel.JExcelHelper;
|
||||
|
||||
import jxl.write.WriteException;
|
||||
import jxl.read.biff.BiffException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class JExcelTest {
|
||||
|
||||
private JExcelHelper jExcelHelper;
|
||||
private static String FILE_NAME = "temp.xls";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException, WriteException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
jExcelHelper = new JExcelHelper();
|
||||
jExcelHelper.writeJExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
|
||||
Map<Integer, List<String>> data = jExcelHelper.readJExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(2)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(2)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.poi.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.poi.excel.ExcelPOIHelper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
import org.junit.After;
|
||||
|
||||
public class ExcelIntegrationTest {
|
||||
|
||||
private ExcelPOIHelper excelPOIHelper;
|
||||
private static String FILE_NAME = "temp.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
excelPOIHelper = new ExcelPOIHelper();
|
||||
excelPOIHelper.writeExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = excelPOIHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(1)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(1)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup(){
|
||||
File testFile = new File(fileLocation);
|
||||
if (testFile.exists()) {
|
||||
testFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
package com.baeldung.poi.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import jxl.read.biff.BiffException;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.poi.excel.ExcelPOIHelper;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
public class ExcelTest {
|
||||
|
||||
private ExcelPOIHelper excelPOIHelper;
|
||||
private static String FILE_NAME = "temp.xlsx";
|
||||
private String fileLocation;
|
||||
|
||||
@Before
|
||||
public void generateExcelFile() throws IOException {
|
||||
|
||||
File currDir = new File(".");
|
||||
String path = currDir.getAbsolutePath();
|
||||
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
|
||||
|
||||
excelPOIHelper = new ExcelPOIHelper();
|
||||
excelPOIHelper.writeExcel();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
|
||||
Map<Integer, List<String>> data = excelPOIHelper.readExcel(fileLocation);
|
||||
|
||||
assertEquals("Name", data.get(0)
|
||||
.get(0));
|
||||
assertEquals("Age", data.get(0)
|
||||
.get(1));
|
||||
|
||||
assertEquals("John Smith", data.get(1)
|
||||
.get(0));
|
||||
assertEquals("20", data.get(1)
|
||||
.get(1));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.poi.word;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WordIntegrationTest {
|
||||
static WordDocument wordDocument;
|
||||
|
||||
@BeforeClass
|
||||
public static void generateMSWordFile() throws Exception {
|
||||
WordIntegrationTest.wordDocument = new WordDocument();
|
||||
wordDocument.handleSimpleDoc();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingOutputDocument_thenCorrect() throws Exception {
|
||||
Path msWordPath = Paths.get(WordDocument.output);
|
||||
XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
|
||||
List<XWPFParagraph> paragraphs = document.getParagraphs();
|
||||
document.close();
|
||||
|
||||
XWPFParagraph title = paragraphs.get(0);
|
||||
XWPFRun titleRun = title.getRuns().get(0);
|
||||
assertEquals("Build Your REST API with Spring", title.getText());
|
||||
assertEquals("009933", titleRun.getColor());
|
||||
assertTrue(titleRun.isBold());
|
||||
assertEquals("Courier", titleRun.getFontFamily());
|
||||
assertEquals(20, titleRun.getFontSize());
|
||||
|
||||
assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
|
||||
assertEquals("What makes a good API?", paragraphs.get(3).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
|
||||
}
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
package com.baeldung.poi.word;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFRun;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WordTest {
|
||||
static WordDocument wordDocument;
|
||||
|
||||
@BeforeClass
|
||||
public static void generateMSWordFile() throws Exception {
|
||||
WordTest.wordDocument = new WordDocument();
|
||||
wordDocument.handleSimpleDoc();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParsingOutputDocument_thenCorrect() throws Exception {
|
||||
Path msWordPath = Paths.get(WordDocument.output);
|
||||
XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
|
||||
List<XWPFParagraph> paragraphs = document.getParagraphs();
|
||||
document.close();
|
||||
|
||||
XWPFParagraph title = paragraphs.get(0);
|
||||
XWPFRun titleRun = title.getRuns().get(0);
|
||||
assertEquals("Build Your REST API with Spring", title.getText());
|
||||
assertEquals("009933", titleRun.getColor());
|
||||
assertTrue(titleRun.isBold());
|
||||
assertEquals("Courier", titleRun.getFontFamily());
|
||||
assertEquals(20, titleRun.getFontSize());
|
||||
|
||||
assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
|
||||
assertEquals("What makes a good API?", paragraphs.get(3).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
|
||||
assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
|
||||
}
|
||||
}
|
Binary file not shown.
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)
|
|
@ -1,50 +1,23 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-solrj</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-solrj</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>apache-solrj</name>
|
||||
|
||||
<properties>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.solr</groupId>
|
||||
<artifactId>solr-solrj</artifactId>
|
||||
<version>6.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.solr</groupId>
|
||||
<artifactId>solr-solrj</artifactId>
|
||||
<version>6.4.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -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());
|
||||
}
|
||||
|
||||
public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
|
||||
|
||||
solrClient.addBean(pBean);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
|
||||
|
||||
SolrInputDocument document = new SolrInputDocument();
|
||||
|
@ -27,12 +33,18 @@ public class SolrJavaIntegration {
|
|||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void deleteSolrDocument(String documentId) throws SolrServerException, IOException {
|
||||
public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
|
||||
|
||||
solrClient.deleteById(documentId);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
|
||||
|
||||
solrClient.deleteByQuery(query);
|
||||
solrClient.commit();
|
||||
}
|
||||
|
||||
protected HttpSolrClient getSolrClient() {
|
||||
return solrClient;
|
||||
}
|
||||
|
@ -40,4 +52,5 @@ public class SolrJavaIntegration {
|
|||
protected void setSolrClient(HttpSolrClient solrClient) {
|
||||
this.solrClient = solrClient;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ public class SolrJavaIntegrationTest {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenVerifyAdded() throws SolrServerException, IOException {
|
||||
public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
|
@ -33,18 +33,68 @@ public class SolrJavaIntegrationTest {
|
|||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(docList.getNumFound(), 1);
|
||||
assertEquals(1, docList.getNumFound());
|
||||
|
||||
for (SolrDocument doc : docList) {
|
||||
assertEquals((String) doc.getFieldValue("id"), "123456");
|
||||
assertEquals((Double) doc.getFieldValue("price"), (Double) 599.99);
|
||||
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDelete_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
|
||||
|
||||
solrJavaIntegration.deleteSolrDocument("123456");
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "price:599.99");
|
||||
QueryResponse response = null;
|
||||
|
||||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(1, docList.getNumFound());
|
||||
|
||||
for (SolrDocument doc : docList) {
|
||||
assertEquals("123456", (String) doc.getFieldValue("id"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||
|
||||
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
|
||||
assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
|
||||
|
||||
ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
|
||||
solrJavaIntegration.addProductBean(pBean);
|
||||
|
||||
SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
|
||||
assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
|
||||
assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
|
||||
solrJavaIntegration.deleteSolrDocumentById("123456");
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(0, docList.getNumFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
|
||||
|
||||
solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
|
||||
|
||||
SolrQuery query = new SolrQuery();
|
||||
query.set("q", "id:123456");
|
||||
|
@ -53,6 +103,6 @@ public class SolrJavaIntegrationTest {
|
|||
response = solrJavaIntegration.getSolrClient().query(query);
|
||||
|
||||
SolrDocumentList docList = response.getResults();
|
||||
assertEquals(docList.getNumFound(), 0);
|
||||
assertEquals(0, docList.getNumFound());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,10 +6,14 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<java.versin>1.8</java.versin>
|
||||
<junit.version>4.12</junit.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<thrift.version>0.10.0</thrift.version>
|
||||
<maven-thrift.version>0.1.11</maven-thrift.version>
|
||||
</properties>
|
||||
|
@ -19,13 +23,12 @@
|
|||
<groupId>org.apache.thrift</groupId>
|
||||
<artifactId>libthrift</artifactId>
|
||||
<version>${thrift.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
@ -39,22 +42,15 @@
|
|||
<build>
|
||||
<defaultGoal>install</defaultGoal>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>generate-sources</phase>
|
||||
<goals><goal>add-source</goal></goals>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>generated</source>
|
||||
|
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CrossPlatformServiceIntegrationTest {
|
||||
|
||||
private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
server.start();
|
||||
} catch (TTransportException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
try {
|
||||
// wait for the server start up
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ping() {
|
||||
CrossPlatformServiceClient client = new CrossPlatformServiceClient();
|
||||
Assert.assertTrue(client.ping());
|
||||
}
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
package com.baeldung.thrift;
|
||||
|
||||
import org.apache.thrift.transport.TTransportException;
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CrossPlatformServiceTest {
|
||||
|
||||
private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
server.start();
|
||||
} catch (TTransportException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
try {
|
||||
// wait for the server start up
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
server.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ping() {
|
||||
CrossPlatformServiceClient client = new CrossPlatformServiceClient();
|
||||
Assert.assertTrue(client.ping());
|
||||
}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
<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">
|
||||
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.baeldung</groupId>
|
||||
|
@ -9,27 +9,22 @@
|
|||
<packaging>war</packaging>
|
||||
<name>apache-velocity</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<jdk.version>1.8</jdk.version>
|
||||
<jstl.version>1.2</jstl.version>
|
||||
<junit.version>4.11</junit.version>
|
||||
<logback.version>1.0.13</logback.version>
|
||||
<jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
|
||||
<velocity-version>1.7</velocity-version>
|
||||
<velocity-tools-version>2.0</velocity-tools-version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.velocity</groupId>
|
||||
<artifactId>velocity</artifactId>
|
||||
|
@ -40,21 +35,17 @@
|
|||
<artifactId>velocity-tools</artifactId>
|
||||
<version>${velocity-tools-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>${jcl-over-slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${org.apache.httpcomponents.version}</version>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
|
@ -66,15 +57,6 @@
|
|||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${jdk.version}</source>
|
||||
<target>${jdk.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
|
@ -83,19 +65,6 @@
|
|||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<systemPropertyVariables>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
|
|
@ -1,23 +1,19 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<Pattern>
|
||||
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
|
||||
</Pattern>
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<logger name="com.baeldung.apache.velocity.service" level="debug"
|
||||
additivity="false">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</logger>
|
||||
|
||||
<root level="error">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -1,3 +0,0 @@
|
|||
### Relevant Articles:
|
||||
- [Intro to AspectJ](http://www.baeldung.com/aspectj)
|
||||
- [Spring Performance Logging](http://www.baeldung.com/spring-performance-logging)
|
143
aspectj/pom.xml
143
aspectj/pom.xml
|
@ -1,143 +0,0 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>aspectj</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>aspectj</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjrt</artifactId>
|
||||
<version>${aspectj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${aspectj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-core</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- unit test -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-beans</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cglib</groupId>
|
||||
<artifactId>cglib</artifactId>
|
||||
<version>3.2.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>1.2.17</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>aspectj</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${source.version}</source>
|
||||
<target>${source.version}</target>
|
||||
</configuration>
|
||||
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>aspectj-maven-plugin</artifactId>
|
||||
<version>1.7</version>
|
||||
<configuration>
|
||||
<complianceLevel>${source.version}</complianceLevel>
|
||||
<source>${source.version}</source>
|
||||
<target>${source.version}</target>
|
||||
<showWeaveInfo>true</showWeaveInfo>
|
||||
<verbose>true</verbose>
|
||||
<Xlint>ignore</Xlint>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
<!-- Post-compile weaving -->
|
||||
<!-- <weaveDependencies> <weaveDependency> <groupId>org.agroup</groupId> <artifactId>to-weave</artifactId> </weaveDependency>
|
||||
<weaveDependency> <groupId>org.anothergroup</groupId> <artifactId>gen</artifactId> </weaveDependency> </weaveDependencies> -->
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version>
|
||||
<configuration> <argLine>-javaagent:"${settings.localRepository}"/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar</argLine>
|
||||
<useSystemClassLoader>true</useSystemClassLoader> <forkMode>always</forkMode> </configuration> </plugin> -->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<source.version>1.8</source.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<aspectj.version>1.8.9</aspectj.version>
|
||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||
<logback.version>1.1.7</logback.version>
|
||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,13 +0,0 @@
|
|||
package com.baeldung.aspectj;
|
||||
|
||||
public class Account {
|
||||
int balance = 20;
|
||||
|
||||
public boolean withdraw(int amount) {
|
||||
if (balance < amount) {
|
||||
return false;
|
||||
}
|
||||
balance = balance - amount;
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
package com.baeldung.performancemonitor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class Person {
|
||||
private String lastName;
|
||||
private String firstName;
|
||||
private LocalDate dateOfBirth;
|
||||
|
||||
public Person() {
|
||||
}
|
||||
|
||||
public Person(String firstName, String lastName, LocalDate dateOfBirth) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public LocalDate getDateOfBirth() {
|
||||
return dateOfBirth;
|
||||
}
|
||||
|
||||
public void setDateOfBirth(LocalDate dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue