fix conflicts in pom.xml

This commit is contained in:
Dassi Orleando 2017-08-24 21:13:59 +01:00
commit 03904ad090
5864 changed files with 505857 additions and 39706 deletions

13
.gitignore vendored
View File

@ -1,3 +1,5 @@
*/bin/*
*.class
# Package Files #
@ -28,3 +30,14 @@ target/
spring-openid/src/main/resources/application.properties
.recommenders/
/spring-hibernate4/nbproject/
spring-security-openid/src/main/resources/application.properties
spring-all/*.log
*.jar
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties

23
.travis.yml Normal file
View File

@ -0,0 +1,23 @@
language: java
before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: travis_wait 60 mvn -q test -fae
sudo: required
jdk:
- oraclejdk8
addons:
apt:
packages:
- oracle-java8-installer
cache:
directories:
- .autoconf
- $HOME/.m2

3
JGit/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [A Guide to JGit](http://www.baeldung.com/jgit)

View File

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

View File

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

View File

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

View File

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

View File

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

3
Twitter4J/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)

52
Twitter4J/pom.xml Normal file
View File

@ -0,0 +1,52 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/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>

View File

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

View File

@ -0,0 +1,4 @@
oauth.consumerKey=//TODO
oauth.consumerSecret=//TODO
oauth.accessToken=//TODO
oauth.accessTokenSecret=//TODO

View File

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

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

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

30
akka-streams/pom.xml Normal file
View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-streams</artifactId>
<name>akka-streams</name>
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.11</artifactId>
<version>${akkastreams.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream-testkit_2.11</artifactId>
<version>${akkastreams.version}</version>
</dependency>
</dependencies>
<properties>
<akkastreams.version>2.5.2</akkastreams.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.akkastreams;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
public class AverageRepository {
CompletionStage<Double> save(Double average) {
return CompletableFuture.supplyAsync(() -> {
System.out.println("saving average: " + average);
return average;
});
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.akkastreams;
import akka.Done;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Keep;
import akka.stream.javadsl.Sink;
import akka.stream.javadsl.Source;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
public class DataImporter {
private final ActorSystem actorSystem;
private final AverageRepository averageRepository = new AverageRepository();
public DataImporter(ActorSystem actorSystem) {
this.actorSystem = actorSystem;
}
private List<Integer> parseLine(String line) {
String[] fields = line.split(";");
return Arrays.stream(fields)
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private Flow<String, Integer, NotUsed> parseContent() {
return Flow.of(String.class).mapConcat(this::parseLine);
}
private Flow<Integer, Double, NotUsed> computeAverage() {
return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers ->
CompletableFuture.supplyAsync(() -> integers
.stream()
.mapToDouble(v -> v)
.average()
.orElse(-1.0)));
}
Flow<String, Double, NotUsed> calculateAverage() {
return Flow.of(String.class)
.via(parseContent())
.via(computeAverage());
}
private Sink<Double, CompletionStage<Done>> storeAverages() {
return Flow.of(Double.class)
.mapAsyncUnordered(4, averageRepository::save)
.toMat(Sink.ignore(), Keep.right());
}
CompletionStage<Done> calculateAverageForContent(String content) {
return Source.single(content)
.via(calculateAverage())
.runWith(storeAverages(), ActorMaterializer.create(actorSystem))
.whenComplete((d, e) -> {
if (d != null) {
System.out.println("Import finished ");
} else {
e.printStackTrace();
}
});
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.akkastreams;
import akka.NotUsed;
import akka.actor.ActorSystem;
import akka.stream.ActorMaterializer;
import akka.stream.javadsl.Flow;
import akka.stream.javadsl.Source;
import akka.stream.testkit.javadsl.TestSink;
import org.junit.Test;
public class DataImporterUnitTest {
private final ActorSystem actorSystem = ActorSystem.create();
@Test
public void givenStreamOfIntegers_whenCalculateAverageOfPairs_thenShouldReturnProperResults() {
//given
Flow<String, Double, NotUsed> tested = new DataImporter(actorSystem).calculateAverage();
String input = "1;9;11;0";
//when
Source<Double, NotUsed> flow = Source.single(input).via(tested);
//then
flow
.runWith(TestSink.probe(actorSystem), ActorMaterializer.create(actorSystem))
.request(4)
.expectNextUnordered(5d, 5.5);
}
@Test
public void givenStreamOfIntegers_whenCalculateAverageAndSaveToSink_thenShouldFinishSuccessfully() {
//given
DataImporter dataImporter = new DataImporter(actorSystem);
String input = "10;90;110;10";
//when
dataImporter.calculateAverageForContent(input)
.thenAccept(d -> actorSystem.terminate());
}
}

1
algorithms/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

10
algorithms/README.md Normal file
View File

@ -0,0 +1,10 @@
## Relevant articles:
- [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)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)

View File

@ -6,33 +6,39 @@
<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>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
<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>
<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>
@ -41,4 +47,23 @@
</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>

View File

@ -0,0 +1,53 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BinarySearch {
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int index = Integer.MAX_VALUE;
while (low <= high) {
int mid = (low + high) / 2;
if (sortedArray[mid] < key) {
low = mid + 1;
} else if (sortedArray[mid] > key) {
high = mid - 1;
} else if (sortedArray[mid] == key) {
index = mid;
break;
}
}
return index;
}
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2;
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
}

View File

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

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.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();
}

View File

@ -0,0 +1,30 @@
package com.baeldung.algorithms.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();
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms.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;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.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));
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.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();
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.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();
}

View File

@ -1,58 +0,0 @@
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;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
import lombok.Data;

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
public class SimulatedAnnealing {

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.annealing;
package com.baeldung.algorithms.ga.annealing;
import java.util.ArrayList;
import java.util.Collections;

View File

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

View File

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

View File

@ -0,0 +1,44 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class Individual {
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private int fitness = 0;
public Individual() {
for (int i = 0; i < genes.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
protected byte getSingleGene(int index) {
return genes[index];
}
protected void setSingleGene(int index, byte value) {
genes[index] = value;
fitness = 0;
}
public int getFitness() {
if (fitness == 0) {
fitness = SimpleGeneticAlgorithm.getFitness(this);
}
return fitness;
}
@Override
public String toString() {
String geneString = "";
for (int i = 0; i < genes.length; i++) {
geneString += getSingleGene(i);
}
return geneString;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.algorithms.ga.binary;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class Population {
private List<Individual> individuals;
public Population(int size, boolean createNew) {
individuals = new ArrayList<>();
if (createNew) {
createNewPopulation(size);
}
}
protected Individual getIndividual(int index) {
return individuals.get(index);
}
protected Individual getFittest() {
Individual fittest = individuals.get(0);
for (int i = 0; i < individuals.size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
private void createNewPopulation(int size) {
for (int i = 0; i < size; i++) {
Individual newIndividual = new Individual();
individuals.add(i, newIndividual);
}
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.algorithms.ga.binary;
import lombok.Data;
@Data
public class SimpleGeneticAlgorithm {
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.025;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
private static byte[] solution = new byte[64];
public boolean runAlgorithm(int populationSize, String solution) {
if (solution.length() != SimpleGeneticAlgorithm.solution.length) {
throw new RuntimeException("The solution needs to have " + SimpleGeneticAlgorithm.solution.length + " bytes");
}
setSolution(solution);
Population myPop = new Population(populationSize, true);
int generationCount = 1;
while (myPop.getFittest().getFitness() < getMaxFitness()) {
System.out.println("Generation: " + generationCount + " Correct genes found: " + myPop.getFittest().getFitness());
myPop = evolvePopulation(myPop);
generationCount++;
}
System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println("Genes: ");
System.out.println(myPop.getFittest());
return true;
}
public Population evolvePopulation(Population pop) {
int elitismOffset;
Population newPopulation = new Population(pop.getIndividuals().size(), false);
if (elitism) {
newPopulation.getIndividuals().add(0, pop.getFittest());
elitismOffset = 1;
} else {
elitismOffset = 0;
}
for (int i = elitismOffset; i < pop.getIndividuals().size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.getIndividuals().add(i, newIndiv);
}
for (int i = elitismOffset; i < newPopulation.getIndividuals().size(); i++) {
mutate(newPopulation.getIndividual(i));
}
return newPopulation;
}
private Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
if (Math.random() <= uniformRate) {
newSol.setSingleGene(i, indiv1.getSingleGene(i));
} else {
newSol.setSingleGene(i, indiv2.getSingleGene(i));
}
}
return newSol;
}
private void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);
}
}
}
private Individual tournamentSelection(Population pop) {
Population tournament = new Population(tournamentSize, false);
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.getIndividuals().size());
tournament.getIndividuals().add(i, pop.getIndividual(randomId));
}
Individual fittest = tournament.getFittest();
return fittest;
}
protected static int getFitness(Individual individual) {
int fitness = 0;
for (int i = 0; i < individual.getDefaultGeneLength() && i < solution.length; i++) {
if (individual.getSingleGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
protected int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
protected void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.dijkstra;
package com.baeldung.algorithms.ga.dijkstra;
import java.util.HashSet;
import java.util.LinkedList;

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.dijkstra;
package com.baeldung.algorithms.ga.dijkstra;
import java.util.HashSet;
import java.util.Set;

View File

@ -0,0 +1,58 @@
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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,189 @@
package com.baeldung.algorithms.hillclimbing;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Stack;
public class HillClimbing {
public static void main(String[] args) {
HillClimbing hillClimbing = new HillClimbing();
String blockArr[] = { "B", "C", "D", "A" };
Stack<String> startState = hillClimbing.getStackWithValues(blockArr);
String goalBlockArr[] = { "A", "B", "C", "D" };
Stack<String> goalState = hillClimbing.getStackWithValues(goalBlockArr);
try {
List<State> solutionSequence = hillClimbing.getRouteWithHillClimbing(startState, goalState);
solutionSequence.forEach(HillClimbing::printEachStep);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printEachStep(State state) {
List<Stack<String>> stackList = state.getState();
System.out.println("----------------");
stackList.forEach(stack -> {
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
System.out.println(" ");
});
}
private Stack<String> getStackWithValues(String[] blocks) {
Stack<String> stack = new Stack<>();
for (String block : blocks)
stack.push(block);
return stack;
}
/**
* This method prepares path from init state to goal state
*/
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
List<Stack<String>> initStateStackList = new ArrayList<>();
initStateStackList.add(initStateStack);
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
State initState = new State(initStateStackList, initStateHeuristics);
List<State> resultPath = new ArrayList<>();
resultPath.add(new State(initState));
State currentState = initState;
boolean noStateFound = false;
while (!currentState.getState()
.get(0)
.equals(goalStateStack) || noStateFound) {
noStateFound = true;
State nextState = findNextState(currentState, goalStateStack);
if (nextState != null) {
noStateFound = false;
currentState = nextState;
resultPath.add(new State(nextState));
}
}
return resultPath;
}
/**
* This method finds new state from current state based on goal and
* heuristics
*/
public State findNextState(State currentState, Stack<String> goalStateStack) {
List<Stack<String>> listOfStacks = currentState.getState();
int currentStateHeuristics = currentState.getHeuristics();
return listOfStacks.stream()
.map(stack -> {
return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
}
/**
* This method applies operations on the current state to get a new state
*/
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
State tempState;
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
String block = stack.pop();
if (stack.size() == 0)
tempStackList.remove(stack);
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
if (tempState == null) {
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
}
if (tempState == null)
stack.push(block);
return tempState;
}
/**
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into a new stack
*/
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
State newState = null;
Stack<String> newStack = new Stack<>();
newStack.push(block);
currentStackList.add(newStack);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
newState = new State(currentStackList, newStateHeuristics);
} else {
currentStackList.remove(newStack);
}
return newState;
}
/**
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into one of the other stacks to explore new
* states
*/
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
Optional<State> newState = currentStackList.stream()
.filter(stack -> stack != currentStack)
.map(stack -> {
return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst();
return newState.orElse(null);
}
/**
* This method pushes a block to the stack and returns new state if its closer to goal
*/
private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) {
stack.push(block);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
return new State(currentStackList, newStateHeuristics);
}
stack.pop();
return null;
}
/**
* This method returns heuristics value for given state with respect to goal
* state
*/
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
Integer heuristicValue;
heuristicValue = currentState.stream()
.mapToInt(stack -> {
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
})
.sum();
return heuristicValue;
}
/**
* This method returns heuristics value for a particular stack
*/
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
int stackHeuristics = 0;
boolean isPositioneCorrect = true;
int goalStartIndex = 0;
for (String currentBlock : stack) {
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
stackHeuristics += goalStartIndex;
} else {
stackHeuristics -= goalStartIndex;
isPositioneCorrect = false;
}
goalStartIndex++;
}
return stackHeuristics;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.algorithms.hillclimbing;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class State {
private List<Stack<String>> state;
private int heuristics;
public State(List<Stack<String>> state) {
this.state = state;
}
State(List<Stack<String>> state, int heuristics) {
this.state = state;
this.heuristics = heuristics;
}
State(State state) {
if (state != null) {
this.state = new ArrayList<>();
for (Stack s : state.getState()) {
Stack s1;
s1 = (Stack) s.clone();
this.state.add(s1);
}
this.heuristics = state.getHeuristics();
}
}
public List<Stack<String>> getState() {
return state;
}
public int getHeuristics() {
return heuristics;
}
public void setHeuristics(int heuristics) {
this.heuristics = heuristics;
}
}

