From f384e46bb1cae1f01fb1ce9b73632c5878f95073 Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sun, 17 Sep 2017 01:42:33 +0100 Subject: [PATCH 1/4] Example Code for N1QL (#2629) * added updated example codes * updated example code StringToCharStream * deleted StringToCharStream.java locally * removed redundant file * added code for apache commons collection SetUtils * refactored example code * added example code for bytebuddy * added example code for PCollections * update pom * refactored tests for PCollections * spring security xml config * spring security xml config * remove redundant comment * example code for apache-shiro * updated example code for Vavr Collections * updated Vavr's Collection example * updated Vavr Collection file * updated example code for Apache Shiro * updated Vavr Collections example * added example code for N1QL * update example code for N1QL * added integration test for N1QL --- couchbase-sdk/.gitignore | 6 + couchbase-sdk/pom.xml | 16 +- .../couchbase/n1ql/BucketFactory.java | 26 ++ .../baeldung/couchbase/n1ql/CodeSnippets.java | 21 ++ .../couchbase/n1ql/IntegrationTestConfig.java | 26 ++ .../couchbase/n1ql/N1QLIntegrationTest.java | 255 ++++++++++++++++++ 6 files changed, 349 insertions(+), 1 deletion(-) create mode 100644 couchbase-sdk/.gitignore create mode 100644 couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java create mode 100644 couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java create mode 100644 couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java create mode 100644 couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java diff --git a/couchbase-sdk/.gitignore b/couchbase-sdk/.gitignore new file mode 100644 index 0000000000..f6867e01bd --- /dev/null +++ b/couchbase-sdk/.gitignore @@ -0,0 +1,6 @@ +# Created by .ignore support plugin (hsz.mobi) + +# IntelliJ project files +.idea +*.iml +/target/ diff --git a/couchbase-sdk/pom.xml b/couchbase-sdk/pom.xml index fd9e1b08f6..d78ceb8933 100644 --- a/couchbase-sdk/pom.xml +++ b/couchbase-sdk/pom.xml @@ -23,6 +23,18 @@ ${couchbase.client.version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + io.vavr + vavr + ${vavr-version} + + + org.springframework @@ -67,9 +79,11 @@ 1.8 UTF-8 - 2.4.0 + 2.5.0 4.3.5.RELEASE 3.5 + 0.9.0 + 2.9.1 diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java new file mode 100644 index 0000000000..98fbe17e60 --- /dev/null +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BucketFactory { + + @Autowired + private Cluster cluster; + + private Bucket travelSampleBucket; + private Bucket testBucket; + + public Bucket getTravelSampleBucket() { + return (travelSampleBucket != null) ? + travelSampleBucket : cluster.openBucket("travel-sample"); + } + + public Bucket getTestBucket() { + return (testBucket != null) ? + testBucket : cluster.openBucket("test"); + } +} diff --git a/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java new file mode 100644 index 0000000000..999dcd897f --- /dev/null +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java @@ -0,0 +1,21 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.query.N1qlQueryResult; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.vavr.control.Try; + +import java.util.List; +import java.util.stream.Collectors; + +public class CodeSnippets { + + public static List extractJsonResult(N1qlQueryResult result) { + ObjectMapper objectMapper = new ObjectMapper(); + return result.allRows().stream() + .map(row -> Try.of(() -> objectMapper.readTree(row.value().toString())) + .getOrNull()) + .collect(Collectors.toList()); + } + +} diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java new file mode 100644 index 0000000000..ef7e31b224 --- /dev/null +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java @@ -0,0 +1,26 @@ +package com.baeldung.couchbase.n1ql; + +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.TimeUnit; + +@Configuration +@ComponentScan(basePackages = { "com.baeldung.couchbase.n1ql" }) +public class IntegrationTestConfig { + + @Bean + public Cluster cluster() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() + .connectTimeout(60000) + .build(); + return CouchbaseCluster.create(env, "127.0.0.1"); + } + + +} diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java new file mode 100644 index 0000000000..d05b107098 --- /dev/null +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java @@ -0,0 +1,255 @@ +package com.baeldung.couchbase.n1ql; + +import com.baeldung.couchbase.n1ql.IntegrationTestConfig; +import com.couchbase.client.java.Bucket; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.document.JsonDocument; +import com.couchbase.client.java.document.json.JsonArray; +import com.couchbase.client.java.document.json.JsonObject; +import com.couchbase.client.java.query.N1qlQuery; +import com.couchbase.client.java.query.N1qlQueryResult; +import com.couchbase.client.java.query.N1qlQueryRow; +import com.couchbase.client.java.query.Statement; +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import rx.Observable; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; +import static com.couchbase.client.java.query.Select.select; +import static com.couchbase.client.java.query.dsl.Expression.i; +import static com.couchbase.client.java.query.dsl.Expression.s; +import static com.couchbase.client.java.query.dsl.Expression.x; +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { IntegrationTestConfig.class }) +public class N1QLIntegrationTest { + + + @Autowired + private Cluster cluster; + + @Autowired + private BucketFactory bucketFactory; + + @Test + public void givenAutowiredCluster_whenNotNull_thenNotNull() { + assertNotNull(cluster); + } + + @Test + public void givenBucketFactory_whenGetTestBucket_thenNotNull() { + assertNotNull(bucketFactory.getTestBucket()); + } + + @Test + public void givenBucketFactory_whenGetTravelSampleBucket_thenNotNull() { + assertNotNull(bucketFactory.getTravelSampleBucket()); + } + + @Test + public void givenDocument_whenInsert_thenResult() { + Bucket bucket = bucketFactory.getTestBucket(); + JsonObject personObj = JsonObject.create() + .put("name", "John") + .put("email", "john@doe.com") + .put("interests", JsonArray.from("Java", "Nigerian Jollof")); + + String id = UUID.randomUUID().toString(); + JsonDocument doc = JsonDocument.create(id, personObj); + bucket.insert(doc); + assertNotNull(bucket.get(id)); + } + + @Test + public void whenBasicSelectQuery_thenGetQueryResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + N1qlQueryResult result + = bucket.query(N1qlQuery.simple("SELECT * FROM test")); + + result.forEach(System.out::println); + + System.out.println("result count: " + result.info().resultCount()); + System.out.println("error count: " + result.info().errorCount()); + } + + @Test + public void givenSelectStatement_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query = "SELECT name FROM `travel-sample` " + + "WHERE type = 'airport' LIMIT 100"; + N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query)); + + System.out.println("Result Count " + result1.info().resultCount()); + + N1qlQueryRow row = result1.allRows().get(0); + JsonObject rowJson = row.value(); + System.out.println("Name in First Row " + rowJson.get("name")); + + } + + @Test + public void givenSelectStatement2_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject pVal = JsonObject.create().put("type", "airport"); + String query = "SELECT * FROM `travel-sample` " + + "WHERE type = $type LIMIT 100"; + N1qlQueryResult r2 = bucket.query(N1qlQuery.parameterized(query, pVal)); + + System.out.println(r2.allRows()); + + List list = extractJsonResult(r2); + System.out.println( + list.get(0).get("travel-sample").get("airportname").asText()); + } + + @Test + public void givenSelectDSL_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + Statement statement = select("*") + .from(i("travel-sample")) + .where(x("type").eq(s("airport"))) + .limit(100); + N1qlQueryResult r3 = bucket.query(N1qlQuery.simple(statement)); + + List list2 = extractJsonResult(r3); + System.out.println("First Airport Name: " + list2.get(0).get("travel-sample").get("airportname").asText()); + + } + + @Test + public void givenSelectStatementWithOperators_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query2 = "SELECT t.city, " + + "t.airportname || \" (\" || t.faa || \")\" AS portname_faa " + + "FROM `travel-sample` t " + + "WHERE t.type=\"airport\"" + + "AND t.country LIKE '%States'" + + "AND t.geo.lat >= 70 " + + "LIMIT 2"; + N1qlQueryResult r4 = bucket.query(N1qlQuery.simple(query2)); + List list3 = extractJsonResult(r4); + System.out.println("First Doc : " + list3.get(0)); + } + + @Test + public void givenSelectStatementWithDSL2_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + Statement st2 = select( + x("t.city, t.airportname") + .concat(s(" (")).concat(x("t.faa")).concat(s(")")).as("portname_faa")) + .from(i("travel-sample").as("t")) + .where( x("t.type").eq(s("airport")) + .and(x("t.country").like(s("%States"))) + .and(x("t.geo.lat").gte(70))) + .limit(2); + N1qlQueryResult r5 = bucket.query(N1qlQuery.simple(st2)); + List list5 = extractJsonResult(r5); + System.out.println("First Doc : " + list5.get(0)); + System.out.println("Query from Statement2: " + st2.toString()); + } + + @Test + public void givenInsertStatement_whenQuery_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query = "INSERT INTO `travel-sample` (KEY, VALUE) " + + " VALUES(" + + "\"cust1293\", " + + "{\"id\":\"1293\",\"name\":\"Sample Airline\", \"type\":\"airline\"})" + + " RETURNING META().id as docid, *"; + N1qlQueryResult r1 = bucket.query(N1qlQuery.simple(query)); + r1.forEach(System.out::println); + } + + @Test + public void givenDocument_whenInsert_thenResults() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject ob = JsonObject.create() + .put("id", "1293") + .put("name", "Sample Airline") + .put("type", "airline"); + bucket.insert(JsonDocument.create("cust1295", ob)); + } + + @Test + public void givenDocuments_whenBatchInsert_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + int docsToCreate = 10; + List documents = new ArrayList<>(); + for (int i = 5; i < docsToCreate; i++) { + JsonObject content = JsonObject.create() + .put("id", i) + .put("type", "airline") + .put("name", "Sample Airline " + i); + documents.add(JsonDocument.create("cust_" + i, content)); + } + + List r5 = Observable + .from(documents) + .flatMap(doc -> bucket.async().insert(doc)) + .toList() + .last() + .toBlocking() + .single(); + + r5.forEach(System.out::println); + } + + @Test + public void givenUpdateStatement_whenQuery_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query2 = "UPDATE `travel-sample` USE KEYS \"cust_1\" " + + "SET name=\"Sample Airline Updated\" RETURNING name"; + N1qlQueryResult result = bucket.query(N1qlQuery.simple(query2)); + result.forEach(System.out::println); + } + + @Test + public void givenDocument_whenUpsert_thenUpdate() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + JsonObject o2 = JsonObject.create() + .put("name", "Sample Airline Updated"); + bucket.upsert(JsonDocument.create("cust_1", o2)); + } + + @Test + public void givenUnestUpdateStatement_whenQuery_thenResult() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query3 = "UPDATE `travel-sample` USE KEYS \"cust_2\" " + + "UNSET name RETURNING *"; + N1qlQueryResult result1 = bucket.query(N1qlQuery.simple(query3)); + result1.forEach(System.out::println); + } + + @Test + public void givenDeleteStatement_whenQuery_thenDelete() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query4 = "DELETE FROM `travel-sample` USE KEYS \"cust_50\""; + N1qlQueryResult result4 = bucket.query(N1qlQuery.simple(query4)); + } + + @Test + public void givenDeleteStatement2_whenQuery_thenDelete() { + Bucket bucket = bucketFactory.getTravelSampleBucket(); + String query5 = "DELETE FROM `travel-sample` WHERE id = 0 RETURNING *"; + N1qlQueryResult result5 = bucket.query(N1qlQuery.simple(query5)); + } + + +} From 9081c089f69977dc53435c37ddca98bf0bb0baa8 Mon Sep 17 00:00:00 2001 From: nabyla <31042612+nabyla@users.noreply.github.com> Date: Sun, 17 Sep 2017 08:20:58 +0100 Subject: [PATCH 2/4] Add stream supplier test (#2631) --- .../baeldung/stream/SupplierStreamTest.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java new file mode 100644 index 0000000000..d78c9fca35 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java @@ -0,0 +1,35 @@ +package com.baeldung.stream; + +import static org.junit.Assert.fail; + +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.junit.Test; + +public class SupplierStreamTest { + + @Test(expected = IllegalStateException.class) + public void givenStream_whenStreamUsedTwice_thenThrowException() { + Stream stringStream = Stream.of("A", "B", "C", "D"); + Optional result1 = stringStream.findAny(); + System.out.println(result1.get()); + Optional result2 = stringStream.findFirst(); + System.out.println(result2.get()); + } + + @Test + public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() { + try { + Supplier> streamSupplier = () -> Stream.of("A", "B", "C", "D"); + Optional result1 = streamSupplier.get().findAny(); + System.out.println(result1.get()); + Optional result2 = streamSupplier.get().findFirst(); + System.out.println(result2.get()); + } catch (IllegalStateException e) { + fail(); + } + } + +} \ No newline at end of file From 1ced2a3b87698a0b605b7438613ab9c909060f72 Mon Sep 17 00:00:00 2001 From: Adam InTae Gerard Date: Sun, 17 Sep 2017 02:43:49 -0700 Subject: [PATCH 3/4] BAEL-1052: EthereumJ (#2614) * Simple Boot REST application and example * BAEL-509 - Removed extra duplicate ant matcher * Example and Unit Tests * documentation * BAEL-1085 - changes per PR code review and document review - altered integration to unit test - all's good * BAEL-1085 - Renamed unit tests and added both to pom.xml * IntelliJ formatter * REVERT - Had removed a duplicate ant matcher from BAEL-509 - this was the incorrect process - reverting now, article has been corrected, but will issue a seperate PR for this * BAEL-509: Removed duplicate ant matcher - does not impact code at runtime * BAEL-1085: Per editor's request, removed Angular client - using CURL POST commands now in article - as such moved the code into a more appropriate module: spring-rest * BAEL-1052: EthereumJ * BAEL-1052: .pom module renamed to EthereumJ * Try catch clauses removed - tested and verified everything again --- ethereumj/.gitgnore | 6 + ethereumj/README.md | 4 + ethereumj/pom.xml | 110 ++++++++++++++++++ .../baeldung/ethereumj/ApplicationMain.java | 16 +++ .../com/baeldung/ethereumj/Constants.java | 9 ++ .../com/baeldung/ethereumj/beans/EthBean.java | 25 ++++ .../baeldung/ethereumj/config/EthConfig.java | 18 +++ .../ethereumj/controllers/EthController.java | 44 +++++++ .../ethereumj/listeners/EthListener.java | 71 +++++++++++ .../ethereumj/transfer/EthResponse.java | 14 +++ .../src/main/resources/application.properties | 2 + .../controllers/EthControllerTestOne.java | 72 ++++++++++++ pom.xml | 2 + 13 files changed, 393 insertions(+) create mode 100644 ethereumj/.gitgnore create mode 100644 ethereumj/README.md create mode 100644 ethereumj/pom.xml create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java create mode 100644 ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java create mode 100644 ethereumj/src/main/resources/application.properties create mode 100644 ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java diff --git a/ethereumj/.gitgnore b/ethereumj/.gitgnore new file mode 100644 index 0000000000..9cff80e071 --- /dev/null +++ b/ethereumj/.gitgnore @@ -0,0 +1,6 @@ +.idea +target +database +logs +target +*.iml \ No newline at end of file diff --git a/ethereumj/README.md b/ethereumj/README.md new file mode 100644 index 0000000000..54da91b4f7 --- /dev/null +++ b/ethereumj/README.md @@ -0,0 +1,4 @@ +## EthereumJ + +### Relevant Articles: +- [Introduction to EthereumJ](http://www.baeldung.com/intro-to-ethereumj) \ No newline at end of file diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml new file mode 100644 index 0000000000..c9f5924d7a --- /dev/null +++ b/ethereumj/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + com.baeldung.ethereumj + ethereumj + war + 1.0.0 + ethereumj + + + UTF-8 + 1.8 + 8.5.4 + + + + org.springframework.boot + spring-boot-starter-parent + 1.5.6.RELEASE + + + + + Ethereum + Ethereum + https://dl.bintray.com/ethereum/maven/ + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-test + 1.5.6.RELEASE + test + + + + + org.ethereum + ethereumj-core + 1.5.0-RELEASE + + + + + javax.servlet + jstl + + + com.fasterxml.jackson.core + jackson-databind + 2.5.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + ethereumj + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + */EthControllerTestOne.java + + + + + + + + + + \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java b/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java new file mode 100644 index 0000000000..4735548bd1 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/ApplicationMain.java @@ -0,0 +1,16 @@ +package com.baeldung.ethereumj; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) +@SpringBootApplication +public class ApplicationMain extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(ApplicationMain.class, args); + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java b/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java new file mode 100644 index 0000000000..919958be35 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/Constants.java @@ -0,0 +1,9 @@ +package com.baeldung.ethereumj; + +public class Constants { + + public static final String ENDPOINT_ONE = "/api/get/bestblock/"; + public static final String ENDPOINT_TWO = "/api/get/difficulty/"; + public static final String RESPONSE_TYPE ="application/json/"; + +} diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java b/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java new file mode 100644 index 0000000000..7680473c6e --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/beans/EthBean.java @@ -0,0 +1,25 @@ +package com.baeldung.ethereumj.beans; + +import com.baeldung.ethereumj.listeners.EthListener; +import org.ethereum.core.Block; +import org.ethereum.facade.Ethereum; +import org.ethereum.facade.EthereumFactory; + +import java.math.BigInteger; + +public class EthBean { + private Ethereum ethereum; + + public void start() { + this.ethereum = EthereumFactory.createEthereum(); + this.ethereum.addListener(new EthListener(ethereum)); + } + + public Block getBestBlock() { + return this.ethereum.getBlockchain().getBestBlock(); + } + + public BigInteger getTotalDifficulty() { + return this.ethereum.getBlockchain().getTotalDifficulty(); + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java b/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java new file mode 100644 index 0000000000..8180cc3ce2 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/config/EthConfig.java @@ -0,0 +1,18 @@ +package com.baeldung.ethereumj.config; + +import com.baeldung.ethereumj.beans.EthBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.Executors; + +@Configuration +public class EthConfig { + + @Bean + EthBean ethBeanConfig() throws Exception { + EthBean eBean = new EthBean(); + Executors.newSingleThreadExecutor().submit(eBean::start); + return eBean; + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java b/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java new file mode 100644 index 0000000000..8240d60e30 --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/controllers/EthController.java @@ -0,0 +1,44 @@ +package com.baeldung.ethereumj.controllers; + +import com.baeldung.ethereumj.Constants; +import com.baeldung.ethereumj.beans.EthBean; +import com.baeldung.ethereumj.transfer.EthResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.PostConstruct; +import javax.servlet.ServletContext; + +@RestController +public class EthController { + + @Autowired + EthBean ethBean; + @Autowired + private ServletContext servletContext; + private Logger l = LoggerFactory.getLogger(EthController.class); + + @RequestMapping(Constants.ENDPOINT_ONE) + public EthResponse getBestBlock() { + l.debug("Request received - fetching best block."); + EthResponse r = new EthResponse(); + r.setResponse(ethBean.getBestBlock().toString()); + return r; + } + + @RequestMapping(Constants.ENDPOINT_TWO) + public EthResponse getTotalDifficulty() { + l.debug("Request received - calculating total difficulty."); + EthResponse r = new EthResponse(); + r.setResponse(ethBean.getTotalDifficulty().toString()); + return r; + } + + @PostConstruct + public void showIt() { + l.debug(servletContext.getContextPath()); + } +} diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java b/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java new file mode 100644 index 0000000000..c3a5143fdb --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/listeners/EthListener.java @@ -0,0 +1,71 @@ +package com.baeldung.ethereumj.listeners; + +import org.ethereum.core.Block; +import org.ethereum.core.TransactionReceipt; +import org.ethereum.facade.Ethereum; +import org.ethereum.listener.EthereumListenerAdapter; +import org.ethereum.util.BIUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.math.BigInteger; +import java.util.List; + +public class EthListener extends EthereumListenerAdapter { + + private Logger l = LoggerFactory.getLogger(EthListener.class); + private Ethereum ethereum; + private boolean syncDone = false; + private static final int thou = 1000; + + private void out(String t) { + l.info(t); + } + + private String calcNetHashRate(Block block) { + String response = "Net hash rate not available"; + if (block.getNumber() > thou) { + long timeDelta = 0; + for (int i = 0; i < thou; ++i) { + Block parent = ethereum + .getBlockchain() + .getBlockByHash(block.getParentHash()); + timeDelta += Math.abs(block.getTimestamp() - parent.getTimestamp()); + } + response = String.valueOf(block + .getDifficultyBI() + .divide(BIUtil.toBI(timeDelta / thou)) + .divide(new BigInteger("1000000000")) + .doubleValue()) + " GH/s"; + } + return response; + } + + public EthListener(Ethereum ethereum) { + this.ethereum = ethereum; + } + + @Override + public void onBlock(Block block, List receipts) { + if (syncDone) { + out("Net hash rate: " + calcNetHashRate(block)); + out("Block difficulty: " + block.getDifficultyBI().toString()); + out("Block transactions: " + block.getTransactionsList().toString()); + out("Best block (last block): " + ethereum + .getBlockchain() + .getBestBlock().toString()); + out("Total difficulty: " + ethereum + .getBlockchain() + .getTotalDifficulty().toString()); + } + } + + @Override + public void onSyncDone(SyncState state) { + out("onSyncDone " + state); + if (!syncDone) { + out(" ** SYNC DONE ** "); + syncDone = true; + } + } +} \ No newline at end of file diff --git a/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java b/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java new file mode 100644 index 0000000000..e8cfb3113b --- /dev/null +++ b/ethereumj/src/main/java/com/baeldung/ethereumj/transfer/EthResponse.java @@ -0,0 +1,14 @@ +package com.baeldung.ethereumj.transfer; + +public class EthResponse { + + private String response; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } +} diff --git a/ethereumj/src/main/resources/application.properties b/ethereumj/src/main/resources/application.properties new file mode 100644 index 0000000000..033e543fe8 --- /dev/null +++ b/ethereumj/src/main/resources/application.properties @@ -0,0 +1,2 @@ +server.servlet-path=/ +server.port=8080 \ No newline at end of file diff --git a/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java new file mode 100644 index 0000000000..9298c34ec2 --- /dev/null +++ b/ethereumj/src/test/java/com/baeldung/ethereumj/controllers/EthControllerTestOne.java @@ -0,0 +1,72 @@ +package com.baeldung.ethereumj.controllers; + +import com.baeldung.ethereumj.ApplicationMain; +import com.baeldung.ethereumj.Constants; +import com.baeldung.ethereumj.transfer.EthResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.*; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ApplicationMain.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@TestPropertySource(properties = "server.port=8080") +public class EthControllerTestOne { + + @LocalServerPort + int port; + + private RestTemplate restTemplate = new RestTemplate(); + + private String url(String uri) { + String s = "http://localhost:" + port + uri; + System.out.println(s); + return s; + } + + @Before + public void setup() { + restTemplate = new RestTemplate(); + } + + @Test() + public void bestBlockTest() throws Exception { + + Thread.sleep(20000); + + EthResponse a = restTemplate.getForObject(url(Constants.ENDPOINT_ONE), EthResponse.class); + assertNotNull(a); + + ResponseEntity b = restTemplate.exchange( + url(Constants.ENDPOINT_ONE), + HttpMethod.GET, new HttpEntity(null, new HttpHeaders()), EthResponse.class); + + assertTrue("Status 200?", b.getStatusCode().equals(HttpStatus.OK)); + System.out.println("Status 200?: " + b.getStatusCode().equals(HttpStatus.OK)); + assertTrue("Dynamic data returned?", b.hasBody()); + System.out.println("Dynamic data returned?: " + b.hasBody()); + } + + @Test() + public void difficultyTest() throws Exception { + + Thread.sleep(20000); + + ResponseEntity a = restTemplate.exchange( + url(Constants.ENDPOINT_TWO), + HttpMethod.GET, new HttpEntity(null, new HttpHeaders()), EthResponse.class); + + assertTrue("Status 200?", a.getStatusCode().equals(HttpStatus.OK)); + System.out.println("Status 200?: " + a.getStatusCode().equals(HttpStatus.OK)); + assertTrue("Dynamic data returned?", a.hasBody()); + System.out.println("Dynamic data returned?: " + a.hasBody()); + } +} diff --git a/pom.xml b/pom.xml index c501dddd3c..11737938a9 100644 --- a/pom.xml +++ b/pom.xml @@ -50,6 +50,8 @@ deltaspike dozer + ethereumj + feign From a323d64d757781a9e52dd8a4a8303a12cd0c444b Mon Sep 17 00:00:00 2001 From: Blue Montag Software Date: Sun, 17 Sep 2017 11:05:27 -0300 Subject: [PATCH 4/4] JIRA issue : BAEL-960. Collection Factory Methods for Vavr. User: ignaciogallego@gmail.com (#2517) * New test class for the collections factory methods in vavr * rename unit test for collection factory methods --- .../CollectionFactoryMethodsUnitTest.java | 107 ++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java diff --git a/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java new file mode 100644 index 0000000000..60359d6803 --- /dev/null +++ b/vavr/src/test/java/com/baeldung/vavr/collections/CollectionFactoryMethodsUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.vavr.collections; + +import static io.vavr.API.Array; +import static io.vavr.API.Failure; +import static io.vavr.API.List; +import static io.vavr.API.None; +import static io.vavr.API.Some; +import static io.vavr.API.Stream; +import static io.vavr.API.Success; +import static io.vavr.API.Tuple; +import static io.vavr.API.Vector; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import io.vavr.Tuple3; +import io.vavr.collection.Array; +import io.vavr.collection.List; +import io.vavr.collection.Stream; +import io.vavr.collection.Vector; +import io.vavr.control.Option; +import io.vavr.control.Try; + +public class CollectionFactoryMethodsUnitTest { + + @Test + public void givenANoneOptionElement_whenCreated_thenCorrect() { + Option none = None(); + assertFalse(none == null); + assertEquals(none, Option.none()); + } + + @Test + public void givenASomeOptionElement_whenCreated_thenCorrect() { + Option some = Some(1); + assertFalse(some == null); + assertTrue(some.contains(1)); + } + + @Test + public void givenATupleElement_whenCreated_thenCorrect() { + Tuple3 tuple = Tuple('a', "chain", 2); + assertTrue(tuple!=null); + assertEquals(tuple._1(), new Character('a')); + assertEquals(tuple._2(), "chain"); + assertEquals(tuple._3().intValue(), 2); + } + + @Test + public void givenASuccessObject_whenEvaluated_thenSuccess() { + Try integer = Success(55); + assertEquals(integer.get().intValue(), 55); + } + @Test + public void givenAFailureObject_whenEvaluated_thenExceptionThrown() { + Try failure = Failure(new Exception("Exception X encapsulated here")); + + try { + Integer i = failure.get();// evaluate a failure raise the exception + System.out.println(i);// not executed + } catch (Exception e) { + assertEquals(e.getMessage(), "Exception X encapsulated here"); + } + } + + @Test + public void givenAList_whenCreated_thenCorrect() { + List list = List(1, 2, 3, 4, 5); + + assertEquals(list.size(), 5); + assertEquals(list.get(0).intValue(), 1); + } + + @Test + public void givenAnEmptyList_whenCreated_thenCorrect() { + List empty = List(); + + assertEquals(empty.size(), 0); + assertEquals(empty, List.empty()); + } + + @Test + public void givenAnArray_whenCreated_thenCorrect() { + Array array = Array(1, 2, 3, 4, 5); + + assertEquals(array.size(), 5); + assertEquals(array.get(0).intValue(), 1); + } + + @Test + public void givenAStream_whenCreated_thenCorrect() { + Stream stream = Stream(1, 2, 3, 4, 5); + + assertEquals(stream.size(), 5); + assertEquals(stream.get(0).intValue(), 1); + } + + @Test + public void givenAVector_whenCreated_thenCorrect() { + Vector vector = Vector(1, 2, 3, 4, 5); + + assertEquals(vector.size(), 5); + assertEquals(vector.get(0).intValue(), 1); + } +}