diff --git a/.gitignore b/.gitignore
index 1352c943be..1890e8bd0e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
+*/bin/*
+
*.class
# Package Files #
@@ -27,4 +29,15 @@ target/
spring-openid/src/main/resources/application.properties
.recommenders/
-/spring-hibernate4/nbproject/
\ No newline at end of file
+/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
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000000..3a953a2e7b
--- /dev/null
+++ b/.travis.yml
@@ -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
+
+
diff --git a/JGit/README.md b/JGit/README.md
new file mode 100644
index 0000000000..5c65f1101b
--- /dev/null
+++ b/JGit/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [A Guide to JGit](http://www.baeldung.com/jgit)
diff --git a/JGit/pom.xml b/JGit/pom.xml
index 93c49edb92..6d505afcf3 100644
--- a/JGit/pom.xml
+++ b/JGit/pom.xml
@@ -6,6 +6,13 @@
1.0-SNAPSHOTjarhttp://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
UTF-81.8
@@ -40,24 +47,5 @@
slf4j-simple1.7.21
-
- junit
- junit
- 4.12
- test
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.2
-
- 1.7
- 1.7
-
-
-
-
\ No newline at end of file
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
new file mode 100644
index 0000000000..ed7168b2c2
--- /dev/null
+++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
@@ -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);
+ }
+ }
+ }
+ }
+}
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
deleted file mode 100644
index acad4e395f..0000000000
--- a/JGit/src/test/java/com/baeldung/jgit/JGitBugTest.java
+++ /dev/null
@@ -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);
- }
- }
- }
- }
-}
diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java
deleted file mode 100644
index ce3a41e657..0000000000
--- a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainTest.java
+++ /dev/null
@@ -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);
- }
-}
diff --git a/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
new file mode 100644
index 0000000000..d3b3358664
--- /dev/null
+++ b/JGit/src/test/java/com/baeldung/jgit/porcelain/PorcelainUnitTest.java
@@ -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);
+ }
+}
diff --git a/Twitter4J/README.md b/Twitter4J/README.md
new file mode 100644
index 0000000000..3057c1c4b2
--- /dev/null
+++ b/Twitter4J/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml
new file mode 100644
index 0000000000..ae0efb487f
--- /dev/null
+++ b/Twitter4J/pom.xml
@@ -0,0 +1,52 @@
+
+ 4.0.0
+ com.mabsisa
+ Twitter4J
+ jar
+ 1.0-SNAPSHOT
+ Twitter4J
+ http://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+
+
+
+
+ org.twitter4j
+ twitter4j-stream
+ 4.0.6
+
+
+
+
+ ${project.artifactId}
+
+
+ src/main/resources
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/ApplicationTest.java
+
+
+
+
+
+
+
diff --git a/Twitter4J/src/main/java/com/baeldung/Application.java b/Twitter4J/src/main/java/com/baeldung/Application.java
new file mode 100644
index 0000000000..3f961ccb4f
--- /dev/null
+++ b/Twitter4J/src/main/java/com/baeldung/Application.java
@@ -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 getTimeLine() throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ List 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 searchtweets() throws TwitterException {
+ Twitter twitter = getTwitterinstance();
+ Query query = new Query("source:twitter4j baeldung");
+ QueryResult result = twitter.search(query);
+ List 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();
+
+ }
+
+}
diff --git a/Twitter4J/src/main/resources/twitter4j.properties b/Twitter4J/src/main/resources/twitter4j.properties
new file mode 100644
index 0000000000..ee11dc62a1
--- /dev/null
+++ b/Twitter4J/src/main/resources/twitter4j.properties
@@ -0,0 +1,4 @@
+oauth.consumerKey=//TODO
+oauth.consumerSecret=//TODO
+oauth.accessToken=//TODO
+oauth.accessTokenSecret=//TODO
diff --git a/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java b/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java
new file mode 100644
index 0000000000..4696283faa
--- /dev/null
+++ b/Twitter4J/src/test/java/com/baeldung/ApplicationIntegrationTest.java
@@ -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 statuses = Application.getTimeLine();
+ List expectedStatuses = new ArrayList();
+ expectedStatuses.add(tweet);
+ assertEquals(expectedStatuses, statuses);
+ }
+
+ @Test
+ public void givenRecipientNameAndMessage_sendDirectMessage() throws TwitterException {
+ String msg = Application.sendDirectMessage("YOUR_RECCIPIENT_ID", tweet);
+ assertEquals(msg, tweet);
+ }
+
+}
diff --git a/akka-streams/README.md b/akka-streams/README.md
new file mode 100644
index 0000000000..7f2751422b
--- /dev/null
+++ b/akka-streams/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Guide to Akka Streams](http://www.baeldung.com/akka-streams)
diff --git a/akka-streams/pom.xml b/akka-streams/pom.xml
new file mode 100644
index 0000000000..b1471641f7
--- /dev/null
+++ b/akka-streams/pom.xml
@@ -0,0 +1,30 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+ akka-streams
+ akka-streams
+
+
+
+ com.typesafe.akka
+ akka-stream_2.11
+ ${akkastreams.version}
+
+
+ com.typesafe.akka
+ akka-stream-testkit_2.11
+ ${akkastreams.version}
+
+
+
+ 2.5.2
+
+
+
\ No newline at end of file
diff --git a/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java b/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java
new file mode 100644
index 0000000000..8cfae6d52a
--- /dev/null
+++ b/akka-streams/src/main/java/com/baeldung/akkastreams/AverageRepository.java
@@ -0,0 +1,14 @@
+package com.baeldung.akkastreams;
+
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+
+public class AverageRepository {
+ CompletionStage save(Double average) {
+ return CompletableFuture.supplyAsync(() -> {
+ System.out.println("saving average: " + average);
+ return average;
+ });
+ }
+}
diff --git a/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java b/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java
new file mode 100644
index 0000000000..92701e4e37
--- /dev/null
+++ b/akka-streams/src/main/java/com/baeldung/akkastreams/DataImporter.java
@@ -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 parseLine(String line) {
+ String[] fields = line.split(";");
+ return Arrays.stream(fields)
+ .map(Integer::parseInt)
+ .collect(Collectors.toList());
+ }
+
+ private Flow parseContent() {
+ return Flow.of(String.class).mapConcat(this::parseLine);
+ }
+
+ private Flow computeAverage() {
+ return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers ->
+ CompletableFuture.supplyAsync(() -> integers
+ .stream()
+ .mapToDouble(v -> v)
+ .average()
+ .orElse(-1.0)));
+ }
+
+ Flow calculateAverage() {
+ return Flow.of(String.class)
+ .via(parseContent())
+ .via(computeAverage());
+ }
+
+ private Sink> storeAverages() {
+ return Flow.of(Double.class)
+ .mapAsyncUnordered(4, averageRepository::save)
+ .toMat(Sink.ignore(), Keep.right());
+ }
+
+
+ CompletionStage 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();
+ }
+ });
+ }
+
+}
diff --git a/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java b/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java
new file mode 100644
index 0000000000..c47d74eae5
--- /dev/null
+++ b/akka-streams/src/test/java/com/baeldung/akkastreams/DataImporterUnitTest.java
@@ -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 tested = new DataImporter(actorSystem).calculateAverage();
+ String input = "1;9;11;0";
+
+ //when
+ Source 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());
+
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/.gitignore b/algorithms/.gitignore
new file mode 100644
index 0000000000..b83d22266a
--- /dev/null
+++ b/algorithms/.gitignore
@@ -0,0 +1 @@
+/target/
diff --git a/algorithms/README.md b/algorithms/README.md
new file mode 100644
index 0000000000..dc12b528da
--- /dev/null
+++ b/algorithms/README.md
@@ -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)
diff --git a/algorithms/pom.xml b/algorithms/pom.xml
index 0c85a19534..967bcbc706 100644
--- a/algorithms/pom.xml
+++ b/algorithms/pom.xml
@@ -1,44 +1,69 @@
- 4.0.0
- com.baeldung
- algorithms
- 0.0.1-SNAPSHOT
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ 4.0.0
+ com.baeldung
+ algorithms
+ 0.0.1-SNAPSHOT
-
- 4.12
- 3.6.0
- 1.5.0
-
+
+ 1.5.0
+ 1.16.12
+ 3.6.1
+
-
-
- junit
- junit
- ${junit.version}
- test
-
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
- install
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
- ${exec-maven-plugin.version}
-
-
-
-
-
\ No newline at end of file
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+ io.jenetics
+ jenetics
+ 3.7.0
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ cobertura-maven-plugin
+ 2.7
+
+
+
+ com/baeldung/algorithms/dijkstra/*
+
+
+ com/baeldung/algorithms/dijkstra/*
+
+
+
+
+
+
+
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java
new file mode 100644
index 0000000000..86522950ef
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/BinarySearch.java
@@ -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 sortedList, Integer key) {
+ int index = Collections.binarySearch(sortedList, key);
+ return index;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
new file mode 100644
index 0000000000..6ab7dbb4e5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java
@@ -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();
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java
new file mode 100644
index 0000000000..0cb11f5138
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java
@@ -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();
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java
new file mode 100644
index 0000000000..1cf06c04b5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java
@@ -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();
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java
new file mode 100644
index 0000000000..31cb9b577e
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java
@@ -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 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;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java
new file mode 100644
index 0000000000..cb205deacb
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java
@@ -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));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java
new file mode 100644
index 0000000000..1889c4c7f6
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java
@@ -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();
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java b/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java
new file mode 100644
index 0000000000..68177ba7dd
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java
@@ -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();
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
deleted file mode 100644
index b00127a259..0000000000
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Node.java
+++ /dev/null
@@ -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 shortestPath = new LinkedList<>();
-
- private Integer distance = Integer.MAX_VALUE;
-
- private Map 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 getAdjacentNodes() {
- return adjacentNodes;
- }
-
- public void setAdjacentNodes(Map adjacentNodes) {
- this.adjacentNodes = adjacentNodes;
- }
-
- public Integer getDistance() {
- return distance;
- }
-
- public void setDistance(Integer distance) {
- this.distance = distance;
- }
-
- public List getShortestPath() {
- return shortestPath;
- }
-
- public void setShortestPath(LinkedList shortestPath) {
- this.shortestPath = shortestPath;
- }
-
-}
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
similarity index 90%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/City.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
index 77e8652df0..cb5647f4d2 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/City.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
import lombok.Data;
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
similarity index 96%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
index a7dc974e97..bff64fc239 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/SimulatedAnnealing.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
public class SimulatedAnnealing {
diff --git a/core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
similarity index 97%
rename from core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
index 9bf341fbbe..3139b49586 100644
--- a/core-java/src/main/java/com/baeldung/algorithms/annealing/Travel.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java
@@ -1,4 +1,4 @@
-package com.baeldung.algorithms.annealing;
+package com.baeldung.algorithms.ga.annealing;
import java.util.ArrayList;
import java.util.Collections;
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
new file mode 100644
index 0000000000..4ea23b799f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java
@@ -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;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
new file mode 100644
index 0000000000..62e124d3f3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java
@@ -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 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);
+ });
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
new file mode 100644
index 0000000000..2a740777f3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java
@@ -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;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
new file mode 100644
index 0000000000..47677d7d88
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java
@@ -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 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);
+ }
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
new file mode 100644
index 0000000000..e62eab0d57
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java
@@ -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;
+ }
+ }
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
similarity index 95%
rename from algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
index 1d41f46adb..0b01e9b48b 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Dijkstra.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java
@@ -1,57 +1,57 @@
-package com.baeldung.algorithms.dijkstra;
-
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map.Entry;
-import java.util.Set;
-
-public class Dijkstra {
-
- public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
-
- source.setDistance(0);
-
- Set settledNodes = new HashSet<>();
- Set unsettledNodes = new HashSet<>();
- unsettledNodes.add(source);
-
- while (unsettledNodes.size() != 0) {
- Node currentNode = getLowestDistanceNode(unsettledNodes);
- unsettledNodes.remove(currentNode);
- for (Entry adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
- Node adjacentNode = adjacencyPair.getKey();
- Integer edgeWeigh = adjacencyPair.getValue();
-
- if (!settledNodes.contains(adjacentNode)) {
- CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
- unsettledNodes.add(adjacentNode);
- }
- }
- settledNodes.add(currentNode);
- }
- return graph;
- }
-
- private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
- Integer sourceDistance = sourceNode.getDistance();
- if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
- evaluationNode.setDistance(sourceDistance + edgeWeigh);
- LinkedList shortestPath = new LinkedList<>(sourceNode.getShortestPath());
- shortestPath.add(sourceNode);
- evaluationNode.setShortestPath(shortestPath);
- }
- }
-
- private static Node getLowestDistanceNode(Set unsettledNodes) {
- Node lowestDistanceNode = null;
- int lowestDistance = Integer.MAX_VALUE;
- for (Node node : unsettledNodes) {
- int nodeDistance = node.getDistance();
- if (nodeDistance < lowestDistance) {
- lowestDistance = nodeDistance;
- lowestDistanceNode = node;
- }
- }
- return lowestDistanceNode;
- }
-}
+package com.baeldung.algorithms.ga.dijkstra;
+
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Map.Entry;
+import java.util.Set;
+
+public class Dijkstra {
+
+ public static Graph calculateShortestPathFromSource(Graph graph, Node source) {
+
+ source.setDistance(0);
+
+ Set settledNodes = new HashSet<>();
+ Set unsettledNodes = new HashSet<>();
+ unsettledNodes.add(source);
+
+ while (unsettledNodes.size() != 0) {
+ Node currentNode = getLowestDistanceNode(unsettledNodes);
+ unsettledNodes.remove(currentNode);
+ for (Entry adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
+ Node adjacentNode = adjacencyPair.getKey();
+ Integer edgeWeigh = adjacencyPair.getValue();
+
+ if (!settledNodes.contains(adjacentNode)) {
+ CalculateMinimumDistance(adjacentNode, edgeWeigh, currentNode);
+ unsettledNodes.add(adjacentNode);
+ }
+ }
+ settledNodes.add(currentNode);
+ }
+ return graph;
+ }
+
+ private static void CalculateMinimumDistance(Node evaluationNode, Integer edgeWeigh, Node sourceNode) {
+ Integer sourceDistance = sourceNode.getDistance();
+ if (sourceDistance + edgeWeigh < evaluationNode.getDistance()) {
+ evaluationNode.setDistance(sourceDistance + edgeWeigh);
+ LinkedList shortestPath = new LinkedList<>(sourceNode.getShortestPath());
+ shortestPath.add(sourceNode);
+ evaluationNode.setShortestPath(shortestPath);
+ }
+ }
+
+ private static Node getLowestDistanceNode(Set unsettledNodes) {
+ Node lowestDistanceNode = null;
+ int lowestDistance = Integer.MAX_VALUE;
+ for (Node node : unsettledNodes) {
+ int nodeDistance = node.getDistance();
+ if (nodeDistance < lowestDistance) {
+ lowestDistance = nodeDistance;
+ lowestDistanceNode = node;
+ }
+ }
+ return lowestDistanceNode;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
similarity index 84%
rename from algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
rename to algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
index f24d6ae60e..76694ed76e 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/dijkstra/Graph.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java
@@ -1,21 +1,21 @@
-package com.baeldung.algorithms.dijkstra;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class Graph {
-
- private Set nodes = new HashSet<>();
-
- public void addNode(Node nodeA) {
- nodes.add(nodeA);
- }
-
- public Set getNodes() {
- return nodes;
- }
-
- public void setNodes(Set nodes) {
- this.nodes = nodes;
- }
-}
+package com.baeldung.algorithms.ga.dijkstra;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class Graph {
+
+ private Set nodes = new HashSet<>();
+
+ public void addNode(Node nodeA) {
+ nodes.add(nodeA);
+ }
+
+ public Set getNodes() {
+ return nodes;
+ }
+
+ public void setNodes(Set nodes) {
+ this.nodes = nodes;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
new file mode 100644
index 0000000000..ac34bfadd1
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java
@@ -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 shortestPath = new LinkedList<>();
+
+ private Integer distance = Integer.MAX_VALUE;
+
+ private Map 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 getAdjacentNodes() {
+ return adjacentNodes;
+ }
+
+ public void setAdjacentNodes(Map adjacentNodes) {
+ this.adjacentNodes = adjacentNodes;
+ }
+
+ public Integer getDistance() {
+ return distance;
+ }
+
+ public void setDistance(Integer distance) {
+ this.distance = distance;
+ }
+
+ public List getShortestPath() {
+ return shortestPath;
+ }
+
+ public void setShortestPath(LinkedList shortestPath) {
+ this.shortestPath = shortestPath;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
new file mode 100644
index 0000000000..cc99ccf204
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java
@@ -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 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 statistics = EvolutionStatistics.ofNumber();
+
+ Phenotype best = engine.stream()
+ .limit(bySteadyFitness(7))
+ .limit(100)
+ .peek(statistics)
+ .collect(toBestPhenotype());
+
+ System.out.println(statistics);
+ System.out.println(best);
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
new file mode 100644
index 0000000000..e3e06d301a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java
@@ -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, Double> {
+ private KnapsackItem[] items;
+ private double size;
+
+ public KnapsackFF(KnapsackItem[] items, double size) {
+ this.items = items;
+ this.size = size;
+ }
+
+ @Override
+ public Double apply(Genotype gt) {
+ KnapsackItem sum = ((BitChromosome) gt.getChromosome()).ones()
+ .mapToObj(i -> items[i])
+ .collect(KnapsackItem.toSum());
+ return sum.size <= this.size ? sum.value : 0;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
new file mode 100644
index 0000000000..876df0ba25
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java
@@ -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 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]));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
new file mode 100644
index 0000000000..845e11b349
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java
@@ -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 gt) {
+ return gt.getChromosome()
+ .as(BitChromosome.class)
+ .bitCount();
+ }
+
+ public static void main(String[] args) {
+ Factory> gtf = Genotype.of(BitChromosome.of(10, 0.5));
+ System.out.println("Before the evolution:\n" + gtf);
+
+ Engine engine = Engine.builder(SimpleGeneticAlgorithm::eval, gtf)
+ .build();
+
+ Genotype result = engine.stream()
+ .limit(500)
+ .collect(EvolutionResult.toBestGenotype());
+
+ System.out.println("After the evolution:\n" + result);
+
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
new file mode 100644
index 0000000000..55f2f7af0a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java
@@ -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, BitGene, Double> {
+
+ private ISeq records;
+ private double maxPricePerUniqueSong;
+
+ public SpringsteenProblem(ISeq records, double maxPricePerUniqueSong) {
+ this.records = requireNonNull(records);
+ this.maxPricePerUniqueSong = maxPricePerUniqueSong;
+ }
+
+ @Override
+ public Function, 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, 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 engine = Engine.builder(springsteen)
+ .build();
+
+ ISeq 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(", "));
+
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
new file mode 100644
index 0000000000..b49709e7f5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java
@@ -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 songs;
+
+ public SpringsteenRecord(String name, double price, ISeq songs) {
+ this.name = requireNonNull(name);
+ this.price = price;
+ this.songs = requireNonNull(songs);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
new file mode 100644
index 0000000000..db1e11239f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java
@@ -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, EnumGene, Integer> {
+
+ private ISeq basicSet;
+ private int size;
+
+ public SubsetSum(ISeq basicSet, int size) {
+ this.basicSet = requireNonNull(basicSet);
+ this.size = size;
+ }
+
+ @Override
+ public Function, Integer> fitness() {
+ return subset -> Math.abs(subset.stream()
+ .mapToInt(Integer::intValue)
+ .sum());
+ }
+
+ @Override
+ public Codec, EnumGene> 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, Integer> engine = Engine.builder(problem)
+ .minimizing()
+ .maximalPhenotypeAge(5)
+ .alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3))
+ .build();
+
+ Phenotype, Integer> result = engine.stream()
+ .limit(limit.bySteadyFitness(55))
+ .collect(EvolutionResult.toBestPhenotype());
+
+ System.out.print(result);
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
new file mode 100644
index 0000000000..80ede0f8c5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java
@@ -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, 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 statistics = EvolutionStatistics.ofNumber();
+
+ final Phenotype, Double> best = engine.stream()
+ .limit(bySteadyFitness(15))
+ .limit(250)
+ .peek(statistics)
+ .collect(toBestPhenotype());
+
+ System.out.println(statistics);
+ System.out.println(best);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java
new file mode 100644
index 0000000000..77089636c8
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java
@@ -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 startState = hillClimbing.getStackWithValues(blockArr);
+ String goalBlockArr[] = { "A", "B", "C", "D" };
+ Stack goalState = hillClimbing.getStackWithValues(goalBlockArr);
+ try {
+ List solutionSequence = hillClimbing.getRouteWithHillClimbing(startState, goalState);
+ solutionSequence.forEach(HillClimbing::printEachStep);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private static void printEachStep(State state) {
+ List> stackList = state.getState();
+ System.out.println("----------------");
+ stackList.forEach(stack -> {
+ while (!stack.isEmpty()) {
+ System.out.println(stack.pop());
+ }
+ System.out.println(" ");
+ });
+ }
+
+ private Stack getStackWithValues(String[] blocks) {
+ Stack stack = new Stack<>();
+ for (String block : blocks)
+ stack.push(block);
+ return stack;
+ }
+
+ /**
+ * This method prepares path from init state to goal state
+ */
+ public List getRouteWithHillClimbing(Stack initStateStack, Stack goalStateStack) throws Exception {
+ List> initStateStackList = new ArrayList<>();
+ initStateStackList.add(initStateStack);
+ int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
+ State initState = new State(initStateStackList, initStateHeuristics);
+
+ List 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 goalStateStack) {
+ List> 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> listOfStacks, Stack stack, int currentStateHeuristics, Stack goalStateStack) {
+ State tempState;
+ List> 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> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) {
+ State newState = null;
+ Stack 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> currentStackList, String block, int currentStateHeuristics, Stack goalStateStack) {
+
+ Optional 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> currentStackList, int currentStateHeuristics, Stack 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> currentState, Stack 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 stack, List> currentState, Stack 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;
+ }
+
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java
new file mode 100644
index 0000000000..9180b33b5b
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java
@@ -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> state;
+ private int heuristics;
+
+ public State(List> state) {
+ this.state = state;
+ }
+
+ State(List> 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> getState() {
+ return state;
+ }
+
+ public int getHeuristics() {
+ return heuristics;
+ }
+
+ public void setHeuristics(int heuristics) {
+ this.heuristics = heuristics;
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
new file mode 100644
index 0000000000..f428df45d3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java
@@ -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 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;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
new file mode 100644
index 0000000000..d855f775a8
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
@@ -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 getAllPossibleStates() {
+ List possibleStates = new ArrayList<>();
+ List 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 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;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
new file mode 100644
index 0000000000..52707aab55
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java
@@ -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())));
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
new file mode 100644
index 0000000000..8b47fa0fdf
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java
@@ -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 getEmptyPositions() {
+ int size = this.boardValues.length;
+ List 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;
+ }
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
new file mode 100644
index 0000000000..94ead4288d
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java
@@ -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;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
new file mode 100644
index 0000000000..20f9e992b5
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
@@ -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 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 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 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 getChildArray() {
+ return childArray;
+ }
+
+ public void setChildArray(List 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();
+ }));
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
new file mode 100644
index 0000000000..c5543c0ed4
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java
@@ -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);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
new file mode 100644
index 0000000000..8e14afcf7a
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java
@@ -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 getPossibleStates(int noOfBonesInHeap) {
+ return IntStream.rangeClosed(1, 3).boxed()
+ .map(i -> noOfBonesInHeap - i)
+ .filter(newHeapCount -> newHeapCount >= 0)
+ .collect(Collectors.toList());
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
new file mode 100644
index 0000000000..fed4ebed48
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java
@@ -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 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 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 children) {
+ Comparator byScoreComparator = Comparator.comparing(Node::getScore);
+
+ return children.stream()
+ .max(isMaxPlayer ? byScoreComparator : byScoreComparator.reversed())
+ .orElseThrow(NoSuchElementException::new);
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java
new file mode 100644
index 0000000000..4ceef0073d
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java
@@ -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 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 getChildren() {
+ return children;
+ }
+
+ void addChild(Node newNode) {
+ children.add(newNode);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java
new file mode 100644
index 0000000000..34c56cdd58
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java
@@ -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;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java
new file mode 100644
index 0000000000..752e659fa3
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BigIntegerPrimeChecker.java
@@ -0,0 +1,13 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.math.BigInteger;
+
+public class BigIntegerPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Long number) {
+ BigInteger bigInt = BigInteger.valueOf(number);
+ return bigInt.isProbablePrime(100);
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java
new file mode 100644
index 0000000000..47ffb3e224
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/BruteForcePrimeChecker.java
@@ -0,0 +1,16 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+public class BruteForcePrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+
+ return number > 2 ? IntStream.range(2, number)
+ .noneMatch(n -> (number % n == 0)) : false;
+ }
+
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java
new file mode 100644
index 0000000000..06ae4acc7f
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/OptimisedPrimeChecker.java
@@ -0,0 +1,15 @@
+package com.baeldung.algorithms.primechecker;
+
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+public class OptimisedPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+ return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number))
+ .noneMatch(n -> (number % n == 0)) : false;
+ }
+
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java
new file mode 100644
index 0000000000..5f7a15a939
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimeChecker.java
@@ -0,0 +1,6 @@
+package com.baeldung.algorithms.primechecker;
+
+public interface PrimeChecker {
+
+ public boolean isPrime( T number );
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java
new file mode 100644
index 0000000000..08b095cb79
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/primechecker/PrimesPrimeChecker.java
@@ -0,0 +1,12 @@
+package com.baeldung.algorithms.primechecker;
+
+import org.apache.commons.math3.primes.Primes;
+
+public class PrimesPrimeChecker implements PrimeChecker{
+
+ @Override
+ public boolean isPrime(Integer number) {
+ return Primes.isPrime(number);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/Item.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java
diff --git a/core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java b/algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/algorithms/slope_one/User.java
rename to algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java
diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
new file mode 100644
index 0000000000..b0218ae23e
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
@@ -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());
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
new file mode 100644
index 0000000000..fa8ecdee77
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
@@ -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"));
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/BinarySearchTest.java b/algorithms/src/test/java/algorithms/BinarySearchTest.java
new file mode 100644
index 0000000000..3611ec8e49
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/BinarySearchTest.java
@@ -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 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));
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
new file mode 100644
index 0000000000..68386278fc
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
@@ -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 shortestPathForNodeB = Arrays.asList(nodeA);
+ List shortestPathForNodeC = Arrays.asList(nodeA);
+ List shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
+ List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
+ List 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;
+ }
+ }
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java b/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
deleted file mode 100644
index 07606bde4b..0000000000
--- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmTest.java
+++ /dev/null
@@ -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 shortestPathForNodeB = Arrays.asList(nodeA);
- List shortestPathForNodeC = Arrays.asList(nodeA);
- List shortestPathForNodeD = Arrays.asList(nodeA, nodeB);
- List shortestPathForNodeE = Arrays.asList(nodeA, nodeB, nodeD);
- List 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;
- }
- }
- }
-}
diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java
new file mode 100644
index 0000000000..666adbb180
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java
@@ -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 initStack;
+ private Stack 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 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> 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());
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/test/java/algorithms/MCTSTest.java b/algorithms/src/test/java/algorithms/MCTSTest.java
new file mode 100644
index 0000000000..f969c26311
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/MCTSTest.java
@@ -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 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);
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
new file mode 100644
index 0000000000..99e962773f
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -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);
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
new file mode 100644
index 0000000000..6ee129ece9
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
@@ -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);
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java b/algorithms/src/test/java/algorithms/mcts/MCTSTest.java
new file mode 100644
index 0000000000..375f66ab6f
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/mcts/MCTSTest.java
@@ -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 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);
+ }
+
+}
diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java b/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
new file mode 100644
index 0000000000..b29c16386c
--- /dev/null
+++ b/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java
@@ -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);
+ }
+}
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java
new file mode 100644
index 0000000000..9203131397
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/primechecker/PrimeCheckerUnitTest.java
@@ -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));
+ }
+
+}
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index e88e441b3e..df6f9d44b7 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -1,7 +1,7 @@
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml
index a365f35c11..eb827b2ea5 100644
--- a/annotations/annotation-user/pom.xml
+++ b/annotations/annotation-user/pom.xml
@@ -1,7 +1,6 @@
-
+4.0.0
@@ -13,11 +12,6 @@
annotation-user
-
- 4.12
- 3.6.0
-
-
@@ -26,31 +20,6 @@
${project.parent.version}
-
- junit
- junit
- ${junit.version}
- test
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
deleted file mode 100644
index 8d01f8a517..0000000000
--- a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
+++ /dev/null
@@ -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());
-
- }
-
-}
diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java
new file mode 100644
index 0000000000..d5f758089a
--- /dev/null
+++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderUnitTest.java
@@ -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());
+
+ }
+
+}
diff --git a/apache-bval/README.md b/apache-bval/README.md
new file mode 100644
index 0000000000..80ea149993
--- /dev/null
+++ b/apache-bval/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Intro to Apache BVal](http://www.baeldung.com/apache-bval)
diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml
new file mode 100644
index 0000000000..1cc0a33702
--- /dev/null
+++ b/apache-bval/pom.xml
@@ -0,0 +1,34 @@
+
+ 4.0.0
+ apache-bval
+ apache-bval
+ 0.0.1-SNAPSHOT
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ org.apache.bval
+ bval-jsr
+ ${bval.version}
+
+
+ javax.validation
+ validation-api
+ 1.1.0.Final
+
+
+ org.apache.bval
+ bval-extras
+ ${bval.version}
+
+
+
+
+ 1.1.2
+
+
\ No newline at end of file
diff --git a/apache-bval/src/main/java/com/baeldung/model/User.java b/apache-bval/src/main/java/com/baeldung/model/User.java
new file mode 100644
index 0000000000..477136ddb4
--- /dev/null
+++ b/apache-bval/src/main/java/com/baeldung/model/User.java
@@ -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;
+ }
+
+}
diff --git a/apache-bval/src/main/java/com/baeldung/validation/Password.java b/apache-bval/src/main/java/com/baeldung/validation/Password.java
new file mode 100644
index 0000000000..4ae06b2fb0
--- /dev/null
+++ b/apache-bval/src/main/java/com/baeldung/validation/Password.java
@@ -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;
+}
diff --git a/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java
new file mode 100644
index 0000000000..19038d04d5
--- /dev/null
+++ b/apache-bval/src/main/java/com/baeldung/validation/PasswordValidator.java
@@ -0,0 +1,35 @@
+package com.baeldung.validation;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+public class PasswordValidator implements ConstraintValidator {
+
+ 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;
+ }
+
+}
diff --git a/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java b/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java
new file mode 100644
index 0000000000..ecbcd100da
--- /dev/null
+++ b/apache-bval/src/test/java/com/baeldung/validation/ValidationIntegrationTest.java
@@ -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> 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> 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> 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> 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> 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> violations = validator.validateProperty(user, "password");
+ assertEquals("size is not 0", 0, violations.size());
+ }
+
+ @AfterClass
+ public static void close() {
+ if (validatorFactory != null) {
+ validatorFactory.close();
+ }
+ }
+}
diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml
index b436b03305..6d8aa85679 100644
--- a/apache-cxf/cxf-aegis/pom.xml
+++ b/apache-cxf/cxf-aegis/pom.xml
@@ -8,7 +8,7 @@
0.0.1-SNAPSHOT
- 3.1.8
+ 3.1.8
diff --git a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java
new file mode 100644
index 0000000000..b28b987cfa
--- /dev/null
+++ b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java
@@ -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 rootClasses = new HashSet();
+ rootClasses.add(CourseRepo.class);
+ context.setRootClasses(rootClasses);
+ Map, 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 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 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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java b/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java
deleted file mode 100644
index 559de037a9..0000000000
--- a/apache-cxf/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungTest.java
+++ /dev/null
@@ -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 rootClasses = new HashSet();
- rootClasses.add(CourseRepo.class);
- context.setRootClasses(rootClasses);
- Map, 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 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 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;
- }
-}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
index 6e0ceaba7e..1b9ba22230 100644
--- a/apache-cxf/cxf-introduction/pom.xml
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -4,18 +4,18 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0cxf-introduction
-
+
com.baeldungapache-cxf0.0.1-SNAPSHOT
-
+
3.1.8
- 2.19.1
+ 2.19.1
-
+
@@ -36,7 +36,7 @@
-
+
org.apache.cxf
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
index c3095be5a5..981e0ef7aa 100644
--- a/apache-cxf/cxf-jaxrs-implementation/pom.xml
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -4,20 +4,20 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0cxf-jaxrs-implementation
-
+
com.baeldungapache-cxf0.0.1-SNAPSHOT
-
+
UTF-83.1.84.5.2
- 2.19.1
+ 2.19.1
-
+
@@ -38,7 +38,7 @@
-
+
org.apache.cxf
@@ -54,6 +54,12 @@
org.apache.httpcomponentshttpclient${httpclient.version}
+
+
+ commons-logging
+ commons-logging
+
+
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
index 79a7650ced..2cd700680b 100644
--- a/apache-cxf/cxf-spring/pom.xml
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -8,7 +8,7 @@
apache-cxf0.0.1-SNAPSHOT
-
+
org.apache.cxf
@@ -24,6 +24,12 @@
org.springframeworkspring-context${spring.version}
+
+
+ commons-logging
+ commons-logging
+
+ org.springframework
@@ -36,7 +42,7 @@
${javax.servlet-api.version}
-
+
@@ -57,7 +63,7 @@
-
+
live
@@ -96,7 +102,7 @@
-
+
maven-surefire-plugin${surefire.version}
@@ -117,17 +123,17 @@
-
+
-
+
3.1.84.3.4.RELEASE3.1.0
-
- 2.6
+
+ 2.62.19.1
- 1.6.1
+ 1.6.1
-
+
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 6849452908..3bc3853f2b 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -6,6 +6,12 @@
0.0.1-SNAPSHOTpom
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
cxf-introductioncxf-spring
@@ -14,33 +20,13 @@
- 4.12
- 3.6.01.5.0
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
install
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
- org.codehaus.mojoexec-maven-plugin
diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml
index 6f89497a7d..f7439dc244 100644
--- a/apache-fop/pom.xml
+++ b/apache-fop/pom.xml
@@ -7,64 +7,14 @@
apache-fop
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
-
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
-
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
-
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
-
org.apache.xmlgraphicsfop
@@ -78,6 +28,10 @@
org.apache.avalon.frameworkavalon-framework-impl
+
+ commons-logging
+ commons-logging
+
@@ -90,6 +44,12 @@
avalon-frameworkavalon-framework-impl${avalon-framework.version}
+
+
+ commons-logging
+ commons-logging
+
+
@@ -101,9 +61,7 @@
org.dbdocletherold
- 6.1.0
- system
- ${basedir}/src/test/resources/jars/herold.jar
+ 8.0.4
@@ -122,33 +80,6 @@
true
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.7
- 1.7
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*IntegrationTest.java
- **/*LiveTest.java
-
-
-
-
-
-
@@ -192,19 +123,6 @@
4.38.0.2r938
-
- 1.7.21
- 1.1.7
-
-
- 1.3
- 4.12
- 1.10.19
-
-
- 3.6.0
- 2.19.1
-
\ No newline at end of file
diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml
index 62d0ea5037..ec0dc2469a 100644
--- a/apache-fop/src/main/resources/logback.xml
+++ b/apache-fop/src/main/resources/logback.xml
@@ -1,5 +1,5 @@
+
-
web - %date [%thread] %-5level %logger{36} - %message%n
@@ -7,10 +7,13 @@
-
+
+
+
+
+
-
\ No newline at end of file
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
index 99487c8fdf..5e2da6fd1e 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
@@ -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);
}
}
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
index 9e71cd9c16..8496222394 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
@@ -10,6 +10,7 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.transform.Result;
@@ -25,19 +26,15 @@ import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;
import org.dbdoclet.trafo.TrafoScriptManager;
-import org.dbdoclet.trafo.html.docbook.DocBookTransformer;
+import org.dbdoclet.trafo.html.docbook.HtmlDocBookTrafo;
import org.dbdoclet.trafo.script.Script;
import org.junit.Test;
import org.w3c.dom.Document;
public class ApacheFOPHeroldLiveTest {
- private String[] inputUrls = {// @formatter:off
- "http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
- "http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
- "http://www.baeldung.com/2011/10/31/securing-a-restful-web-service-with-spring-security-3-1-part-3/",
- "http://www.baeldung.com/spring-security-basic-authentication",
- "http://www.baeldung.com/spring-security-digest-authentication",
- "http://www.baeldung.com/2011/11/20/basic-and-digest-authentication-for-a-restful-service-with-spring-security-3-1/",
+ private final String[] inputUrls = {// @formatter:off
+ // "http://www.baeldung.com/spring-security-basic-authentication",
+ "http://www.baeldung.com/spring-security-digest-authentication"
//"http://www.baeldung.com/spring-httpmessageconverter-rest",
//"http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/",
//"http://www.baeldung.com/2011/11/13/rest-service-discoverability-with-spring-part-5/",
@@ -49,10 +46,10 @@ public class ApacheFOPHeroldLiveTest {
//"http://www.baeldung.com/2013/01/18/testing-rest-with-multiple-mime-types/"
}; // @formatter:on
- private String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
- private String output_file = "src/test/resources/final_output.pdf";
- private String xmlInput = "src/test/resources/input.xml";
- private String xmlOutput = "src/test/resources/output.xml";
+ private final String style_file = "src/test/resources/docbook-xsl/fo/docbook.xsl";
+ private final String output_file = "src/test/resources/final_output.pdf";
+ private final String xmlInput = "src/test/resources/input.xml";
+ private final String xmlOutput = "src/test/resources/output.xml";
// tests
@@ -75,10 +72,11 @@ public class ApacheFOPHeroldLiveTest {
final TrafoScriptManager mgr = new TrafoScriptManager();
final File profileFile = new File("src/test/resources/default.her");
script = mgr.parseScript(profileFile);
- final DocBookTransformer transformer = new DocBookTransformer();
- transformer.setScript(script);
+ final HtmlDocBookTrafo transformer = new HtmlDocBookTrafo();
+ transformer.setInputStream(getInputStream(input));
+ transformer.setOutputStream(new FileOutputStream(xmlInput, append));
- transformer.convert(getInputStream(input), new FileOutputStream(xmlInput, append));
+ transformer.transform(script);
}
private Document fromXMLFileToFO() throws Exception {
@@ -112,7 +110,9 @@ public class ApacheFOPHeroldLiveTest {
private InputStream getInputStream(final String input) throws IOException {
final URL url = new URL(input);
- return url.openStream();
+ final HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
+ httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
+ return httpcon.getInputStream();
}
private void fixXML(final String input, final String output) throws IOException {
@@ -127,7 +127,7 @@ public class ApacheFOPHeroldLiveTest {
if (line.contains("info>")) {
writer.write(line.replace("info>", "section>"));
- } else if (!((line.startsWith(" 4)) {
+ } else if (!((line.startsWith(" 4))) {
writer.write(line.replaceAll("xml:id=\"", "xml:id=\"" + count));
}
writer.write("\n");
diff --git a/apache-fop/src/test/resources/jars/herold.jar b/apache-fop/src/test/resources/jars/herold.jar
deleted file mode 100644
index ef5d052f36..0000000000
Binary files a/apache-fop/src/test/resources/jars/herold.jar and /dev/null differ
diff --git a/apache-poi/.gitignore b/apache-poi/.gitignore
index e05054868c..9552c1e63d 100644
--- a/apache-poi/.gitignore
+++ b/apache-poi/.gitignore
@@ -1 +1,3 @@
*.docx
+temp.xls
+temp.xlsx
diff --git a/apache-poi/README.md b/apache-poi/README.md
index cef6810c97..10fe8ba2e7 100644
--- a/apache-poi/README.md
+++ b/apache-poi/README.md
@@ -1,2 +1,3 @@
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
+- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index d94b2e2ad1..22c0cd156a 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -5,37 +5,33 @@
apache-poi0.0.1-SNAPSHOT
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
- 3.6.0
- 4.123.15
+ 1.0.6
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
-
-
-
-
- junit
- junit
- ${junit.version}
- test
- org.apache.poipoi-ooxml${poi.version}
+
+ org.jxls
+ jxls-jexcel
+ ${jexcel.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
diff --git a/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java
new file mode 100644
index 0000000000..4ad3fc766c
--- /dev/null
+++ b/apache-poi/src/main/java/com/baeldung/jexcel/JExcelHelper.java
@@ -0,0 +1,74 @@
+package com.baeldung.jexcel;
+
+import jxl.*;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.List;
+import jxl.read.biff.BiffException;
+import java.io.File;
+import java.io.IOException;
+import jxl.write.*;
+import jxl.write.Number;
+import jxl.format.Colour;
+
+public class JExcelHelper {
+
+ public Map> readJExcel(String fileLocation) throws IOException, BiffException {
+ Map> data = new HashMap<>();
+
+ Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
+ Sheet sheet = workbook.getSheet(0);
+ int rows = sheet.getRows();
+ int columns = sheet.getColumns();
+
+ for (int i = 0; i < rows; i++) {
+ data.put(i, new ArrayList());
+ for (int j = 0; j < columns; j++) {
+ data.get(i).add(sheet.getCell(j, i).getContents());
+ }
+ }
+ return data;
+ }
+
+ public void writeJExcel() throws IOException, WriteException {
+ WritableWorkbook workbook = null;
+ try {
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
+
+ workbook = Workbook.createWorkbook(new File(fileLocation));
+
+ WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
+
+ WritableCellFormat headerFormat = new WritableCellFormat();
+ WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
+ headerFormat.setFont(font);
+ headerFormat.setBackground(Colour.LIGHT_BLUE);
+ headerFormat.setWrap(true);
+ Label headerLabel = new Label(0, 0, "Name", headerFormat);
+ sheet.setColumnView(0, 60);
+ sheet.addCell(headerLabel);
+
+ headerLabel = new Label(1, 0, "Age", headerFormat);
+ sheet.setColumnView(0, 40);
+ sheet.addCell(headerLabel);
+
+ WritableCellFormat cellFormat = new WritableCellFormat();
+ cellFormat.setWrap(true);
+
+ Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
+ sheet.addCell(cellLabel);
+ Number cellNumber = new Number(1, 2, 20, cellFormat);
+ sheet.addCell(cellNumber);
+
+ workbook.write();
+ } finally {
+ if (workbook != null) {
+ workbook.close();
+ }
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java
new file mode 100644
index 0000000000..b6b0cbef20
--- /dev/null
+++ b/apache-poi/src/main/java/com/baeldung/poi/excel/ExcelPOIHelper.java
@@ -0,0 +1,128 @@
+package com.baeldung.poi.excel;
+
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellType;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+import org.apache.poi.xssf.usermodel.XSSFFont;
+import org.apache.poi.ss.usermodel.DateUtil;
+import org.apache.poi.ss.usermodel.FillPatternType;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ExcelPOIHelper {
+
+ public Map> readExcel(String fileLocation) throws IOException {
+
+ Map> data = new HashMap<>();
+ FileInputStream file = new FileInputStream(new File(fileLocation));
+ Workbook workbook = new XSSFWorkbook(file);
+ Sheet sheet = workbook.getSheetAt(0);
+ int i = 0;
+ for (Row row : sheet) {
+ data.put(i, new ArrayList());
+ for (Cell cell : row) {
+ switch (cell.getCellTypeEnum()) {
+ case STRING:
+ data.get(i)
+ .add(cell.getRichStringCellValue()
+ .getString());
+ break;
+ case NUMERIC:
+ if (DateUtil.isCellDateFormatted(cell)) {
+ data.get(i)
+ .add(cell.getDateCellValue() + "");
+ } else {
+ data.get(i)
+ .add((int)cell.getNumericCellValue() + "");
+ }
+ break;
+ case BOOLEAN:
+ data.get(i)
+ .add(cell.getBooleanCellValue() + "");
+ break;
+ case FORMULA:
+ data.get(i)
+ .add(cell.getCellFormula() + "");
+ break;
+ default:
+ data.get(i)
+ .add(" ");
+ }
+ }
+ i++;
+ }
+ if (workbook != null){
+ workbook.close();
+ }
+ return data;
+ }
+
+ public void writeExcel() throws IOException {
+ Workbook workbook = new XSSFWorkbook();
+
+ try {
+ Sheet sheet = workbook.createSheet("Persons");
+ sheet.setColumnWidth(0, 6000);
+ sheet.setColumnWidth(1, 4000);
+
+ Row header = sheet.createRow(0);
+
+ CellStyle headerStyle = workbook.createCellStyle();
+
+ headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
+ headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
+
+ XSSFFont font = ((XSSFWorkbook) workbook).createFont();
+ font.setFontName("Arial");
+ font.setFontHeightInPoints((short) 16);
+ font.setBold(true);
+ headerStyle.setFont(font);
+
+ Cell headerCell = header.createCell(0);
+ headerCell.setCellValue("Name");
+ headerCell.setCellStyle(headerStyle);
+
+ headerCell = header.createCell(1);
+ headerCell.setCellValue("Age");
+ headerCell.setCellStyle(headerStyle);
+
+ CellStyle style = workbook.createCellStyle();
+ style.setWrapText(true);
+
+ Row row = sheet.createRow(2);
+ Cell cell = row.createCell(0);
+ cell.setCellValue("John Smith");
+ cell.setCellStyle(style);
+
+ cell = row.createCell(1);
+ cell.setCellValue(20);
+ cell.setCellStyle(style);
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
+
+ FileOutputStream outputStream = new FileOutputStream(fileLocation);
+ workbook.write(outputStream);
+ } finally {
+ if (workbook != null) {
+
+ workbook.close();
+
+ }
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
new file mode 100644
index 0000000000..41efd9d9ba
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/jexcel/JExcelIntegrationTest.java
@@ -0,0 +1,64 @@
+package com.baeldung.jexcel;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import jxl.read.biff.BiffException;
+import java.util.Map;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.jexcel.JExcelHelper;
+
+import jxl.write.WriteException;
+import jxl.read.biff.BiffException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.After;
+
+public class JExcelIntegrationTest {
+
+ private JExcelHelper jExcelHelper;
+ private static String FILE_NAME = "temp.xls";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException, WriteException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ jExcelHelper = new JExcelHelper();
+ jExcelHelper.writeJExcel();
+
+ }
+
+ @Test
+ public void whenParsingJExcelFile_thenCorrect() throws IOException, BiffException {
+ Map> data = jExcelHelper.readJExcel(fileLocation);
+
+ assertEquals("Name", data.get(0)
+ .get(0));
+ assertEquals("Age", data.get(0)
+ .get(1));
+
+ assertEquals("John Smith", data.get(2)
+ .get(0));
+ assertEquals("20", data.get(2)
+ .get(1));
+ }
+
+ @After
+ public void cleanup(){
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
new file mode 100644
index 0000000000..5d7ccb9b94
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/poi/excel/ExcelIntegrationTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.poi.excel;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import jxl.read.biff.BiffException;
+import java.util.Map;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.poi.excel.ExcelPOIHelper;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.After;
+
+public class ExcelIntegrationTest {
+
+ private ExcelPOIHelper excelPOIHelper;
+ private static String FILE_NAME = "temp.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ excelPOIHelper = new ExcelPOIHelper();
+ excelPOIHelper.writeExcel();
+
+ }
+
+ @Test
+ public void whenParsingPOIExcelFile_thenCorrect() throws IOException {
+ Map> data = excelPOIHelper.readExcel(fileLocation);
+
+ assertEquals("Name", data.get(0)
+ .get(0));
+ assertEquals("Age", data.get(0)
+ .get(1));
+
+ assertEquals("John Smith", data.get(1)
+ .get(0));
+ assertEquals("20", data.get(1)
+ .get(1));
+ }
+
+ @After
+ public void cleanup(){
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java
new file mode 100644
index 0000000000..98b5c5b520
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/poi/word/WordIntegrationTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.poi.word;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+
+import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.apache.poi.xwpf.usermodel.XWPFParagraph;
+import org.apache.poi.xwpf.usermodel.XWPFRun;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class WordIntegrationTest {
+ static WordDocument wordDocument;
+
+ @BeforeClass
+ public static void generateMSWordFile() throws Exception {
+ WordIntegrationTest.wordDocument = new WordDocument();
+ wordDocument.handleSimpleDoc();
+ }
+
+ @Test
+ public void whenParsingOutputDocument_thenCorrect() throws Exception {
+ Path msWordPath = Paths.get(WordDocument.output);
+ XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
+ List paragraphs = document.getParagraphs();
+ document.close();
+
+ XWPFParagraph title = paragraphs.get(0);
+ XWPFRun titleRun = title.getRuns().get(0);
+ assertEquals("Build Your REST API with Spring", title.getText());
+ assertEquals("009933", titleRun.getColor());
+ assertTrue(titleRun.isBold());
+ assertEquals("Courier", titleRun.getFontFamily());
+ assertEquals(20, titleRun.getFontSize());
+
+ assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
+ assertEquals("What makes a good API?", paragraphs.get(3).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
+ assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
+ }
+}
diff --git a/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java b/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
deleted file mode 100644
index bc1011a03a..0000000000
--- a/apache-poi/src/test/java/com/baeldung/poi/word/WordTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.baeldung.poi.word;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-
-import org.apache.poi.xwpf.usermodel.XWPFDocument;
-import org.apache.poi.xwpf.usermodel.XWPFParagraph;
-import org.apache.poi.xwpf.usermodel.XWPFRun;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class WordTest {
- static WordDocument wordDocument;
-
- @BeforeClass
- public static void generateMSWordFile() throws Exception {
- WordTest.wordDocument = new WordDocument();
- wordDocument.handleSimpleDoc();
- }
-
- @Test
- public void whenParsingOutputDocument_thenCorrect() throws Exception {
- Path msWordPath = Paths.get(WordDocument.output);
- XWPFDocument document = new XWPFDocument(Files.newInputStream(msWordPath));
- List paragraphs = document.getParagraphs();
- document.close();
-
- XWPFParagraph title = paragraphs.get(0);
- XWPFRun titleRun = title.getRuns().get(0);
- assertEquals("Build Your REST API with Spring", title.getText());
- assertEquals("009933", titleRun.getColor());
- assertTrue(titleRun.isBold());
- assertEquals("Courier", titleRun.getFontFamily());
- assertEquals(20, titleRun.getFontSize());
-
- assertEquals("from HTTP fundamentals to API Mastery", paragraphs.get(1).getText());
- assertEquals("What makes a good API?", paragraphs.get(3).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph1), paragraphs.get(4).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph2), paragraphs.get(5).getText());
- assertEquals(wordDocument.convertTextFileToString(WordDocument.paragraph3), paragraphs.get(6).getText());
- }
-}
diff --git a/apache-shiro/.gitignore b/apache-shiro/.gitignore
new file mode 100644
index 0000000000..020cda4898
--- /dev/null
+++ b/apache-shiro/.gitignore
@@ -0,0 +1,4 @@
+
+/.idea/
+/target/
+/apache-shiro.iml
\ No newline at end of file
diff --git a/apache-shiro/README.md b/apache-shiro/README.md
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml
new file mode 100644
index 0000000000..97ed872a26
--- /dev/null
+++ b/apache-shiro/pom.xml
@@ -0,0 +1,65 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ apache-shiro
+ 1.0-SNAPSHOT
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 1.4.0
+ 1.2.17
+ 1.7.25
+
+
+
+
+ org.apache.shiro
+ shiro-core
+ ${apache-shiro-core-version}
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${slf4j-version}
+ runtime
+
+
+ org.slf4j
+ slf4j-log4j12
+ ${slf4j-version}
+ runtime
+
+
+ log4j
+ log4j
+ ${log4j-version}
+ runtime
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.6.2
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-shiro/src/main/java/com/baeldung/Main.java b/apache-shiro/src/main/java/com/baeldung/Main.java
new file mode 100644
index 0000000000..5e341f251b
--- /dev/null
+++ b/apache-shiro/src/main/java/com/baeldung/Main.java
@@ -0,0 +1,85 @@
+package com.baeldung;
+
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.authc.*;
+import org.apache.shiro.mgt.DefaultSecurityManager;
+import org.apache.shiro.mgt.SecurityManager;
+import org.apache.shiro.realm.Realm;
+import org.apache.shiro.realm.text.IniRealm;
+import org.apache.shiro.session.Session;
+import org.apache.shiro.subject.Subject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Main {
+
+ private static final transient Logger log = LoggerFactory.getLogger(Main.class);
+
+ public static void main(String[] args) {
+
+ Realm realm = new MyCustomRealm();
+ SecurityManager securityManager = new DefaultSecurityManager(realm);
+
+ SecurityUtils.setSecurityManager(securityManager);
+ Subject currentUser = SecurityUtils.getSubject();
+
+ if (!currentUser.isAuthenticated()) {
+ UsernamePasswordToken token
+ = new UsernamePasswordToken("user", "password");
+ token.setRememberMe(true);
+ try {
+ currentUser.login(token);
+ } catch (UnknownAccountException uae) {
+ log.error("Username Not Found!", uae);
+ } catch (IncorrectCredentialsException ice) {
+ log.error("Invalid Credentials!", ice);
+ } catch (LockedAccountException lae) {
+ log.error("Your Account is Locked!", lae);
+ } catch (AuthenticationException ae) {
+ log.error("Unexpected Error!", ae);
+ }
+ }
+
+ log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
+
+ if (currentUser.hasRole("admin")) {
+ log.info("Welcome Admin");
+ } else if(currentUser.hasRole("editor")) {
+ log.info("Welcome, Editor!");
+ } else if(currentUser.hasRole("author")) {
+ log.info("Welcome, Author");
+ } else {
+ log.info("Welcome, Guest");
+ }
+
+ if(currentUser.isPermitted("articles:compose")) {
+ log.info("You can compose an article");
+ } else {
+ log.info("You are not permitted to compose an article!");
+ }
+
+ if(currentUser.isPermitted("articles:save")) {
+ log.info("You can save articles");
+ } else {
+ log.info("You can not save articles");
+ }
+
+ if(currentUser.isPermitted("articles:publish")) {
+ log.info("You can publish articles");
+ } else {
+ log.info("You can not publish articles");
+ }
+
+ Session session = currentUser.getSession();
+ session.setAttribute("key", "value");
+ String value = (String) session.getAttribute("key");
+ if (value.equals("value")) {
+ log.info("Retrieved the correct value! [" + value + "]");
+ }
+
+ currentUser.logout();
+
+ System.exit(0);
+ }
+
+}
diff --git a/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java
new file mode 100644
index 0000000000..8d792c76a5
--- /dev/null
+++ b/apache-shiro/src/main/java/com/baeldung/MyCustomRealm.java
@@ -0,0 +1,102 @@
+package com.baeldung;
+
+import org.apache.shiro.authc.*;
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.authz.SimpleAuthorizationInfo;
+import org.apache.shiro.realm.jdbc.JdbcRealm;
+import org.apache.shiro.subject.PrincipalCollection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.*;
+
+public class MyCustomRealm extends JdbcRealm {
+
+ private Map credentials = new HashMap<>();
+ private Map> roles = new HashMap<>();
+ private Map> perm = new HashMap<>();
+
+ {
+ credentials.put("user", "password");
+ credentials.put("user2", "password2");
+ credentials.put("user3", "password3");
+
+ roles.put("user", new HashSet<>(Arrays.asList("admin")));
+ roles.put("user2", new HashSet<>(Arrays.asList("editor")));
+ roles.put("user3", new HashSet<>(Arrays.asList("author")));
+
+ perm.put("admin", new HashSet<>(Arrays.asList("*")));
+ perm.put("editor", new HashSet<>(Arrays.asList("articles:*")));
+ perm.put("author",
+ new HashSet<>(Arrays.asList("articles:compose",
+ "articles:save")));
+
+ }
+
+ @Override
+ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
+ throws AuthenticationException {
+
+ UsernamePasswordToken uToken = (UsernamePasswordToken) token;
+
+ if(uToken.getUsername() == null
+ || uToken.getUsername().isEmpty()
+ || !credentials.containsKey(uToken.getUsername())
+ ) {
+ throw new UnknownAccountException("username not found!");
+ }
+
+
+ return new SimpleAuthenticationInfo(
+ uToken.getUsername(), credentials.get(uToken.getUsername()),
+ getName());
+ }
+
+ @Override
+ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+ Set roleNames = new HashSet<>();
+ Set permissions = new HashSet<>();
+
+ principals.forEach(p -> {
+ try {
+ Set roles = getRoleNamesForUser(null, (String) p);
+ roleNames.addAll(roles);
+ permissions.addAll(getPermissions(null, null,roles));
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ });
+
+ SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
+ info.setStringPermissions(permissions);
+ return info;
+ }
+
+ @Override
+ protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException {
+ if(!roles.containsKey(username)) {
+ throw new SQLException("username not found!");
+ }
+
+ return roles.get(username);
+ }
+
+ @Override
+ protected Set getPermissions(Connection conn, String username, Collection roleNames) throws SQLException {
+ for (String role : roleNames) {
+ if (!perm.containsKey(role)) {
+ throw new SQLException("role not found!");
+ }
+ }
+
+ Set finalSet = new HashSet<>();
+ for (String role : roleNames) {
+ finalSet.addAll(perm.get(role));
+ }
+
+ return finalSet;
+ }
+
+}
diff --git a/apache-shiro/src/main/resources/log4j.properties b/apache-shiro/src/main/resources/log4j.properties
new file mode 100644
index 0000000000..897bf08221
--- /dev/null
+++ b/apache-shiro/src/main/resources/log4j.properties
@@ -0,0 +1,12 @@
+log4j.rootLogger=INFO, stdout
+
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
+
+log4j.logger.org.apache=WARN
+
+log4j.logger.org.apache.shiro=INFO
+
+log4j.logger.org.apache.shiro.util.ThreadContext=WARN
+log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
\ No newline at end of file
diff --git a/apache-shiro/src/main/resources/shiro.ini b/apache-shiro/src/main/resources/shiro.ini
new file mode 100644
index 0000000000..0bb7567d1e
--- /dev/null
+++ b/apache-shiro/src/main/resources/shiro.ini
@@ -0,0 +1,9 @@
+[users]
+user = password,admin
+user2 = password2,editor
+user3 = password3,author
+
+[roles]
+admin = *
+editor = articles:*
+author = articles:compose,articles:save
\ No newline at end of file
diff --git a/apache-solrj/README.md b/apache-solrj/README.md
new file mode 100644
index 0000000000..7a32becb64
--- /dev/null
+++ b/apache-solrj/README.md
@@ -0,0 +1,4 @@
+## Apache Solrj Tutorials Project
+
+### Relevant Articles
+- [Guide to Solr in Java with Apache Solrj](http://www.baeldung.com/apache-solrj)
diff --git a/apache-solrj/pom.xml b/apache-solrj/pom.xml
new file mode 100644
index 0000000000..ea696b024b
--- /dev/null
+++ b/apache-solrj/pom.xml
@@ -0,0 +1,23 @@
+
+ 4.0.0
+ com.baeldung
+ apache-solrj
+ 0.0.1-SNAPSHOT
+ jar
+ apache-solrj
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.solr
+ solr-solrj
+ 6.4.0
+
+
+
\ No newline at end of file
diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java b/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java
new file mode 100644
index 0000000000..14eea8f2f9
--- /dev/null
+++ b/apache-solrj/src/main/java/com/baeldung/solrjava/ProductBean.java
@@ -0,0 +1,44 @@
+package com.baeldung.solrjava;
+
+import org.apache.solr.client.solrj.beans.Field;
+
+public class ProductBean {
+
+ String id;
+ String name;
+ String price;
+
+ public ProductBean(String id, String name, String price) {
+ super();
+ this.id = id;
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ @Field("id")
+ protected void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Field("name")
+ protected void setName(String name) {
+ this.name = name;
+ }
+
+ public String getPrice() {
+ return price;
+ }
+
+ @Field("price")
+ protected void setPrice(String price) {
+ this.price = price;
+ }
+}
diff --git a/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java
new file mode 100644
index 0000000000..c55e1c9ada
--- /dev/null
+++ b/apache-solrj/src/main/java/com/baeldung/solrjava/SolrJavaIntegration.java
@@ -0,0 +1,56 @@
+package com.baeldung.solrjava;
+
+import java.io.IOException;
+
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.impl.HttpSolrClient;
+import org.apache.solr.client.solrj.impl.XMLResponseParser;
+import org.apache.solr.common.SolrInputDocument;
+
+public class SolrJavaIntegration {
+
+ private HttpSolrClient solrClient;
+
+ public SolrJavaIntegration(String clientUrl) {
+
+ solrClient = new HttpSolrClient.Builder(clientUrl).build();
+ solrClient.setParser(new XMLResponseParser());
+ }
+
+ public void addProductBean(ProductBean pBean) throws IOException, SolrServerException {
+
+ solrClient.addBean(pBean);
+ solrClient.commit();
+ }
+
+ public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
+
+ SolrInputDocument document = new SolrInputDocument();
+ document.addField("id", documentId);
+ document.addField("name", itemName);
+ document.addField("price", itemPrice);
+ solrClient.add(document);
+ solrClient.commit();
+ }
+
+ public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
+
+ solrClient.deleteById(documentId);
+ solrClient.commit();
+ }
+
+ public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
+
+ solrClient.deleteByQuery(query);
+ solrClient.commit();
+ }
+
+ protected HttpSolrClient getSolrClient() {
+ return solrClient;
+ }
+
+ protected void setSolrClient(HttpSolrClient solrClient) {
+ this.solrClient = solrClient;
+ }
+
+}
diff --git a/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java
new file mode 100644
index 0000000000..8b5fe77c6f
--- /dev/null
+++ b/apache-solrj/src/test/java/com/baeldung/solrjava/SolrJavaIntegrationTest.java
@@ -0,0 +1,108 @@
+package com.baeldung.solrjava;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.SolrServerException;
+import org.apache.solr.client.solrj.response.QueryResponse;
+import org.apache.solr.common.SolrDocument;
+import org.apache.solr.common.SolrDocumentList;
+import org.junit.Before;
+import org.junit.Test;
+
+public class SolrJavaIntegrationTest {
+
+ private SolrJavaIntegration solrJavaIntegration;
+
+ @Before
+ public void setUp() throws Exception {
+
+ solrJavaIntegration = new SolrJavaIntegration("http://localhost:8983/solr/bigboxstore");
+ solrJavaIntegration.addSolrDocument("123456", "Kenmore Dishwasher", "599.99");
+ }
+
+ @Test
+ public void whenAdd_thenVerifyAddedByQueryOnId() throws SolrServerException, IOException {
+
+ SolrQuery query = new SolrQuery();
+ query.set("q", "id:123456");
+ QueryResponse response = null;
+
+ response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(1, docList.getNumFound());
+
+ for (SolrDocument doc : docList) {
+ assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
+ }
+ }
+
+ @Test
+ public void whenAdd_thenVerifyAddedByQueryOnPrice() throws SolrServerException, IOException {
+
+ SolrQuery query = new SolrQuery();
+ query.set("q", "price:599.99");
+ QueryResponse response = null;
+
+ response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(1, docList.getNumFound());
+
+ for (SolrDocument doc : docList) {
+ assertEquals("123456", (String) doc.getFieldValue("id"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
+ }
+ }
+
+ @Test
+ public void whenAdd_thenVerifyAddedByQuery() throws SolrServerException, IOException {
+
+ SolrDocument doc = solrJavaIntegration.getSolrClient().getById("123456");
+ assertEquals("Kenmore Dishwasher", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 599.99, (Double) doc.getFieldValue("price"));
+ }
+
+ @Test
+ public void whenAddBean_thenVerifyAddedByQuery() throws SolrServerException, IOException {
+
+ ProductBean pBean = new ProductBean("888", "Apple iPhone 6s", "299.99");
+ solrJavaIntegration.addProductBean(pBean);
+
+ SolrDocument doc = solrJavaIntegration.getSolrClient().getById("888");
+ assertEquals("Apple iPhone 6s", (String) doc.getFieldValue("name"));
+ assertEquals((Double) 299.99, (Double) doc.getFieldValue("price"));
+ }
+
+ @Test
+ public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {
+
+ solrJavaIntegration.deleteSolrDocumentById("123456");
+
+ SolrQuery query = new SolrQuery();
+ query.set("q", "id:123456");
+ QueryResponse response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(0, docList.getNumFound());
+ }
+
+ @Test
+ public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {
+
+ solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");
+
+ SolrQuery query = new SolrQuery();
+ query.set("q", "id:123456");
+ QueryResponse response = null;
+
+ response = solrJavaIntegration.getSolrClient().query(query);
+
+ SolrDocumentList docList = response.getResults();
+ assertEquals(0, docList.getNumFound());
+ }
+}
diff --git a/apache-thrift/README.md b/apache-thrift/README.md
new file mode 100644
index 0000000000..d8b9195dcc
--- /dev/null
+++ b/apache-thrift/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [Working with Apache Thrift](http://www.baeldung.com/apache-thrift)
diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java
new file mode 100644
index 0000000000..6cb5af0695
--- /dev/null
+++ b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformResource.java
@@ -0,0 +1,579 @@
+/**
+ * Autogenerated by Thrift Compiler (0.10.0)
+ *
+ * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
+ * @generated
+ */
+package com.baeldung.thrift.impl;
+
+@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
+@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
+public class CrossPlatformResource implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CrossPlatformResource");
+
+ private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
+ private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2);
+ private static final org.apache.thrift.protocol.TField SALUTATION_FIELD_DESC = new org.apache.thrift.protocol.TField("salutation", org.apache.thrift.protocol.TType.STRING, (short)3);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new CrossPlatformResourceStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new CrossPlatformResourceTupleSchemeFactory();
+
+ public int id; // required
+ public java.lang.String name; // required
+ public java.lang.String salutation; // optional
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ ID((short)1, "id"),
+ NAME((short)2, "name"),
+ SALUTATION((short)3, "salutation");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 1: // ID
+ return ID;
+ case 2: // NAME
+ return NAME;
+ case 3: // SALUTATION
+ return SALUTATION;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ private static final int __ID_ISSET_ID = 0;
+ private byte __isset_bitfield = 0;
+ private static final _Fields optionals[] = {_Fields.SALUTATION};
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
+ tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
+ tmpMap.put(_Fields.SALUTATION, new org.apache.thrift.meta_data.FieldMetaData("salutation", org.apache.thrift.TFieldRequirementType.OPTIONAL,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CrossPlatformResource.class, metaDataMap);
+ }
+
+ public CrossPlatformResource() {
+ }
+
+ public CrossPlatformResource(
+ int id,
+ java.lang.String name)
+ {
+ this();
+ this.id = id;
+ setIdIsSet(true);
+ this.name = name;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public CrossPlatformResource(CrossPlatformResource other) {
+ __isset_bitfield = other.__isset_bitfield;
+ this.id = other.id;
+ if (other.isSetName()) {
+ this.name = other.name;
+ }
+ if (other.isSetSalutation()) {
+ this.salutation = other.salutation;
+ }
+ }
+
+ public CrossPlatformResource deepCopy() {
+ return new CrossPlatformResource(this);
+ }
+
+ @Override
+ public void clear() {
+ setIdIsSet(false);
+ this.id = 0;
+ this.name = null;
+ this.salutation = null;
+ }
+
+ public int getId() {
+ return this.id;
+ }
+
+ public CrossPlatformResource setId(int id) {
+ this.id = id;
+ setIdIsSet(true);
+ return this;
+ }
+
+ public void unsetId() {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
+ }
+
+ /** Returns true if field id is set (has been assigned a value) and false otherwise */
+ public boolean isSetId() {
+ return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
+ }
+
+ public void setIdIsSet(boolean value) {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
+ }
+
+ public java.lang.String getName() {
+ return this.name;
+ }
+
+ public CrossPlatformResource setName(java.lang.String name) {
+ this.name = name;
+ return this;
+ }
+
+ public void unsetName() {
+ this.name = null;
+ }
+
+ /** Returns true if field name is set (has been assigned a value) and false otherwise */
+ public boolean isSetName() {
+ return this.name != null;
+ }
+
+ public void setNameIsSet(boolean value) {
+ if (!value) {
+ this.name = null;
+ }
+ }
+
+ public java.lang.String getSalutation() {
+ return this.salutation;
+ }
+
+ public CrossPlatformResource setSalutation(java.lang.String salutation) {
+ this.salutation = salutation;
+ return this;
+ }
+
+ public void unsetSalutation() {
+ this.salutation = null;
+ }
+
+ /** Returns true if field salutation is set (has been assigned a value) and false otherwise */
+ public boolean isSetSalutation() {
+ return this.salutation != null;
+ }
+
+ public void setSalutationIsSet(boolean value) {
+ if (!value) {
+ this.salutation = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case ID:
+ if (value == null) {
+ unsetId();
+ } else {
+ setId((java.lang.Integer)value);
+ }
+ break;
+
+ case NAME:
+ if (value == null) {
+ unsetName();
+ } else {
+ setName((java.lang.String)value);
+ }
+ break;
+
+ case SALUTATION:
+ if (value == null) {
+ unsetSalutation();
+ } else {
+ setSalutation((java.lang.String)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case ID:
+ return getId();
+
+ case NAME:
+ return getName();
+
+ case SALUTATION:
+ return getSalutation();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case ID:
+ return isSetId();
+ case NAME:
+ return isSetName();
+ case SALUTATION:
+ return isSetSalutation();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof CrossPlatformResource)
+ return this.equals((CrossPlatformResource)that);
+ return false;
+ }
+
+ public boolean equals(CrossPlatformResource that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_id = true;
+ boolean that_present_id = true;
+ if (this_present_id || that_present_id) {
+ if (!(this_present_id && that_present_id))
+ return false;
+ if (this.id != that.id)
+ return false;
+ }
+
+ boolean this_present_name = true && this.isSetName();
+ boolean that_present_name = true && that.isSetName();
+ if (this_present_name || that_present_name) {
+ if (!(this_present_name && that_present_name))
+ return false;
+ if (!this.name.equals(that.name))
+ return false;
+ }
+
+ boolean this_present_salutation = true && this.isSetSalutation();
+ boolean that_present_salutation = true && that.isSetSalutation();
+ if (this_present_salutation || that_present_salutation) {
+ if (!(this_present_salutation && that_present_salutation))
+ return false;
+ if (!this.salutation.equals(that.salutation))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + id;
+
+ hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287);
+ if (isSetName())
+ hashCode = hashCode * 8191 + name.hashCode();
+
+ hashCode = hashCode * 8191 + ((isSetSalutation()) ? 131071 : 524287);
+ if (isSetSalutation())
+ hashCode = hashCode * 8191 + salutation.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(CrossPlatformResource other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetId()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetName()).compareTo(other.isSetName());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetName()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetSalutation()).compareTo(other.isSetSalutation());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetSalutation()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.salutation, other.salutation);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("CrossPlatformResource(");
+ boolean first = true;
+
+ sb.append("id:");
+ sb.append(this.id);
+ first = false;
+ if (!first) sb.append(", ");
+ sb.append("name:");
+ if (this.name == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.name);
+ }
+ first = false;
+ if (isSetSalutation()) {
+ if (!first) sb.append(", ");
+ sb.append("salutation:");
+ if (this.salutation == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.salutation);
+ }
+ first = false;
+ }
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
+ __isset_bitfield = 0;
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class CrossPlatformResourceStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public CrossPlatformResourceStandardScheme getScheme() {
+ return new CrossPlatformResourceStandardScheme();
+ }
+ }
+
+ private static class CrossPlatformResourceStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 1: // ID
+ if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
+ struct.id = iprot.readI32();
+ struct.setIdIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 2: // NAME
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
+ struct.name = iprot.readString();
+ struct.setNameIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 3: // SALUTATION
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
+ struct.salutation = iprot.readString();
+ struct.setSalutationIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ oprot.writeFieldBegin(ID_FIELD_DESC);
+ oprot.writeI32(struct.id);
+ oprot.writeFieldEnd();
+ if (struct.name != null) {
+ oprot.writeFieldBegin(NAME_FIELD_DESC);
+ oprot.writeString(struct.name);
+ oprot.writeFieldEnd();
+ }
+ if (struct.salutation != null) {
+ if (struct.isSetSalutation()) {
+ oprot.writeFieldBegin(SALUTATION_FIELD_DESC);
+ oprot.writeString(struct.salutation);
+ oprot.writeFieldEnd();
+ }
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class CrossPlatformResourceTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public CrossPlatformResourceTupleScheme getScheme() {
+ return new CrossPlatformResourceTupleScheme();
+ }
+ }
+
+ private static class CrossPlatformResourceTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetId()) {
+ optionals.set(0);
+ }
+ if (struct.isSetName()) {
+ optionals.set(1);
+ }
+ if (struct.isSetSalutation()) {
+ optionals.set(2);
+ }
+ oprot.writeBitSet(optionals, 3);
+ if (struct.isSetId()) {
+ oprot.writeI32(struct.id);
+ }
+ if (struct.isSetName()) {
+ oprot.writeString(struct.name);
+ }
+ if (struct.isSetSalutation()) {
+ oprot.writeString(struct.salutation);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(3);
+ if (incoming.get(0)) {
+ struct.id = iprot.readI32();
+ struct.setIdIsSet(true);
+ }
+ if (incoming.get(1)) {
+ struct.name = iprot.readString();
+ struct.setNameIsSet(true);
+ }
+ if (incoming.get(2)) {
+ struct.salutation = iprot.readString();
+ struct.setSalutationIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+}
+
diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java
new file mode 100644
index 0000000000..4e4537f7b6
--- /dev/null
+++ b/apache-thrift/generated/com/baeldung/thrift/impl/CrossPlatformService.java
@@ -0,0 +1,3745 @@
+/**
+ * Autogenerated by Thrift Compiler (0.10.0)
+ *
+ * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
+ * @generated
+ */
+package com.baeldung.thrift.impl;
+
+@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
+@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
+public class CrossPlatformService {
+
+ public interface Iface {
+
+ public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException;
+
+ public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException;
+
+ public java.util.List getList() throws InvalidOperationException, org.apache.thrift.TException;
+
+ public boolean ping() throws InvalidOperationException, org.apache.thrift.TException;
+
+ }
+
+ public interface AsyncIface {
+
+ public void get(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
+
+ public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
+
+ public void getList(org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException;
+
+ public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
+
+ }
+
+ public static class Client extends org.apache.thrift.TServiceClient implements Iface {
+ public static class Factory implements org.apache.thrift.TServiceClientFactory {
+ public Factory() {}
+ public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
+ return new Client(prot);
+ }
+ public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
+ return new Client(iprot, oprot);
+ }
+ }
+
+ public Client(org.apache.thrift.protocol.TProtocol prot)
+ {
+ super(prot, prot);
+ }
+
+ public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
+ super(iprot, oprot);
+ }
+
+ public CrossPlatformResource get(int id) throws InvalidOperationException, org.apache.thrift.TException
+ {
+ send_get(id);
+ return recv_get();
+ }
+
+ public void send_get(int id) throws org.apache.thrift.TException
+ {
+ get_args args = new get_args();
+ args.setId(id);
+ sendBase("get", args);
+ }
+
+ public CrossPlatformResource recv_get() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ get_result result = new get_result();
+ receiveBase(result, "get");
+ if (result.isSetSuccess()) {
+ return result.success;
+ }
+ if (result.e != null) {
+ throw result.e;
+ }
+ throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "get failed: unknown result");
+ }
+
+ public void save(CrossPlatformResource resource) throws InvalidOperationException, org.apache.thrift.TException
+ {
+ send_save(resource);
+ recv_save();
+ }
+
+ public void send_save(CrossPlatformResource resource) throws org.apache.thrift.TException
+ {
+ save_args args = new save_args();
+ args.setResource(resource);
+ sendBase("save", args);
+ }
+
+ public void recv_save() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ save_result result = new save_result();
+ receiveBase(result, "save");
+ if (result.e != null) {
+ throw result.e;
+ }
+ return;
+ }
+
+ public java.util.List getList() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ send_getList();
+ return recv_getList();
+ }
+
+ public void send_getList() throws org.apache.thrift.TException
+ {
+ getList_args args = new getList_args();
+ sendBase("getList", args);
+ }
+
+ public java.util.List recv_getList() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ getList_result result = new getList_result();
+ receiveBase(result, "getList");
+ if (result.isSetSuccess()) {
+ return result.success;
+ }
+ if (result.e != null) {
+ throw result.e;
+ }
+ throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getList failed: unknown result");
+ }
+
+ public boolean ping() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ send_ping();
+ return recv_ping();
+ }
+
+ public void send_ping() throws org.apache.thrift.TException
+ {
+ ping_args args = new ping_args();
+ sendBase("ping", args);
+ }
+
+ public boolean recv_ping() throws InvalidOperationException, org.apache.thrift.TException
+ {
+ ping_result result = new ping_result();
+ receiveBase(result, "ping");
+ if (result.isSetSuccess()) {
+ return result.success;
+ }
+ if (result.e != null) {
+ throw result.e;
+ }
+ throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "ping failed: unknown result");
+ }
+
+ }
+ public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
+ public static class Factory implements org.apache.thrift.async.TAsyncClientFactory {
+ private org.apache.thrift.async.TAsyncClientManager clientManager;
+ private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
+ public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
+ this.clientManager = clientManager;
+ this.protocolFactory = protocolFactory;
+ }
+ public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
+ return new AsyncClient(protocolFactory, clientManager, transport);
+ }
+ }
+
+ public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
+ super(protocolFactory, clientManager, transport);
+ }
+
+ public void get(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ checkReady();
+ get_call method_call = new get_call(id, resultHandler, this, ___protocolFactory, ___transport);
+ this.___currentMethod = method_call;
+ ___manager.call(method_call);
+ }
+
+ public static class get_call extends org.apache.thrift.async.TAsyncMethodCall {
+ private int id;
+ public get_call(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
+ super(client, protocolFactory, transport, resultHandler, false);
+ this.id = id;
+ }
+
+ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
+ prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("get", org.apache.thrift.protocol.TMessageType.CALL, 0));
+ get_args args = new get_args();
+ args.setId(id);
+ args.write(prot);
+ prot.writeMessageEnd();
+ }
+
+ public CrossPlatformResource getResult() throws InvalidOperationException, org.apache.thrift.TException {
+ if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
+ throw new java.lang.IllegalStateException("Method call not finished!");
+ }
+ org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
+ org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
+ return (new Client(prot)).recv_get();
+ }
+ }
+
+ public void save(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ checkReady();
+ save_call method_call = new save_call(resource, resultHandler, this, ___protocolFactory, ___transport);
+ this.___currentMethod = method_call;
+ ___manager.call(method_call);
+ }
+
+ public static class save_call extends org.apache.thrift.async.TAsyncMethodCall {
+ private CrossPlatformResource resource;
+ public save_call(CrossPlatformResource resource, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
+ super(client, protocolFactory, transport, resultHandler, false);
+ this.resource = resource;
+ }
+
+ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
+ prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("save", org.apache.thrift.protocol.TMessageType.CALL, 0));
+ save_args args = new save_args();
+ args.setResource(resource);
+ args.write(prot);
+ prot.writeMessageEnd();
+ }
+
+ public Void getResult() throws InvalidOperationException, org.apache.thrift.TException {
+ if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
+ throw new java.lang.IllegalStateException("Method call not finished!");
+ }
+ org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
+ org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
+ return null;
+ }
+ }
+
+ public void getList(org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException {
+ checkReady();
+ getList_call method_call = new getList_call(resultHandler, this, ___protocolFactory, ___transport);
+ this.___currentMethod = method_call;
+ ___manager.call(method_call);
+ }
+
+ public static class getList_call extends org.apache.thrift.async.TAsyncMethodCall> {
+ public getList_call(org.apache.thrift.async.AsyncMethodCallback> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
+ super(client, protocolFactory, transport, resultHandler, false);
+ }
+
+ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
+ prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getList", org.apache.thrift.protocol.TMessageType.CALL, 0));
+ getList_args args = new getList_args();
+ args.write(prot);
+ prot.writeMessageEnd();
+ }
+
+ public java.util.List getResult() throws InvalidOperationException, org.apache.thrift.TException {
+ if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
+ throw new java.lang.IllegalStateException("Method call not finished!");
+ }
+ org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
+ org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
+ return (new Client(prot)).recv_getList();
+ }
+ }
+
+ public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ checkReady();
+ ping_call method_call = new ping_call(resultHandler, this, ___protocolFactory, ___transport);
+ this.___currentMethod = method_call;
+ ___manager.call(method_call);
+ }
+
+ public static class ping_call extends org.apache.thrift.async.TAsyncMethodCall {
+ public ping_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
+ super(client, protocolFactory, transport, resultHandler, false);
+ }
+
+ public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
+ prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("ping", org.apache.thrift.protocol.TMessageType.CALL, 0));
+ ping_args args = new ping_args();
+ args.write(prot);
+ prot.writeMessageEnd();
+ }
+
+ public java.lang.Boolean getResult() throws InvalidOperationException, org.apache.thrift.TException {
+ if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
+ throw new java.lang.IllegalStateException("Method call not finished!");
+ }
+ org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
+ org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
+ return (new Client(prot)).recv_ping();
+ }
+ }
+
+ }
+
+ public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor {
+ private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
+ public Processor(I iface) {
+ super(iface, getProcessMap(new java.util.HashMap>()));
+ }
+
+ protected Processor(I iface, java.util.Map> processMap) {
+ super(iface, getProcessMap(processMap));
+ }
+
+ private static java.util.Map> getProcessMap(java.util.Map> processMap) {
+ processMap.put("get", new get());
+ processMap.put("save", new save());
+ processMap.put("getList", new getList());
+ processMap.put("ping", new ping());
+ return processMap;
+ }
+
+ public static class get extends org.apache.thrift.ProcessFunction {
+ public get() {
+ super("get");
+ }
+
+ public get_args getEmptyArgsInstance() {
+ return new get_args();
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public get_result getResult(I iface, get_args args) throws org.apache.thrift.TException {
+ get_result result = new get_result();
+ try {
+ result.success = iface.get(args.id);
+ } catch (InvalidOperationException e) {
+ result.e = e;
+ }
+ return result;
+ }
+ }
+
+ public static class save extends org.apache.thrift.ProcessFunction {
+ public save() {
+ super("save");
+ }
+
+ public save_args getEmptyArgsInstance() {
+ return new save_args();
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public save_result getResult(I iface, save_args args) throws org.apache.thrift.TException {
+ save_result result = new save_result();
+ try {
+ iface.save(args.resource);
+ } catch (InvalidOperationException e) {
+ result.e = e;
+ }
+ return result;
+ }
+ }
+
+ public static class getList extends org.apache.thrift.ProcessFunction {
+ public getList() {
+ super("getList");
+ }
+
+ public getList_args getEmptyArgsInstance() {
+ return new getList_args();
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public getList_result getResult(I iface, getList_args args) throws org.apache.thrift.TException {
+ getList_result result = new getList_result();
+ try {
+ result.success = iface.getList();
+ } catch (InvalidOperationException e) {
+ result.e = e;
+ }
+ return result;
+ }
+ }
+
+ public static class ping extends org.apache.thrift.ProcessFunction {
+ public ping() {
+ super("ping");
+ }
+
+ public ping_args getEmptyArgsInstance() {
+ return new ping_args();
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public ping_result getResult(I iface, ping_args args) throws org.apache.thrift.TException {
+ ping_result result = new ping_result();
+ try {
+ result.success = iface.ping();
+ result.setSuccessIsSet(true);
+ } catch (InvalidOperationException e) {
+ result.e = e;
+ }
+ return result;
+ }
+ }
+
+ }
+
+ public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor {
+ private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName());
+ public AsyncProcessor(I iface) {
+ super(iface, getProcessMap(new java.util.HashMap>()));
+ }
+
+ protected AsyncProcessor(I iface, java.util.Map> processMap) {
+ super(iface, getProcessMap(processMap));
+ }
+
+ private static java.util.Map> getProcessMap(java.util.Map> processMap) {
+ processMap.put("get", new get());
+ processMap.put("save", new save());
+ processMap.put("getList", new getList());
+ processMap.put("ping", new ping());
+ return processMap;
+ }
+
+ public static class get extends org.apache.thrift.AsyncProcessFunction {
+ public get() {
+ super("get");
+ }
+
+ public get_args getEmptyArgsInstance() {
+ return new get_args();
+ }
+
+ public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
+ final org.apache.thrift.AsyncProcessFunction fcall = this;
+ return new org.apache.thrift.async.AsyncMethodCallback() {
+ public void onComplete(CrossPlatformResource o) {
+ get_result result = new get_result();
+ result.success = o;
+ try {
+ fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
+ } catch (org.apache.thrift.transport.TTransportException e) {
+ _LOGGER.error("TTransportException writing to internal frame buffer", e);
+ fb.close();
+ } catch (java.lang.Exception e) {
+ _LOGGER.error("Exception writing to internal frame buffer", e);
+ onError(e);
+ }
+ }
+ public void onError(java.lang.Exception e) {
+ byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
+ org.apache.thrift.TSerializable msg;
+ get_result result = new get_result();
+ if (e instanceof InvalidOperationException) {
+ result.e = (InvalidOperationException) e;
+ result.setEIsSet(true);
+ msg = result;
+ } else if (e instanceof org.apache.thrift.transport.TTransportException) {
+ _LOGGER.error("TTransportException inside handler", e);
+ fb.close();
+ return;
+ } else if (e instanceof org.apache.thrift.TApplicationException) {
+ _LOGGER.error("TApplicationException inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = (org.apache.thrift.TApplicationException)e;
+ } else {
+ _LOGGER.error("Exception inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
+ }
+ try {
+ fcall.sendResponse(fb,msg,msgType,seqid);
+ } catch (java.lang.Exception ex) {
+ _LOGGER.error("Exception writing to internal frame buffer", ex);
+ fb.close();
+ }
+ }
+ };
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public void start(I iface, get_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ iface.get(args.id,resultHandler);
+ }
+ }
+
+ public static class save extends org.apache.thrift.AsyncProcessFunction {
+ public save() {
+ super("save");
+ }
+
+ public save_args getEmptyArgsInstance() {
+ return new save_args();
+ }
+
+ public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
+ final org.apache.thrift.AsyncProcessFunction fcall = this;
+ return new org.apache.thrift.async.AsyncMethodCallback() {
+ public void onComplete(Void o) {
+ save_result result = new save_result();
+ try {
+ fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
+ } catch (org.apache.thrift.transport.TTransportException e) {
+ _LOGGER.error("TTransportException writing to internal frame buffer", e);
+ fb.close();
+ } catch (java.lang.Exception e) {
+ _LOGGER.error("Exception writing to internal frame buffer", e);
+ onError(e);
+ }
+ }
+ public void onError(java.lang.Exception e) {
+ byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
+ org.apache.thrift.TSerializable msg;
+ save_result result = new save_result();
+ if (e instanceof InvalidOperationException) {
+ result.e = (InvalidOperationException) e;
+ result.setEIsSet(true);
+ msg = result;
+ } else if (e instanceof org.apache.thrift.transport.TTransportException) {
+ _LOGGER.error("TTransportException inside handler", e);
+ fb.close();
+ return;
+ } else if (e instanceof org.apache.thrift.TApplicationException) {
+ _LOGGER.error("TApplicationException inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = (org.apache.thrift.TApplicationException)e;
+ } else {
+ _LOGGER.error("Exception inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
+ }
+ try {
+ fcall.sendResponse(fb,msg,msgType,seqid);
+ } catch (java.lang.Exception ex) {
+ _LOGGER.error("Exception writing to internal frame buffer", ex);
+ fb.close();
+ }
+ }
+ };
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public void start(I iface, save_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ iface.save(args.resource,resultHandler);
+ }
+ }
+
+ public static class getList extends org.apache.thrift.AsyncProcessFunction> {
+ public getList() {
+ super("getList");
+ }
+
+ public getList_args getEmptyArgsInstance() {
+ return new getList_args();
+ }
+
+ public org.apache.thrift.async.AsyncMethodCallback> getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
+ final org.apache.thrift.AsyncProcessFunction fcall = this;
+ return new org.apache.thrift.async.AsyncMethodCallback>() {
+ public void onComplete(java.util.List o) {
+ getList_result result = new getList_result();
+ result.success = o;
+ try {
+ fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
+ } catch (org.apache.thrift.transport.TTransportException e) {
+ _LOGGER.error("TTransportException writing to internal frame buffer", e);
+ fb.close();
+ } catch (java.lang.Exception e) {
+ _LOGGER.error("Exception writing to internal frame buffer", e);
+ onError(e);
+ }
+ }
+ public void onError(java.lang.Exception e) {
+ byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
+ org.apache.thrift.TSerializable msg;
+ getList_result result = new getList_result();
+ if (e instanceof InvalidOperationException) {
+ result.e = (InvalidOperationException) e;
+ result.setEIsSet(true);
+ msg = result;
+ } else if (e instanceof org.apache.thrift.transport.TTransportException) {
+ _LOGGER.error("TTransportException inside handler", e);
+ fb.close();
+ return;
+ } else if (e instanceof org.apache.thrift.TApplicationException) {
+ _LOGGER.error("TApplicationException inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = (org.apache.thrift.TApplicationException)e;
+ } else {
+ _LOGGER.error("Exception inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
+ }
+ try {
+ fcall.sendResponse(fb,msg,msgType,seqid);
+ } catch (java.lang.Exception ex) {
+ _LOGGER.error("Exception writing to internal frame buffer", ex);
+ fb.close();
+ }
+ }
+ };
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public void start(I iface, getList_args args, org.apache.thrift.async.AsyncMethodCallback> resultHandler) throws org.apache.thrift.TException {
+ iface.getList(resultHandler);
+ }
+ }
+
+ public static class ping extends org.apache.thrift.AsyncProcessFunction {
+ public ping() {
+ super("ping");
+ }
+
+ public ping_args getEmptyArgsInstance() {
+ return new ping_args();
+ }
+
+ public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
+ final org.apache.thrift.AsyncProcessFunction fcall = this;
+ return new org.apache.thrift.async.AsyncMethodCallback() {
+ public void onComplete(java.lang.Boolean o) {
+ ping_result result = new ping_result();
+ result.success = o;
+ result.setSuccessIsSet(true);
+ try {
+ fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
+ } catch (org.apache.thrift.transport.TTransportException e) {
+ _LOGGER.error("TTransportException writing to internal frame buffer", e);
+ fb.close();
+ } catch (java.lang.Exception e) {
+ _LOGGER.error("Exception writing to internal frame buffer", e);
+ onError(e);
+ }
+ }
+ public void onError(java.lang.Exception e) {
+ byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
+ org.apache.thrift.TSerializable msg;
+ ping_result result = new ping_result();
+ if (e instanceof InvalidOperationException) {
+ result.e = (InvalidOperationException) e;
+ result.setEIsSet(true);
+ msg = result;
+ } else if (e instanceof org.apache.thrift.transport.TTransportException) {
+ _LOGGER.error("TTransportException inside handler", e);
+ fb.close();
+ return;
+ } else if (e instanceof org.apache.thrift.TApplicationException) {
+ _LOGGER.error("TApplicationException inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = (org.apache.thrift.TApplicationException)e;
+ } else {
+ _LOGGER.error("Exception inside handler", e);
+ msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
+ msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
+ }
+ try {
+ fcall.sendResponse(fb,msg,msgType,seqid);
+ } catch (java.lang.Exception ex) {
+ _LOGGER.error("Exception writing to internal frame buffer", ex);
+ fb.close();
+ }
+ }
+ };
+ }
+
+ protected boolean isOneway() {
+ return false;
+ }
+
+ public void start(I iface, ping_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
+ iface.ping(resultHandler);
+ }
+ }
+
+ }
+
+ public static class get_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("get_args");
+
+ private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new get_argsStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new get_argsTupleSchemeFactory();
+
+ public int id; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ ID((short)1, "id");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 1: // ID
+ return ID;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ private static final int __ID_ISSET_ID = 0;
+ private byte __isset_bitfield = 0;
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(get_args.class, metaDataMap);
+ }
+
+ public get_args() {
+ }
+
+ public get_args(
+ int id)
+ {
+ this();
+ this.id = id;
+ setIdIsSet(true);
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public get_args(get_args other) {
+ __isset_bitfield = other.__isset_bitfield;
+ this.id = other.id;
+ }
+
+ public get_args deepCopy() {
+ return new get_args(this);
+ }
+
+ @Override
+ public void clear() {
+ setIdIsSet(false);
+ this.id = 0;
+ }
+
+ public int getId() {
+ return this.id;
+ }
+
+ public get_args setId(int id) {
+ this.id = id;
+ setIdIsSet(true);
+ return this;
+ }
+
+ public void unsetId() {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
+ }
+
+ /** Returns true if field id is set (has been assigned a value) and false otherwise */
+ public boolean isSetId() {
+ return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
+ }
+
+ public void setIdIsSet(boolean value) {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case ID:
+ if (value == null) {
+ unsetId();
+ } else {
+ setId((java.lang.Integer)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case ID:
+ return getId();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case ID:
+ return isSetId();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof get_args)
+ return this.equals((get_args)that);
+ return false;
+ }
+
+ public boolean equals(get_args that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_id = true;
+ boolean that_present_id = true;
+ if (this_present_id || that_present_id) {
+ if (!(this_present_id && that_present_id))
+ return false;
+ if (this.id != that.id)
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + id;
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(get_args other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetId()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("get_args(");
+ boolean first = true;
+
+ sb.append("id:");
+ sb.append(this.id);
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
+ __isset_bitfield = 0;
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class get_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public get_argsStandardScheme getScheme() {
+ return new get_argsStandardScheme();
+ }
+ }
+
+ private static class get_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, get_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 1: // ID
+ if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
+ struct.id = iprot.readI32();
+ struct.setIdIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, get_args struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ oprot.writeFieldBegin(ID_FIELD_DESC);
+ oprot.writeI32(struct.id);
+ oprot.writeFieldEnd();
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class get_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public get_argsTupleScheme getScheme() {
+ return new get_argsTupleScheme();
+ }
+ }
+
+ private static class get_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, get_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetId()) {
+ optionals.set(0);
+ }
+ oprot.writeBitSet(optionals, 1);
+ if (struct.isSetId()) {
+ oprot.writeI32(struct.id);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, get_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(1);
+ if (incoming.get(0)) {
+ struct.id = iprot.readI32();
+ struct.setIdIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class get_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("get_result");
+
+ private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRUCT, (short)0);
+ private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new get_resultStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new get_resultTupleSchemeFactory();
+
+ public CrossPlatformResource success; // required
+ public InvalidOperationException e; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ SUCCESS((short)0, "success"),
+ E((short)1, "e");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 0: // SUCCESS
+ return SUCCESS;
+ case 1: // E
+ return E;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class)));
+ tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(get_result.class, metaDataMap);
+ }
+
+ public get_result() {
+ }
+
+ public get_result(
+ CrossPlatformResource success,
+ InvalidOperationException e)
+ {
+ this();
+ this.success = success;
+ this.e = e;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public get_result(get_result other) {
+ if (other.isSetSuccess()) {
+ this.success = new CrossPlatformResource(other.success);
+ }
+ if (other.isSetE()) {
+ this.e = new InvalidOperationException(other.e);
+ }
+ }
+
+ public get_result deepCopy() {
+ return new get_result(this);
+ }
+
+ @Override
+ public void clear() {
+ this.success = null;
+ this.e = null;
+ }
+
+ public CrossPlatformResource getSuccess() {
+ return this.success;
+ }
+
+ public get_result setSuccess(CrossPlatformResource success) {
+ this.success = success;
+ return this;
+ }
+
+ public void unsetSuccess() {
+ this.success = null;
+ }
+
+ /** Returns true if field success is set (has been assigned a value) and false otherwise */
+ public boolean isSetSuccess() {
+ return this.success != null;
+ }
+
+ public void setSuccessIsSet(boolean value) {
+ if (!value) {
+ this.success = null;
+ }
+ }
+
+ public InvalidOperationException getE() {
+ return this.e;
+ }
+
+ public get_result setE(InvalidOperationException e) {
+ this.e = e;
+ return this;
+ }
+
+ public void unsetE() {
+ this.e = null;
+ }
+
+ /** Returns true if field e is set (has been assigned a value) and false otherwise */
+ public boolean isSetE() {
+ return this.e != null;
+ }
+
+ public void setEIsSet(boolean value) {
+ if (!value) {
+ this.e = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case SUCCESS:
+ if (value == null) {
+ unsetSuccess();
+ } else {
+ setSuccess((CrossPlatformResource)value);
+ }
+ break;
+
+ case E:
+ if (value == null) {
+ unsetE();
+ } else {
+ setE((InvalidOperationException)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case SUCCESS:
+ return getSuccess();
+
+ case E:
+ return getE();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case SUCCESS:
+ return isSetSuccess();
+ case E:
+ return isSetE();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof get_result)
+ return this.equals((get_result)that);
+ return false;
+ }
+
+ public boolean equals(get_result that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_success = true && this.isSetSuccess();
+ boolean that_present_success = true && that.isSetSuccess();
+ if (this_present_success || that_present_success) {
+ if (!(this_present_success && that_present_success))
+ return false;
+ if (!this.success.equals(that.success))
+ return false;
+ }
+
+ boolean this_present_e = true && this.isSetE();
+ boolean that_present_e = true && that.isSetE();
+ if (this_present_e || that_present_e) {
+ if (!(this_present_e && that_present_e))
+ return false;
+ if (!this.e.equals(that.e))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
+ if (isSetSuccess())
+ hashCode = hashCode * 8191 + success.hashCode();
+
+ hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287);
+ if (isSetE())
+ hashCode = hashCode * 8191 + e.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(get_result other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetSuccess()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetE()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("get_result(");
+ boolean first = true;
+
+ sb.append("success:");
+ if (this.success == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.success);
+ }
+ first = false;
+ if (!first) sb.append(", ");
+ sb.append("e:");
+ if (this.e == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.e);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ if (success != null) {
+ success.validate();
+ }
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class get_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public get_resultStandardScheme getScheme() {
+ return new get_resultStandardScheme();
+ }
+ }
+
+ private static class get_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, get_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 0: // SUCCESS
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.success = new CrossPlatformResource();
+ struct.success.read(iprot);
+ struct.setSuccessIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 1: // E
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, get_result struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.success != null) {
+ oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
+ struct.success.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ if (struct.e != null) {
+ oprot.writeFieldBegin(E_FIELD_DESC);
+ struct.e.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class get_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public get_resultTupleScheme getScheme() {
+ return new get_resultTupleScheme();
+ }
+ }
+
+ private static class get_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, get_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetSuccess()) {
+ optionals.set(0);
+ }
+ if (struct.isSetE()) {
+ optionals.set(1);
+ }
+ oprot.writeBitSet(optionals, 2);
+ if (struct.isSetSuccess()) {
+ struct.success.write(oprot);
+ }
+ if (struct.isSetE()) {
+ struct.e.write(oprot);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, get_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(2);
+ if (incoming.get(0)) {
+ struct.success = new CrossPlatformResource();
+ struct.success.read(iprot);
+ struct.setSuccessIsSet(true);
+ }
+ if (incoming.get(1)) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class save_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("save_args");
+
+ private static final org.apache.thrift.protocol.TField RESOURCE_FIELD_DESC = new org.apache.thrift.protocol.TField("resource", org.apache.thrift.protocol.TType.STRUCT, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new save_argsStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new save_argsTupleSchemeFactory();
+
+ public CrossPlatformResource resource; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ RESOURCE((short)1, "resource");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 1: // RESOURCE
+ return RESOURCE;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.RESOURCE, new org.apache.thrift.meta_data.FieldMetaData("resource", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(save_args.class, metaDataMap);
+ }
+
+ public save_args() {
+ }
+
+ public save_args(
+ CrossPlatformResource resource)
+ {
+ this();
+ this.resource = resource;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public save_args(save_args other) {
+ if (other.isSetResource()) {
+ this.resource = new CrossPlatformResource(other.resource);
+ }
+ }
+
+ public save_args deepCopy() {
+ return new save_args(this);
+ }
+
+ @Override
+ public void clear() {
+ this.resource = null;
+ }
+
+ public CrossPlatformResource getResource() {
+ return this.resource;
+ }
+
+ public save_args setResource(CrossPlatformResource resource) {
+ this.resource = resource;
+ return this;
+ }
+
+ public void unsetResource() {
+ this.resource = null;
+ }
+
+ /** Returns true if field resource is set (has been assigned a value) and false otherwise */
+ public boolean isSetResource() {
+ return this.resource != null;
+ }
+
+ public void setResourceIsSet(boolean value) {
+ if (!value) {
+ this.resource = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case RESOURCE:
+ if (value == null) {
+ unsetResource();
+ } else {
+ setResource((CrossPlatformResource)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case RESOURCE:
+ return getResource();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case RESOURCE:
+ return isSetResource();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof save_args)
+ return this.equals((save_args)that);
+ return false;
+ }
+
+ public boolean equals(save_args that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_resource = true && this.isSetResource();
+ boolean that_present_resource = true && that.isSetResource();
+ if (this_present_resource || that_present_resource) {
+ if (!(this_present_resource && that_present_resource))
+ return false;
+ if (!this.resource.equals(that.resource))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + ((isSetResource()) ? 131071 : 524287);
+ if (isSetResource())
+ hashCode = hashCode * 8191 + resource.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(save_args other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetResource()).compareTo(other.isSetResource());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetResource()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.resource, other.resource);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("save_args(");
+ boolean first = true;
+
+ sb.append("resource:");
+ if (this.resource == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.resource);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ if (resource != null) {
+ resource.validate();
+ }
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class save_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public save_argsStandardScheme getScheme() {
+ return new save_argsStandardScheme();
+ }
+ }
+
+ private static class save_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, save_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 1: // RESOURCE
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.resource = new CrossPlatformResource();
+ struct.resource.read(iprot);
+ struct.setResourceIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, save_args struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.resource != null) {
+ oprot.writeFieldBegin(RESOURCE_FIELD_DESC);
+ struct.resource.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class save_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public save_argsTupleScheme getScheme() {
+ return new save_argsTupleScheme();
+ }
+ }
+
+ private static class save_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, save_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetResource()) {
+ optionals.set(0);
+ }
+ oprot.writeBitSet(optionals, 1);
+ if (struct.isSetResource()) {
+ struct.resource.write(oprot);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, save_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(1);
+ if (incoming.get(0)) {
+ struct.resource = new CrossPlatformResource();
+ struct.resource.read(iprot);
+ struct.setResourceIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class save_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("save_result");
+
+ private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new save_resultStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new save_resultTupleSchemeFactory();
+
+ public InvalidOperationException e; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ E((short)1, "e");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 1: // E
+ return E;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(save_result.class, metaDataMap);
+ }
+
+ public save_result() {
+ }
+
+ public save_result(
+ InvalidOperationException e)
+ {
+ this();
+ this.e = e;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public save_result(save_result other) {
+ if (other.isSetE()) {
+ this.e = new InvalidOperationException(other.e);
+ }
+ }
+
+ public save_result deepCopy() {
+ return new save_result(this);
+ }
+
+ @Override
+ public void clear() {
+ this.e = null;
+ }
+
+ public InvalidOperationException getE() {
+ return this.e;
+ }
+
+ public save_result setE(InvalidOperationException e) {
+ this.e = e;
+ return this;
+ }
+
+ public void unsetE() {
+ this.e = null;
+ }
+
+ /** Returns true if field e is set (has been assigned a value) and false otherwise */
+ public boolean isSetE() {
+ return this.e != null;
+ }
+
+ public void setEIsSet(boolean value) {
+ if (!value) {
+ this.e = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case E:
+ if (value == null) {
+ unsetE();
+ } else {
+ setE((InvalidOperationException)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case E:
+ return getE();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case E:
+ return isSetE();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof save_result)
+ return this.equals((save_result)that);
+ return false;
+ }
+
+ public boolean equals(save_result that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_e = true && this.isSetE();
+ boolean that_present_e = true && that.isSetE();
+ if (this_present_e || that_present_e) {
+ if (!(this_present_e && that_present_e))
+ return false;
+ if (!this.e.equals(that.e))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287);
+ if (isSetE())
+ hashCode = hashCode * 8191 + e.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(save_result other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetE()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("save_result(");
+ boolean first = true;
+
+ sb.append("e:");
+ if (this.e == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.e);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class save_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public save_resultStandardScheme getScheme() {
+ return new save_resultStandardScheme();
+ }
+ }
+
+ private static class save_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, save_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 1: // E
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, save_result struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.e != null) {
+ oprot.writeFieldBegin(E_FIELD_DESC);
+ struct.e.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class save_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public save_resultTupleScheme getScheme() {
+ return new save_resultTupleScheme();
+ }
+ }
+
+ private static class save_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, save_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetE()) {
+ optionals.set(0);
+ }
+ oprot.writeBitSet(optionals, 1);
+ if (struct.isSetE()) {
+ struct.e.write(oprot);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, save_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(1);
+ if (incoming.get(0)) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class getList_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getList_args");
+
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getList_argsStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getList_argsTupleSchemeFactory();
+
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+;
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getList_args.class, metaDataMap);
+ }
+
+ public getList_args() {
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public getList_args(getList_args other) {
+ }
+
+ public getList_args deepCopy() {
+ return new getList_args(this);
+ }
+
+ @Override
+ public void clear() {
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof getList_args)
+ return this.equals((getList_args)that);
+ return false;
+ }
+
+ public boolean equals(getList_args that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(getList_args other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("getList_args(");
+ boolean first = true;
+
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class getList_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public getList_argsStandardScheme getScheme() {
+ return new getList_argsStandardScheme();
+ }
+ }
+
+ private static class getList_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, getList_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, getList_args struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class getList_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public getList_argsTupleScheme getScheme() {
+ return new getList_argsTupleScheme();
+ }
+ }
+
+ private static class getList_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, getList_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, getList_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class getList_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getList_result");
+
+ private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0);
+ private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new getList_resultStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new getList_resultTupleSchemeFactory();
+
+ public java.util.List success; // required
+ public InvalidOperationException e; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ SUCCESS((short)0, "success"),
+ E((short)1, "e");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 0: // SUCCESS
+ return SUCCESS;
+ case 1: // E
+ return E;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, CrossPlatformResource.class))));
+ tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getList_result.class, metaDataMap);
+ }
+
+ public getList_result() {
+ }
+
+ public getList_result(
+ java.util.List success,
+ InvalidOperationException e)
+ {
+ this();
+ this.success = success;
+ this.e = e;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public getList_result(getList_result other) {
+ if (other.isSetSuccess()) {
+ java.util.List __this__success = new java.util.ArrayList(other.success.size());
+ for (CrossPlatformResource other_element : other.success) {
+ __this__success.add(new CrossPlatformResource(other_element));
+ }
+ this.success = __this__success;
+ }
+ if (other.isSetE()) {
+ this.e = new InvalidOperationException(other.e);
+ }
+ }
+
+ public getList_result deepCopy() {
+ return new getList_result(this);
+ }
+
+ @Override
+ public void clear() {
+ this.success = null;
+ this.e = null;
+ }
+
+ public int getSuccessSize() {
+ return (this.success == null) ? 0 : this.success.size();
+ }
+
+ public java.util.Iterator getSuccessIterator() {
+ return (this.success == null) ? null : this.success.iterator();
+ }
+
+ public void addToSuccess(CrossPlatformResource elem) {
+ if (this.success == null) {
+ this.success = new java.util.ArrayList();
+ }
+ this.success.add(elem);
+ }
+
+ public java.util.List getSuccess() {
+ return this.success;
+ }
+
+ public getList_result setSuccess(java.util.List success) {
+ this.success = success;
+ return this;
+ }
+
+ public void unsetSuccess() {
+ this.success = null;
+ }
+
+ /** Returns true if field success is set (has been assigned a value) and false otherwise */
+ public boolean isSetSuccess() {
+ return this.success != null;
+ }
+
+ public void setSuccessIsSet(boolean value) {
+ if (!value) {
+ this.success = null;
+ }
+ }
+
+ public InvalidOperationException getE() {
+ return this.e;
+ }
+
+ public getList_result setE(InvalidOperationException e) {
+ this.e = e;
+ return this;
+ }
+
+ public void unsetE() {
+ this.e = null;
+ }
+
+ /** Returns true if field e is set (has been assigned a value) and false otherwise */
+ public boolean isSetE() {
+ return this.e != null;
+ }
+
+ public void setEIsSet(boolean value) {
+ if (!value) {
+ this.e = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case SUCCESS:
+ if (value == null) {
+ unsetSuccess();
+ } else {
+ setSuccess((java.util.List)value);
+ }
+ break;
+
+ case E:
+ if (value == null) {
+ unsetE();
+ } else {
+ setE((InvalidOperationException)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case SUCCESS:
+ return getSuccess();
+
+ case E:
+ return getE();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case SUCCESS:
+ return isSetSuccess();
+ case E:
+ return isSetE();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof getList_result)
+ return this.equals((getList_result)that);
+ return false;
+ }
+
+ public boolean equals(getList_result that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_success = true && this.isSetSuccess();
+ boolean that_present_success = true && that.isSetSuccess();
+ if (this_present_success || that_present_success) {
+ if (!(this_present_success && that_present_success))
+ return false;
+ if (!this.success.equals(that.success))
+ return false;
+ }
+
+ boolean this_present_e = true && this.isSetE();
+ boolean that_present_e = true && that.isSetE();
+ if (this_present_e || that_present_e) {
+ if (!(this_present_e && that_present_e))
+ return false;
+ if (!this.e.equals(that.e))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
+ if (isSetSuccess())
+ hashCode = hashCode * 8191 + success.hashCode();
+
+ hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287);
+ if (isSetE())
+ hashCode = hashCode * 8191 + e.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(getList_result other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetSuccess()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetE()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("getList_result(");
+ boolean first = true;
+
+ sb.append("success:");
+ if (this.success == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.success);
+ }
+ first = false;
+ if (!first) sb.append(", ");
+ sb.append("e:");
+ if (this.e == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.e);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class getList_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public getList_resultStandardScheme getScheme() {
+ return new getList_resultStandardScheme();
+ }
+ }
+
+ private static class getList_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, getList_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 0: // SUCCESS
+ if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
+ {
+ org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();
+ struct.success = new java.util.ArrayList(_list0.size);
+ CrossPlatformResource _elem1;
+ for (int _i2 = 0; _i2 < _list0.size; ++_i2)
+ {
+ _elem1 = new CrossPlatformResource();
+ _elem1.read(iprot);
+ struct.success.add(_elem1);
+ }
+ iprot.readListEnd();
+ }
+ struct.setSuccessIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 1: // E
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, getList_result struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.success != null) {
+ oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
+ {
+ oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size()));
+ for (CrossPlatformResource _iter3 : struct.success)
+ {
+ _iter3.write(oprot);
+ }
+ oprot.writeListEnd();
+ }
+ oprot.writeFieldEnd();
+ }
+ if (struct.e != null) {
+ oprot.writeFieldBegin(E_FIELD_DESC);
+ struct.e.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class getList_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public getList_resultTupleScheme getScheme() {
+ return new getList_resultTupleScheme();
+ }
+ }
+
+ private static class getList_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, getList_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetSuccess()) {
+ optionals.set(0);
+ }
+ if (struct.isSetE()) {
+ optionals.set(1);
+ }
+ oprot.writeBitSet(optionals, 2);
+ if (struct.isSetSuccess()) {
+ {
+ oprot.writeI32(struct.success.size());
+ for (CrossPlatformResource _iter4 : struct.success)
+ {
+ _iter4.write(oprot);
+ }
+ }
+ }
+ if (struct.isSetE()) {
+ struct.e.write(oprot);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, getList_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(2);
+ if (incoming.get(0)) {
+ {
+ org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
+ struct.success = new java.util.ArrayList(_list5.size);
+ CrossPlatformResource _elem6;
+ for (int _i7 = 0; _i7 < _list5.size; ++_i7)
+ {
+ _elem6 = new CrossPlatformResource();
+ _elem6.read(iprot);
+ struct.success.add(_elem6);
+ }
+ }
+ struct.setSuccessIsSet(true);
+ }
+ if (incoming.get(1)) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class ping_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_args");
+
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ping_argsStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ping_argsTupleSchemeFactory();
+
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+;
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_args.class, metaDataMap);
+ }
+
+ public ping_args() {
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public ping_args(ping_args other) {
+ }
+
+ public ping_args deepCopy() {
+ return new ping_args(this);
+ }
+
+ @Override
+ public void clear() {
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof ping_args)
+ return this.equals((ping_args)that);
+ return false;
+ }
+
+ public boolean equals(ping_args that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(ping_args other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("ping_args(");
+ boolean first = true;
+
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class ping_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public ping_argsStandardScheme getScheme() {
+ return new ping_argsStandardScheme();
+ }
+ }
+
+ private static class ping_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, ping_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, ping_args struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class ping_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public ping_argsTupleScheme getScheme() {
+ return new ping_argsTupleScheme();
+ }
+ }
+
+ private static class ping_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+ public static class ping_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ping_result");
+
+ private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0);
+ private static final org.apache.thrift.protocol.TField E_FIELD_DESC = new org.apache.thrift.protocol.TField("e", org.apache.thrift.protocol.TType.STRUCT, (short)1);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new ping_resultStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new ping_resultTupleSchemeFactory();
+
+ public boolean success; // required
+ public InvalidOperationException e; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ SUCCESS((short)0, "success"),
+ E((short)1, "e");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 0: // SUCCESS
+ return SUCCESS;
+ case 1: // E
+ return E;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ private static final int __SUCCESS_ISSET_ID = 0;
+ private byte __isset_bitfield = 0;
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
+ tmpMap.put(_Fields.E, new org.apache.thrift.meta_data.FieldMetaData("e", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, InvalidOperationException.class)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_result.class, metaDataMap);
+ }
+
+ public ping_result() {
+ }
+
+ public ping_result(
+ boolean success,
+ InvalidOperationException e)
+ {
+ this();
+ this.success = success;
+ setSuccessIsSet(true);
+ this.e = e;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public ping_result(ping_result other) {
+ __isset_bitfield = other.__isset_bitfield;
+ this.success = other.success;
+ if (other.isSetE()) {
+ this.e = new InvalidOperationException(other.e);
+ }
+ }
+
+ public ping_result deepCopy() {
+ return new ping_result(this);
+ }
+
+ @Override
+ public void clear() {
+ setSuccessIsSet(false);
+ this.success = false;
+ this.e = null;
+ }
+
+ public boolean isSuccess() {
+ return this.success;
+ }
+
+ public ping_result setSuccess(boolean success) {
+ this.success = success;
+ setSuccessIsSet(true);
+ return this;
+ }
+
+ public void unsetSuccess() {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
+ }
+
+ /** Returns true if field success is set (has been assigned a value) and false otherwise */
+ public boolean isSetSuccess() {
+ return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
+ }
+
+ public void setSuccessIsSet(boolean value) {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
+ }
+
+ public InvalidOperationException getE() {
+ return this.e;
+ }
+
+ public ping_result setE(InvalidOperationException e) {
+ this.e = e;
+ return this;
+ }
+
+ public void unsetE() {
+ this.e = null;
+ }
+
+ /** Returns true if field e is set (has been assigned a value) and false otherwise */
+ public boolean isSetE() {
+ return this.e != null;
+ }
+
+ public void setEIsSet(boolean value) {
+ if (!value) {
+ this.e = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case SUCCESS:
+ if (value == null) {
+ unsetSuccess();
+ } else {
+ setSuccess((java.lang.Boolean)value);
+ }
+ break;
+
+ case E:
+ if (value == null) {
+ unsetE();
+ } else {
+ setE((InvalidOperationException)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case SUCCESS:
+ return isSuccess();
+
+ case E:
+ return getE();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case SUCCESS:
+ return isSetSuccess();
+ case E:
+ return isSetE();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof ping_result)
+ return this.equals((ping_result)that);
+ return false;
+ }
+
+ public boolean equals(ping_result that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_success = true;
+ boolean that_present_success = true;
+ if (this_present_success || that_present_success) {
+ if (!(this_present_success && that_present_success))
+ return false;
+ if (this.success != that.success)
+ return false;
+ }
+
+ boolean this_present_e = true && this.isSetE();
+ boolean that_present_e = true && that.isSetE();
+ if (this_present_e || that_present_e) {
+ if (!(this_present_e && that_present_e))
+ return false;
+ if (!this.e.equals(that.e))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + ((success) ? 131071 : 524287);
+
+ hashCode = hashCode * 8191 + ((isSetE()) ? 131071 : 524287);
+ if (isSetE())
+ hashCode = hashCode * 8191 + e.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(ping_result other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetSuccess()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetE()).compareTo(other.isSetE());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetE()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.e, other.e);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("ping_result(");
+ boolean first = true;
+
+ sb.append("success:");
+ sb.append(this.success);
+ first = false;
+ if (!first) sb.append(", ");
+ sb.append("e:");
+ if (this.e == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.e);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
+ __isset_bitfield = 0;
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class ping_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public ping_resultStandardScheme getScheme() {
+ return new ping_resultStandardScheme();
+ }
+ }
+
+ private static class ping_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, ping_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 0: // SUCCESS
+ if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
+ struct.success = iprot.readBool();
+ struct.setSuccessIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 1: // E
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, ping_result struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ if (struct.isSetSuccess()) {
+ oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
+ oprot.writeBool(struct.success);
+ oprot.writeFieldEnd();
+ }
+ if (struct.e != null) {
+ oprot.writeFieldBegin(E_FIELD_DESC);
+ struct.e.write(oprot);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class ping_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public ping_resultTupleScheme getScheme() {
+ return new ping_resultTupleScheme();
+ }
+ }
+
+ private static class ping_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetSuccess()) {
+ optionals.set(0);
+ }
+ if (struct.isSetE()) {
+ optionals.set(1);
+ }
+ oprot.writeBitSet(optionals, 2);
+ if (struct.isSetSuccess()) {
+ oprot.writeBool(struct.success);
+ }
+ if (struct.isSetE()) {
+ struct.e.write(oprot);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(2);
+ if (incoming.get(0)) {
+ struct.success = iprot.readBool();
+ struct.setSuccessIsSet(true);
+ }
+ if (incoming.get(1)) {
+ struct.e = new InvalidOperationException();
+ struct.e.read(iprot);
+ struct.setEIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+ }
+
+}
diff --git a/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java b/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java
new file mode 100644
index 0000000000..c07616a00e
--- /dev/null
+++ b/apache-thrift/generated/com/baeldung/thrift/impl/InvalidOperationException.java
@@ -0,0 +1,472 @@
+/**
+ * Autogenerated by Thrift Compiler (0.10.0)
+ *
+ * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
+ * @generated
+ */
+package com.baeldung.thrift.impl;
+
+@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
+@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
+public class InvalidOperationException extends org.apache.thrift.TException implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable {
+ private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperationException");
+
+ private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.I32, (short)1);
+ private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2);
+
+ private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InvalidOperationExceptionStandardSchemeFactory();
+ private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InvalidOperationExceptionTupleSchemeFactory();
+
+ public int code; // required
+ public java.lang.String description; // required
+
+ /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
+ public enum _Fields implements org.apache.thrift.TFieldIdEnum {
+ CODE((short)1, "code"),
+ DESCRIPTION((short)2, "description");
+
+ private static final java.util.Map byName = new java.util.HashMap();
+
+ static {
+ for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
+ byName.put(field.getFieldName(), field);
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, or null if its not found.
+ */
+ public static _Fields findByThriftId(int fieldId) {
+ switch(fieldId) {
+ case 1: // CODE
+ return CODE;
+ case 2: // DESCRIPTION
+ return DESCRIPTION;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ * Find the _Fields constant that matches fieldId, throwing an exception
+ * if it is not found.
+ */
+ public static _Fields findByThriftIdOrThrow(int fieldId) {
+ _Fields fields = findByThriftId(fieldId);
+ if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
+ return fields;
+ }
+
+ /**
+ * Find the _Fields constant that matches name, or null if its not found.
+ */
+ public static _Fields findByName(java.lang.String name) {
+ return byName.get(name);
+ }
+
+ private final short _thriftId;
+ private final java.lang.String _fieldName;
+
+ _Fields(short thriftId, java.lang.String fieldName) {
+ _thriftId = thriftId;
+ _fieldName = fieldName;
+ }
+
+ public short getThriftFieldId() {
+ return _thriftId;
+ }
+
+ public java.lang.String getFieldName() {
+ return _fieldName;
+ }
+ }
+
+ // isset id assignments
+ private static final int __CODE_ISSET_ID = 0;
+ private byte __isset_bitfield = 0;
+ public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
+ static {
+ java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
+ tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
+ tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.DEFAULT,
+ new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
+ metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
+ org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidOperationException.class, metaDataMap);
+ }
+
+ public InvalidOperationException() {
+ }
+
+ public InvalidOperationException(
+ int code,
+ java.lang.String description)
+ {
+ this();
+ this.code = code;
+ setCodeIsSet(true);
+ this.description = description;
+ }
+
+ /**
+ * Performs a deep copy on other.
+ */
+ public InvalidOperationException(InvalidOperationException other) {
+ __isset_bitfield = other.__isset_bitfield;
+ this.code = other.code;
+ if (other.isSetDescription()) {
+ this.description = other.description;
+ }
+ }
+
+ public InvalidOperationException deepCopy() {
+ return new InvalidOperationException(this);
+ }
+
+ @Override
+ public void clear() {
+ setCodeIsSet(false);
+ this.code = 0;
+ this.description = null;
+ }
+
+ public int getCode() {
+ return this.code;
+ }
+
+ public InvalidOperationException setCode(int code) {
+ this.code = code;
+ setCodeIsSet(true);
+ return this;
+ }
+
+ public void unsetCode() {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CODE_ISSET_ID);
+ }
+
+ /** Returns true if field code is set (has been assigned a value) and false otherwise */
+ public boolean isSetCode() {
+ return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CODE_ISSET_ID);
+ }
+
+ public void setCodeIsSet(boolean value) {
+ __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CODE_ISSET_ID, value);
+ }
+
+ public java.lang.String getDescription() {
+ return this.description;
+ }
+
+ public InvalidOperationException setDescription(java.lang.String description) {
+ this.description = description;
+ return this;
+ }
+
+ public void unsetDescription() {
+ this.description = null;
+ }
+
+ /** Returns true if field description is set (has been assigned a value) and false otherwise */
+ public boolean isSetDescription() {
+ return this.description != null;
+ }
+
+ public void setDescriptionIsSet(boolean value) {
+ if (!value) {
+ this.description = null;
+ }
+ }
+
+ public void setFieldValue(_Fields field, java.lang.Object value) {
+ switch (field) {
+ case CODE:
+ if (value == null) {
+ unsetCode();
+ } else {
+ setCode((java.lang.Integer)value);
+ }
+ break;
+
+ case DESCRIPTION:
+ if (value == null) {
+ unsetDescription();
+ } else {
+ setDescription((java.lang.String)value);
+ }
+ break;
+
+ }
+ }
+
+ public java.lang.Object getFieldValue(_Fields field) {
+ switch (field) {
+ case CODE:
+ return getCode();
+
+ case DESCRIPTION:
+ return getDescription();
+
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
+ public boolean isSet(_Fields field) {
+ if (field == null) {
+ throw new java.lang.IllegalArgumentException();
+ }
+
+ switch (field) {
+ case CODE:
+ return isSetCode();
+ case DESCRIPTION:
+ return isSetDescription();
+ }
+ throw new java.lang.IllegalStateException();
+ }
+
+ @Override
+ public boolean equals(java.lang.Object that) {
+ if (that == null)
+ return false;
+ if (that instanceof InvalidOperationException)
+ return this.equals((InvalidOperationException)that);
+ return false;
+ }
+
+ public boolean equals(InvalidOperationException that) {
+ if (that == null)
+ return false;
+ if (this == that)
+ return true;
+
+ boolean this_present_code = true;
+ boolean that_present_code = true;
+ if (this_present_code || that_present_code) {
+ if (!(this_present_code && that_present_code))
+ return false;
+ if (this.code != that.code)
+ return false;
+ }
+
+ boolean this_present_description = true && this.isSetDescription();
+ boolean that_present_description = true && that.isSetDescription();
+ if (this_present_description || that_present_description) {
+ if (!(this_present_description && that_present_description))
+ return false;
+ if (!this.description.equals(that.description))
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int hashCode = 1;
+
+ hashCode = hashCode * 8191 + code;
+
+ hashCode = hashCode * 8191 + ((isSetDescription()) ? 131071 : 524287);
+ if (isSetDescription())
+ hashCode = hashCode * 8191 + description.hashCode();
+
+ return hashCode;
+ }
+
+ @Override
+ public int compareTo(InvalidOperationException other) {
+ if (!getClass().equals(other.getClass())) {
+ return getClass().getName().compareTo(other.getClass().getName());
+ }
+
+ int lastComparison = 0;
+
+ lastComparison = java.lang.Boolean.valueOf(isSetCode()).compareTo(other.isSetCode());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetCode()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, other.code);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ lastComparison = java.lang.Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ if (isSetDescription()) {
+ lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
+ if (lastComparison != 0) {
+ return lastComparison;
+ }
+ }
+ return 0;
+ }
+
+ public _Fields fieldForId(int fieldId) {
+ return _Fields.findByThriftId(fieldId);
+ }
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
+ scheme(iprot).read(iprot, this);
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
+ scheme(oprot).write(oprot, this);
+ }
+
+ @Override
+ public java.lang.String toString() {
+ java.lang.StringBuilder sb = new java.lang.StringBuilder("InvalidOperationException(");
+ boolean first = true;
+
+ sb.append("code:");
+ sb.append(this.code);
+ first = false;
+ if (!first) sb.append(", ");
+ sb.append("description:");
+ if (this.description == null) {
+ sb.append("null");
+ } else {
+ sb.append(this.description);
+ }
+ first = false;
+ sb.append(")");
+ return sb.toString();
+ }
+
+ public void validate() throws org.apache.thrift.TException {
+ // check for required fields
+ // check for sub-struct validity
+ }
+
+ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
+ try {
+ write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
+ try {
+ // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
+ __isset_bitfield = 0;
+ read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
+ } catch (org.apache.thrift.TException te) {
+ throw new java.io.IOException(te);
+ }
+ }
+
+ private static class InvalidOperationExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public InvalidOperationExceptionStandardScheme getScheme() {
+ return new InvalidOperationExceptionStandardScheme();
+ }
+ }
+
+ private static class InvalidOperationExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme {
+
+ public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidOperationException struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TField schemeField;
+ iprot.readStructBegin();
+ while (true)
+ {
+ schemeField = iprot.readFieldBegin();
+ if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
+ break;
+ }
+ switch (schemeField.id) {
+ case 1: // CODE
+ if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
+ struct.code = iprot.readI32();
+ struct.setCodeIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ case 2: // DESCRIPTION
+ if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
+ struct.description = iprot.readString();
+ struct.setDescriptionIsSet(true);
+ } else {
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ break;
+ default:
+ org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
+ }
+ iprot.readFieldEnd();
+ }
+ iprot.readStructEnd();
+
+ // check for required fields of primitive type, which can't be checked in the validate method
+ struct.validate();
+ }
+
+ public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidOperationException struct) throws org.apache.thrift.TException {
+ struct.validate();
+
+ oprot.writeStructBegin(STRUCT_DESC);
+ oprot.writeFieldBegin(CODE_FIELD_DESC);
+ oprot.writeI32(struct.code);
+ oprot.writeFieldEnd();
+ if (struct.description != null) {
+ oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
+ oprot.writeString(struct.description);
+ oprot.writeFieldEnd();
+ }
+ oprot.writeFieldStop();
+ oprot.writeStructEnd();
+ }
+
+ }
+
+ private static class InvalidOperationExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
+ public InvalidOperationExceptionTupleScheme getScheme() {
+ return new InvalidOperationExceptionTupleScheme();
+ }
+ }
+
+ private static class InvalidOperationExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme {
+
+ @Override
+ public void write(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet optionals = new java.util.BitSet();
+ if (struct.isSetCode()) {
+ optionals.set(0);
+ }
+ if (struct.isSetDescription()) {
+ optionals.set(1);
+ }
+ oprot.writeBitSet(optionals, 2);
+ if (struct.isSetCode()) {
+ oprot.writeI32(struct.code);
+ }
+ if (struct.isSetDescription()) {
+ oprot.writeString(struct.description);
+ }
+ }
+
+ @Override
+ public void read(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
+ org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
+ java.util.BitSet incoming = iprot.readBitSet(2);
+ if (incoming.get(0)) {
+ struct.code = iprot.readI32();
+ struct.setCodeIsSet(true);
+ }
+ if (incoming.get(1)) {
+ struct.description = iprot.readString();
+ struct.setDescriptionIsSet(true);
+ }
+ }
+ }
+
+ private static S scheme(org.apache.thrift.protocol.TProtocol proto) {
+ return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
+ }
+}
+
diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml
new file mode 100644
index 0000000000..91e51a7092
--- /dev/null
+++ b/apache-thrift/pom.xml
@@ -0,0 +1,64 @@
+
+ 4.0.0
+ com.baeldung
+ apache-thrift
+ 0.0.1-SNAPSHOT
+ pom
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 1.8
+ 0.10.0
+ 0.1.11
+
+
+
+
+ org.apache.thrift
+ libthrift
+ ${thrift.version}
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+
+ org.slf4j
+ slf4j-simple
+ 1.7.12
+ test
+
+
+
+
+ install
+
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+
+
+ generate-sources
+
+ add-source
+
+
+
+ generated
+
+
+
+
+
+
+
+
diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/Application.java b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java
new file mode 100644
index 0000000000..3321a0927a
--- /dev/null
+++ b/apache-thrift/src/main/java/com/baeldung/thrift/Application.java
@@ -0,0 +1,11 @@
+package com.baeldung.thrift;
+
+import org.apache.thrift.transport.TTransportException;
+
+public class Application {
+
+ public static void main(String[] args) throws TTransportException {
+ CrossPlatformServiceServer server = new CrossPlatformServiceServer();
+ server.start();
+ }
+}
diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java
new file mode 100644
index 0000000000..8c369acccb
--- /dev/null
+++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceClient.java
@@ -0,0 +1,41 @@
+package com.baeldung.thrift;
+
+import com.baeldung.thrift.impl.CrossPlatformService;
+
+import org.apache.thrift.TException;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.transport.TSocket;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+
+public class CrossPlatformServiceClient {
+
+ public boolean ping() {
+ try {
+ TTransport transport;
+
+ transport = new TSocket("localhost", 9090);
+ transport.open();
+
+ TProtocol protocol = new TBinaryProtocol(transport);
+ CrossPlatformService.Client client = new CrossPlatformService.Client(protocol);
+
+ System.out.print("Calling remote method...");
+
+ boolean result = client.ping();
+
+ System.out.println("done.");
+
+ transport.close();
+
+ return result;
+ } catch (TTransportException e) {
+ e.printStackTrace();
+ } catch (TException x) {
+ x.printStackTrace();
+ }
+
+ return false;
+ }
+}
diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java
new file mode 100644
index 0000000000..008fc05ee7
--- /dev/null
+++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceImpl.java
@@ -0,0 +1,35 @@
+package com.baeldung.thrift;
+
+import com.baeldung.thrift.impl.CrossPlatformResource;
+import com.baeldung.thrift.impl.CrossPlatformService;
+import com.baeldung.thrift.impl.InvalidOperationException;
+
+import org.apache.thrift.TException;
+
+import java.util.Collections;
+import java.util.List;
+
+public class CrossPlatformServiceImpl implements CrossPlatformService.Iface {
+
+ @Override
+ public CrossPlatformResource get(final int id) throws InvalidOperationException, TException {
+ // add some action
+ return new CrossPlatformResource();
+ }
+
+ @Override
+ public void save(final CrossPlatformResource resource) throws InvalidOperationException, TException {
+ // add some action
+ }
+
+ @Override
+ public List getList() throws InvalidOperationException, TException {
+ // add some action
+ return Collections.emptyList();
+ }
+
+ @Override
+ public boolean ping() throws InvalidOperationException, TException {
+ return true;
+ }
+}
diff --git a/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java
new file mode 100644
index 0000000000..32c7891ef2
--- /dev/null
+++ b/apache-thrift/src/main/java/com/baeldung/thrift/CrossPlatformServiceServer.java
@@ -0,0 +1,36 @@
+package com.baeldung.thrift;
+
+import com.baeldung.thrift.impl.CrossPlatformService;
+
+import org.apache.thrift.server.TServer;
+import org.apache.thrift.server.TSimpleServer;
+import org.apache.thrift.transport.TServerSocket;
+import org.apache.thrift.transport.TServerTransport;
+import org.apache.thrift.transport.TTransportException;
+
+public class CrossPlatformServiceServer {
+
+ private TServer server;
+
+ public void start() throws TTransportException {
+ TServerTransport serverTransport = new TServerSocket(9090);
+ server = new TSimpleServer(new TServer.Args(serverTransport)
+ .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
+
+ System.out.print("Starting the server... ");
+
+ server.serve();
+
+ System.out.println("done.");
+ }
+
+ public void stop() {
+ if (server != null && server.isServing()) {
+ System.out.print("Stopping the server... ");
+
+ server.stop();
+
+ System.out.println("done.");
+ }
+ }
+}
diff --git a/apache-thrift/src/main/resources/cross-platform-service.thrift b/apache-thrift/src/main/resources/cross-platform-service.thrift
new file mode 100644
index 0000000000..d6d3c51e18
--- /dev/null
+++ b/apache-thrift/src/main/resources/cross-platform-service.thrift
@@ -0,0 +1,24 @@
+namespace cpp com.baeldung.thrift.impl
+namespace java com.baeldung.thrift.impl
+
+exception InvalidOperationException {
+ 1: i32 code,
+ 2: string description
+}
+
+struct CrossPlatformResource {
+ 1: i32 id,
+ 2: string name,
+ 3: optional string salutation
+}
+
+service CrossPlatformService {
+
+ CrossPlatformResource get(1:i32 id) throws (1:InvalidOperationException e),
+
+ void save(1:CrossPlatformResource resource) throws (1:InvalidOperationException e),
+
+ list getList() throws (1:InvalidOperationException e),
+
+ bool ping() throws (1:InvalidOperationException e)
+}
\ No newline at end of file
diff --git a/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java
new file mode 100644
index 0000000000..7d4b41c400
--- /dev/null
+++ b/apache-thrift/src/test/java/com/baeldung/thrift/CrossPlatformServiceIntegrationTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.thrift;
+
+import org.apache.thrift.transport.TTransportException;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class CrossPlatformServiceIntegrationTest {
+
+ private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
+
+ @Before
+ public void setUp() {
+ new Thread(() -> {
+ try {
+ server.start();
+ } catch (TTransportException e) {
+ e.printStackTrace();
+ }
+ }).start();
+ try {
+ // wait for the server start up
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @After
+ public void tearDown() {
+ server.stop();
+ }
+
+ @Test
+ public void ping() {
+ CrossPlatformServiceClient client = new CrossPlatformServiceClient();
+ Assert.assertTrue(client.ping());
+ }
+}
diff --git a/apache-velocity/README.md b/apache-velocity/README.md
new file mode 100644
index 0000000000..53c67f847e
--- /dev/null
+++ b/apache-velocity/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [Introduction to Apache Velocity](http://www.baeldung.com/apache-velocity)
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
new file mode 100644
index 0000000000..69633ebbab
--- /dev/null
+++ b/apache-velocity/pom.xml
@@ -0,0 +1,70 @@
+
+
+ 4.0.0
+ com.baeldung
+ 0.1-SNAPSHOT
+ apache-velocity
+
+ war
+ apache-velocity
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 1.8
+ 1.2
+ 2.6
+ 4.5.2
+ 1.7
+ 2.0
+
+
+
+
+ org.apache.velocity
+ velocity
+ ${velocity-version}
+
+
+ org.apache.velocity
+ velocity-tools
+ ${velocity-tools-version}
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${org.apache.httpcomponents.version}
+ test
+
+
+ commons-logging
+ commons-logging
+
+
+
+
+
+ apache-velocity
+
+
+ src/main/resources
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
+
+
+
diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java
new file mode 100644
index 0000000000..c215223181
--- /dev/null
+++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/model/Product.java
@@ -0,0 +1,33 @@
+package com.baeldung.apache.velocity.model;
+
+public class Product {
+
+ private String name;
+ private double price;
+
+ public Product(String name, double price) {
+ this.name = name;
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public double getPrice() {
+ return price;
+ }
+
+ public void setPrice(double price) {
+ this.price = price;
+ }
+
+ @Override
+ public String toString() {
+ return "Product{" + "name='" + name + '\'' + ", price=" + price + '}';
+ }
+}
diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java
new file mode 100644
index 0000000000..0a623d4d65
--- /dev/null
+++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/service/ProductService.java
@@ -0,0 +1,20 @@
+package com.baeldung.apache.velocity.service;
+
+import com.baeldung.apache.velocity.model.Product;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class ProductService {
+
+ Logger logger = LoggerFactory.getLogger(ProductService.class);
+
+ public List getProducts() {
+ logger.debug("Product service returning list of products");
+
+ return Arrays.asList(new Product("Laptop", 31000.00), new Product("Mobile", 16000.00),
+ new Product("Tablet", 15000.00), new Product("Camera", 23000.00));
+ }
+}
diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java
new file mode 100644
index 0000000000..d4208a3880
--- /dev/null
+++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/LayoutServlet.java
@@ -0,0 +1,41 @@
+package com.baeldung.apache.velocity.servlet;
+
+import com.baeldung.apache.velocity.model.Product;
+import com.baeldung.apache.velocity.service.ProductService;
+import org.apache.velocity.Template;
+import org.apache.velocity.context.Context;
+import org.apache.velocity.tools.view.VelocityLayoutServlet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.List;
+
+public class LayoutServlet extends VelocityLayoutServlet {
+ ProductService service = new ProductService();
+
+ @Override
+ public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
+
+ Logger logger= LoggerFactory.getLogger(LayoutServlet.class);
+
+ List products = service.getProducts();
+
+ context.put("products", products);
+
+ Template template = null;
+
+ try {
+ template = getTemplate("templates/layoutdemo.vm");
+
+ response.setHeader("Template Returned", "Success");
+ } catch (Exception e) {
+ logger.error("Error while reading the template ",e);
+ }
+
+ return template;
+
+ }
+
+}
diff --git a/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java
new file mode 100644
index 0000000000..60c9169fce
--- /dev/null
+++ b/apache-velocity/src/main/java/com/baeldung/apache/velocity/servlet/ProductServlet.java
@@ -0,0 +1,40 @@
+package com.baeldung.apache.velocity.servlet;
+
+import com.baeldung.apache.velocity.model.Product;
+import com.baeldung.apache.velocity.service.ProductService;
+import org.apache.velocity.Template;
+import org.apache.velocity.context.Context;
+import org.apache.velocity.tools.view.VelocityViewServlet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.List;
+
+public class ProductServlet extends VelocityViewServlet {
+
+ ProductService service = new ProductService();
+
+ @Override
+ public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {
+
+ Logger logger= LoggerFactory.getLogger(ProductServlet.class);
+
+ List products = service.getProducts();
+
+ context.put("products", products);
+
+ Template template = null;
+
+ try {
+ template = getTemplate("templates/index.vm");
+ response.setHeader("Template Returned", "Success");
+ } catch (Exception e) {
+ logger.error("Error while reading the template ", e);
+ }
+
+ return template;
+
+ }
+}
diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml
new file mode 100644
index 0000000000..ec0dc2469a
--- /dev/null
+++ b/apache-velocity/src/main/resources/logback.xml
@@ -0,0 +1,19 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-velocity/src/main/webapp/WEB-INF/velocity.properties b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties
new file mode 100644
index 0000000000..97b19f4cb7
--- /dev/null
+++ b/apache-velocity/src/main/webapp/WEB-INF/velocity.properties
@@ -0,0 +1,4 @@
+resource.loader=webapp
+webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
+webapp.resource.loader.path =
+webapp.resource.loader.cache = true
\ No newline at end of file
diff --git a/apache-velocity/src/main/webapp/WEB-INF/web.xml b/apache-velocity/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..95b41b36dd
--- /dev/null
+++ b/apache-velocity/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,49 @@
+
+
+
+ apache-velocity
+
+ ProductServlet
+ com.baeldung.apache.velocity.servlet.ProductServlet
+
+
+
+ LayoutServlet
+ com.baeldung.apache.velocity.servlet.LayoutServlet
+
+
+ velocityLayout
+ org.apache.velocity.tools.view.VelocityLayoutServlet
+
+
+ org.apache.velocity.properties
+ /WEB-INF/velocity.properties
+
+
+
+ ProductServlet
+ /
+
+
+
+ LayoutServlet
+ /layout
+
+
+ velocityLayout
+ *.vm
+
+
+
+
+ 30
+
+
+
+
+
+ index.html
+
+
diff --git a/apache-velocity/src/main/webapp/fragments/footer.vm b/apache-velocity/src/main/webapp/fragments/footer.vm
new file mode 100644
index 0000000000..41bb36ce5e
--- /dev/null
+++ b/apache-velocity/src/main/webapp/fragments/footer.vm
@@ -0,0 +1,4 @@
+
+ @Copyright baeldung.com
+
\ No newline at end of file
diff --git a/apache-velocity/src/main/webapp/fragments/header.vm b/apache-velocity/src/main/webapp/fragments/header.vm
new file mode 100644
index 0000000000..96700d3baf
--- /dev/null
+++ b/apache-velocity/src/main/webapp/fragments/header.vm
@@ -0,0 +1,5 @@
+
+
+
Layout Demo Page
+
+
\ No newline at end of file
diff --git a/apache-velocity/src/main/webapp/layout/Default.vm b/apache-velocity/src/main/webapp/layout/Default.vm
new file mode 100644
index 0000000000..39a8b277a5
--- /dev/null
+++ b/apache-velocity/src/main/webapp/layout/Default.vm
@@ -0,0 +1,22 @@
+
+
+ Velocity
+
+
+
+ #parse("/fragments/header.vm")
+
+
+
+
+
+
+ $screen_content
+
+
+
+
+ #parse("/fragments/footer.vm")
+
+
+
\ No newline at end of file
diff --git a/apache-velocity/src/main/webapp/templates/index.vm b/apache-velocity/src/main/webapp/templates/index.vm
new file mode 100644
index 0000000000..0ca07caf42
--- /dev/null
+++ b/apache-velocity/src/main/webapp/templates/index.vm
@@ -0,0 +1,63 @@
+
+
+ Online Electronic Store
+
+
+
+
+
+
Today's Offers
+
+
+
$products.size() Products on Sale!
+
+ We are proud to offer these fine products
+ at these amazing prices.
+
+
+ #set( $count = 1 )
+