View File

@ -0,0 +1,109 @@
package com.baeldung.algorithms.mcts.montecarlo;
import java.util.List;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tree.Node;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MonteCarloTreeSearch {
private static final int WIN_SCORE = 10;
private int level;
private int oponent;
public MonteCarloTreeSearch() {
this.level = 3;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
private int getMillisForCurrentLevel() {
return 2 * (this.level - 1) + 1;
}
public Board findNextMove(Board board, int playerNo) {
long start = System.currentTimeMillis();
long end = start + 60 * getMillisForCurrentLevel();
oponent = 3 - playerNo;
Tree tree = new Tree();
Node rootNode = tree.getRoot();
rootNode.getState().setBoard(board);
rootNode.getState().setPlayerNo(oponent);
while (System.currentTimeMillis() < end) {
// Phase 1 - Selection
Node promisingNode = selectPromisingNode(rootNode);
// Phase 2 - Expansion
if (promisingNode.getState().getBoard().checkStatus() == Board.IN_PROGRESS)
expandNode(promisingNode);
// Phase 3 - Simulation
Node nodeToExplore = promisingNode;
if (promisingNode.getChildArray().size() > 0) {
nodeToExplore = promisingNode.getRandomChildNode();
}
int playoutResult = simulateRandomPlayout(nodeToExplore);
// Phase 4 - Update
backPropogation(nodeToExplore, playoutResult);
}
Node winnerNode = rootNode.getChildWithMaxScore();
tree.setRoot(winnerNode);
return winnerNode.getState().getBoard();
}
private Node selectPromisingNode(Node rootNode) {
Node node = rootNode;
while (node.getChildArray().size() != 0) {
node = UCT.findBestNodeWithUCT(node);
}
return node;
}
private void expandNode(Node node) {
List<State> possibleStates = node.getState().getAllPossibleStates();
possibleStates.forEach(state -> {
Node newNode = new Node(state);
newNode.setParent(node);
newNode.getState().setPlayerNo(node.getState().getOpponent());
node.getChildArray().add(newNode);
});
}
private void backPropogation(Node nodeToExplore, int playerNo) {
Node tempNode = nodeToExplore;
while (tempNode != null) {
tempNode.getState().incrementVisit();
if (tempNode.getState().getPlayerNo() == playerNo)
tempNode.getState().addScore(WIN_SCORE);
tempNode = tempNode.getParent();
}
}
private int simulateRandomPlayout(Node node) {
Node tempNode = new Node(node);
State tempState = tempNode.getState();
int boardStatus = tempState.getBoard().checkStatus();
if (boardStatus == oponent) {
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
return boardStatus;
}
while (boardStatus == Board.IN_PROGRESS) {
tempState.togglePlayer();
tempState.randomPlay();
boardStatus = tempState.getBoard().checkStatus();
}
return boardStatus;
}
}

View File

@ -0,0 +1,97 @@
package com.baeldung.algorithms.mcts.montecarlo;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
public class State {
private Board board;
private int playerNo;
private int visitCount;
private double winScore;
public State() {
board = new Board();
}
public State(State state) {
this.board = new Board(state.getBoard());
this.playerNo = state.getPlayerNo();
this.visitCount = state.getVisitCount();
this.winScore = state.getWinScore();
}
public State(Board board) {
this.board = new Board(board);
}
Board getBoard() {
return board;
}
void setBoard(Board board) {
this.board = board;
}
int getPlayerNo() {
return playerNo;
}
void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
int getOpponent() {
return 3 - playerNo;
}
public int getVisitCount() {
return visitCount;
}
public void setVisitCount(int visitCount) {
this.visitCount = visitCount;
}
double getWinScore() {
return winScore;
}
void setWinScore(double winScore) {
this.winScore = winScore;
}
public List<State> getAllPossibleStates() {
List<State> possibleStates = new ArrayList<>();
List<Position> availablePositions = this.board.getEmptyPositions();
availablePositions.forEach(p -> {
State newState = new State(this.board);
newState.setPlayerNo(3 - this.playerNo);
newState.getBoard().performMove(newState.getPlayerNo(), p);
possibleStates.add(newState);
});
return possibleStates;
}
void incrementVisit() {
this.visitCount++;
}
void addScore(double score) {
if (this.winScore != Integer.MIN_VALUE)
this.winScore += score;
}
void randomPlay() {
List<Position> availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
void togglePlayer() {
this.playerNo = 3 - this.playerNo;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.mcts.montecarlo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.baeldung.algorithms.mcts.tree.Node;
public class UCT {
public static double uctValue(int totalVisit, double nodeWinScore, int nodeVisit) {
if (nodeVisit == 0) {
return Integer.MAX_VALUE;
}
return (nodeWinScore / (double) nodeVisit) + 1.41 * Math.sqrt(Math.log(totalVisit) / (double) nodeVisit);
}
static Node findBestNodeWithUCT(Node node) {
int parentVisit = node.getState().getVisitCount();
return Collections.max(
node.getChildArray(),
Comparator.comparing(c -> uctValue(parentVisit, c.getState().getWinScore(), c.getState().getVisitCount())));
}
}

View File

@ -0,0 +1,155 @@
package com.baeldung.algorithms.mcts.tictactoe;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Board {
int[][] boardValues;
int totalMoves;
public static final int DEFAULT_BOARD_SIZE = 3;
public static final int IN_PROGRESS = -1;
public static final int DRAW = 0;
public static final int P1 = 1;
public static final int P2 = 2;
public Board() {
boardValues = new int[DEFAULT_BOARD_SIZE][DEFAULT_BOARD_SIZE];
}
public Board(int boardSize) {
boardValues = new int[boardSize][boardSize];
}
public Board(int[][] boardValues) {
this.boardValues = boardValues;
}
public Board(int[][] boardValues, int totalMoves) {
this.boardValues = boardValues;
this.totalMoves = totalMoves;
}
public Board(Board board) {
int boardLength = board.getBoardValues().length;
this.boardValues = new int[boardLength][boardLength];
int[][] boardValues = board.getBoardValues();
int n = boardValues.length;
for (int i = 0; i < n; i++) {
int m = boardValues[i].length;
for (int j = 0; j < m; j++) {
this.boardValues[i][j] = boardValues[i][j];
}
}
}
public void performMove(int player, Position p) {
this.totalMoves++;
boardValues[p.getX()][p.getY()] = player;
}
public int[][] getBoardValues() {
return boardValues;
}
public void setBoardValues(int[][] boardValues) {
this.boardValues = boardValues;
}
public int checkStatus() {
int boardSize = boardValues.length;
int maxIndex = boardSize - 1;
int[] diag1 = new int[boardSize];
int[] diag2 = new int[boardSize];
for (int i = 0; i < boardSize; i++) {
int[] row = boardValues[i];
int[] col = new int[boardSize];
for (int j = 0; j < boardSize; j++) {
col[j] = boardValues[j][i];
}
int checkRowForWin = checkForWin(row);
if(checkRowForWin!=0)
return checkRowForWin;
int checkColForWin = checkForWin(col);
if(checkColForWin!=0)
return checkColForWin;
diag1[i] = boardValues[i][i];
diag2[i] = boardValues[maxIndex - i][i];
}
int checkDia1gForWin = checkForWin(diag1);
if(checkDia1gForWin!=0)
return checkDia1gForWin;
int checkDiag2ForWin = checkForWin(diag2);
if(checkDiag2ForWin!=0)
return checkDiag2ForWin;
if (getEmptyPositions().size() > 0)
return IN_PROGRESS;
else
return DRAW;
}
private int checkForWin(int[] row) {
boolean isEqual = true;
int size = row.length;
int previous = row[0];
for (int i = 0; i < size; i++) {
if (previous != row[i]) {
isEqual = false;
break;
}
previous = row[i];
}
if(isEqual)
return previous;
else
return 0;
}
public void printBoard() {
int size = this.boardValues.length;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(boardValues[i][j] + " ");
}
System.out.println();
}
}
public List<Position> getEmptyPositions() {
int size = this.boardValues.length;
List<Position> emptyPositions = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (boardValues[i][j] == 0)
emptyPositions.add(new Position(i, j));
}
}
return emptyPositions;
}
public void printStatus() {
switch (this.checkStatus()) {
case P1:
System.out.println("Player 1 wins");
break;
case P2:
System.out.println("Player 2 wins");
break;
case DRAW:
System.out.println("Game Draw");
break;
case IN_PROGRESS:
System.out.println("Game In rogress");
break;
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.mcts.tictactoe;
public class Position {
int x;
int y;
public Position() {
}
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.algorithms.mcts.tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.baeldung.algorithms.mcts.montecarlo.State;
public class Node {
State state;
Node parent;
List<Node> childArray;
public Node() {
this.state = new State();
childArray = new ArrayList<>();
}
public Node(State state) {
this.state = state;
childArray = new ArrayList<>();
}
public Node(State state, Node parent, List<Node> childArray) {
this.state = state;
this.parent = parent;
this.childArray = childArray;
}
public Node(Node node) {
this.childArray = new ArrayList<>();
this.state = new State(node.getState());
if (node.getParent() != null)
this.parent = node.getParent();
List<Node> childArray = node.getChildArray();
for (Node child : childArray) {
this.childArray.add(new Node(child));
}
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public List<Node> getChildArray() {
return childArray;
}
public void setChildArray(List<Node> childArray) {
this.childArray = childArray;
}
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
return this.childArray.get(selectRandom);
}
public Node getChildWithMaxScore() {
return Collections.max(this.childArray, Comparator.comparing(c -> {
return c.getState().getVisitCount();
}));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.algorithms.mcts.tree;
public class Tree {
Node root;
public Tree() {
root = new Node();
}
public Tree(Node root) {
this.root = root;
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
public void addChild(Node parent, Node child) {
parent.getChildArray().add(child);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.algorithms.minimax;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class GameOfBones {
static List<Integer> getPossibleStates(int noOfBonesInHeap) {
return IntStream.rangeClosed(1, 3).boxed()
.map(i -> noOfBonesInHeap - i)
.filter(newHeapCount -> newHeapCount >= 0)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.algorithms.minimax;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
public class MiniMax {
private Tree tree;
public Tree getTree() {
return tree;
}
public void constructTree(int noOfBones) {
tree = new Tree();
Node root = new Node(noOfBones, true);
tree.setRoot(root);
constructTree(root);
}
private void constructTree(Node parentNode) {
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(parentNode.getNoOfBones());
boolean isChildMaxPlayer = !parentNode.isMaxPlayer();
listofPossibleHeaps.forEach(n -> {
Node newNode = new Node(n, isChildMaxPlayer);
parentNode.addChild(newNode);
if (newNode.getNoOfBones() > 0) {
constructTree(newNode);
}
});
}
public boolean checkWin() {
Node root = tree.getRoot();
checkWin(root);
return root.getScore() == 1;
}
private void checkWin(Node node) {
List<Node> children = node.getChildren();
boolean isMaxPlayer = node.isMaxPlayer();
children.forEach(child -> {
if (child.getNoOfBones() == 0) {
child.setScore(isMaxPlayer ? 1 : -1);
} else {
checkWin(child);
}
});
Node bestChild = findBestChild(isMaxPlayer, children);
node.setScore(bestChild.getScore());
}
private Node findBestChild(boolean isMaxPlayer, List<Node> children) {
Comparator<Node> byScoreComparator = Comparator.comparing(Node::getScore);
return children.stream()
.max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed())
.orElseThrow(NoSuchElementException::new);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.algorithms.minimax;
import java.util.ArrayList;
import java.util.List;
public class Node {
private int noOfBones;
private boolean isMaxPlayer;
private int score;
private List<Node> children;
public Node(int noOfBones, boolean isMaxPlayer) {
this.noOfBones = noOfBones;
this.isMaxPlayer = isMaxPlayer;
children = new ArrayList<>();
}
int getNoOfBones() {
return noOfBones;
}
boolean isMaxPlayer() {
return isMaxPlayer;
}
int getScore() {
return score;
}
void setScore(int score) {
this.score = score;
}
List<Node> getChildren() {
return children;
}
void addChild(Node newNode) {
children.add(newNode);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.algorithms.minimax;
public class Tree {
private Node root;
Tree() {
}
Node getRoot() {
return root;
}
void setRoot(Node root) {
this.root = root;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,6 @@
package com.baeldung.algorithms.primechecker;
public interface PrimeChecker <T> {
public boolean isPrime( T number );
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,41 @@
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int expectedIndexForSearchKey = 7;
int low = 0;
int high = sortedArray.length - 1;
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
}
@Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
}
}

View File

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

View File

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

View File

@ -0,0 +1,58 @@
package algorithms;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmTest {
private Stack<String> initStack;
private Stack<String> goalStack;
@Before
public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" };
initStack = new Stack<>();
for (String block : blockArr)
initStack.push(block);
goalStack = new Stack<>();
for (String block : goalBlockArr)
goalStack.push(block);
}
@Test
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
HillClimbing hillClimbing = new HillClimbing();
List<State> path;
try {
path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
assertNotNull(path);
assertEquals(path.get(path.size() - 1)
.getState()
.get(0), goalStack);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack);
State currentState = new State(initList);
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
State nextState = hillClimbing.findNextState(currentState, goalStack);
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
}
}

View File

@ -0,0 +1,92 @@
package algorithms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
import com.baeldung.algorithms.mcts.montecarlo.UCT;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
Tree gameTree;
MonteCarloTreeSearch mcts;
@Before
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
int availablePositions = board.getEmptyPositions().size();
assertTrue(initAvailablePositions > availablePositions);
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
board = mcts.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
mcts3.setLevel(3);
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
if (player == Board.P1)
board = mcts3.findNextMove(board, player);
else
board = mcts1.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
}
}

View File

@ -0,0 +1,73 @@
package algorithms;
import com.baeldung.algorithms.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);
}
}

View File

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

View File

@ -0,0 +1,92 @@
package algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
import com.baeldung.algorithms.mcts.montecarlo.UCT;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
private Tree gameTree;
private MonteCarloTreeSearch mcts;
@Before
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
int availablePositions = board.getEmptyPositions().size();
assertTrue(initAvailablePositions > availablePositions);
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
board = mcts.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
mcts3.setLevel(3);
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
if (player == Board.P1)
board = mcts3.findNextMove(board, player);
else
board = mcts1.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
}
}

View File

@ -0,0 +1,36 @@
package algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.baeldung.algorithms.minimax.MiniMax;
import com.baeldung.algorithms.minimax.Tree;
public class MinimaxTest {
private Tree gameTree;
private MiniMax miniMax;
@Before
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
assertNotNull(gameTree);
}
@Test
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);
miniMax.constructTree(8);
result = miniMax.checkWin();
assertFalse(result);
}
}

View File

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

View File

@ -1,6 +1,5 @@
<?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"
<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>
@ -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>

View File

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

View File

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

2
apache-bval/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Intro to Apache BVal](http://www.baeldung.com/apache-bval)

34
apache-bval/pom.xml Normal file
View File

@ -0,0 +1,34 @@
<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>apache-bval</groupId>
<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>
<artifactId>bval-jsr</artifactId>
<version>${bval.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-extras</artifactId>
<version>${bval.version}</version>
</dependency>
</dependencies>
<properties>
<bval.version>1.1.2</bval.version>
</properties>
</project>

View File

@ -0,0 +1,120 @@
package com.baeldung.model;
import java.io.File;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.apache.bval.constraints.Email;
import org.apache.bval.constraints.NotEmpty;
import org.apache.bval.extras.constraints.checkdigit.IBAN;
import org.apache.bval.extras.constraints.creditcard.Visa;
import org.apache.bval.extras.constraints.file.Directory;
import org.apache.bval.extras.constraints.net.InetAddress;
import com.baeldung.validation.Password;
public class User {
@NotNull
@Email
private String email;
@NotEmpty
@Password
private String password;
@Size(min = 1, max = 20)
private String name;
@Min(18)
private int age;
@Visa
private String cardNumber = "";
@IBAN
private String iban = "";
@InetAddress
private String website = "";
@Directory
private File mainDirectory=new File(".");
public User() {
}
public User(String email, String password, String name, int age) {
super();
this.email = email;
this.password = password;
this.name = name;
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public File getMainDirectory() {
return mainDirectory;
}
public void setMainDirectory(File mainDirectory) {
this.mainDirectory = mainDirectory;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.validation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import static java.lang.annotation.ElementType.*;
@Constraint(validatedBy = { PasswordValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {
String message() default "Invalid password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int length() default 6;
int nonAlpha() default 1;
}

View File

@ -0,0 +1,35 @@
package com.baeldung.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PasswordValidator implements ConstraintValidator<Password, String> {
private int length;
private int nonAlpha;
@Override
public void initialize(Password password) {
this.length = password.length();
this.nonAlpha = password.nonAlpha();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value.length() < length) {
return false;
}
int nonAlphaNr = 0;
for (int i = 0; i < value.length(); i++) {
if (!Character.isLetterOrDigit(value.charAt(i))) {
nonAlphaNr++;
}
}
if (nonAlphaNr < nonAlpha) {
return false;
}
return true;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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