├── .gitignore ├── LICENSE ├── README.md ├── post-1 ├── pom.xml └── src │ ├── main │ └── java │ │ └── io │ │ └── vertx │ │ └── intro │ │ └── first │ │ └── MyFirstVerticle.java │ └── test │ └── java │ └── io │ └── vertx │ └── intro │ └── first │ └── MyFirstVerticleTest.java ├── post-2 ├── pom.xml └── src │ ├── main │ ├── conf │ │ └── my-application-conf.json │ └── java │ │ └── io │ │ └── vertx │ │ └── intro │ │ └── first │ │ └── MyFirstVerticle.java │ └── test │ └── java │ └── io │ └── vertx │ └── intro │ └── first │ └── MyFirstVerticleTest.java ├── post-3 ├── pom.xml └── src │ ├── main │ ├── conf │ │ └── my-application-conf.json │ ├── java │ │ └── io │ │ │ └── vertx │ │ │ └── intro │ │ │ └── first │ │ │ ├── Article.java │ │ │ └── MyFirstVerticle.java │ └── resources │ │ └── assets │ │ └── index.html │ └── test │ └── java │ └── io │ └── vertx │ └── intro │ └── first │ └── MyFirstVerticleTest.java ├── post-4 ├── pom.xml └── src │ ├── main │ ├── conf │ │ └── my-application-conf.json │ ├── java │ │ └── io │ │ │ └── vertx │ │ │ └── intro │ │ │ └── first │ │ │ ├── ActionHelper.java │ │ │ ├── Article.java │ │ │ └── MyFirstVerticle.java │ └── resources │ │ ├── assets │ │ └── index.html │ │ └── tables.sql │ └── test │ ├── java │ └── io │ │ └── vertx │ │ └── intro │ │ └── first │ │ └── MyFirstVerticleTest.java │ └── resources │ └── tables.sql └── post-5 ├── pom.xml └── src ├── main ├── conf │ └── my-application-conf.json ├── java │ └── io │ │ └── vertx │ │ └── intro │ │ └── first │ │ ├── ActionHelper.java │ │ ├── Article.java │ │ └── MyFirstVerticle.java └── resources │ ├── assets │ └── index.html │ └── tables.sql └── test ├── java └── io │ └── vertx │ └── intro │ └── first │ └── MyFirstVerticleTest.java └── resources └── tables.sql /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | dependency-reduced-pom.xml 8 | buildNumber.properties 9 | .mvn/timing.properties 10 | 11 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 12 | !/.mvn/wrapper/maven-wrapper.jar 13 | .settings 14 | *.iml 15 | .idea 16 | 17 | .vertx 18 | .classpath 19 | .project 20 | file-uploads 21 | Icon? 22 | articles-list.png 23 | intro-to-vertx-post*.md 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction to Eclipse Vert.x 2 | 3 | This repository contains the code developed in the _Introduction to Eclipse Vert.x_ blog post series. Posts composing the series are: 4 | 5 | 1. [My First Vert.x Application](https://developers.redhat.com/blog/2018/03/13/eclipse-vertx-first-application/) 6 | 2. [Eclipse Vert.x Application Configuration](https://developers.redhat.com/blog/2018/03/22/eclipse-vert-x-application-configuration/) 7 | 3. [Some REST with Vert.x](https://developers.redhat.com/blog/2018/03/29/rest-vert-x/) 8 | 4. [Asynchronous data access with Vert.x](https://developers.redhat.com/blog/2018/04/09/accessing-data-reactive-way/) 9 | 5. [Using Reactive eXtensions with Vert.x](https://developers.redhat.com/blog/2018/04/18/eclipse-vertx-reactive-extensions/) 10 | 6. Deploying Vert.x applications on Kubernetes and OpenShift - to be published 11 | 12 | The code developed for each post is contained in the corresponding folder. Except mentionned otherwise in the blog post, the application can be: 13 | 14 | * build using: `mvn package` 15 | * run locally using `mvn compile vertx:run` 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /post-1/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.vertx.intro 8 | my-first-app 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.9.3 13 | 1.0.13 14 | 15 | io.vertx.intro.first.MyFirstVerticle 16 | 17 | 18 | 19 | 20 | io.vertx 21 | vertx-core 22 | ${vertx.version} 23 | 24 | 25 | junit 26 | junit 27 | 4.13.1 28 | test 29 | 30 | 31 | io.vertx 32 | vertx-unit 33 | ${vertx.version} 34 | test 35 | 36 | 37 | 38 | 39 | 40 | 41 | maven-compiler-plugin 42 | 3.7.0 43 | 44 | 1.8 45 | 1.8 46 | 47 | 48 | 49 | io.fabric8 50 | vertx-maven-plugin 51 | ${vertx-maven-plugin.version} 52 | 53 | 54 | vmp 55 | 56 | initialize 57 | package 58 | 59 | 60 | 61 | 62 | true 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /post-1/src/main/java/io/vertx/intro/first/MyFirstVerticle.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.AbstractVerticle; 4 | import io.vertx.core.Future; 5 | 6 | public class MyFirstVerticle extends AbstractVerticle { 7 | 8 | @Override 9 | public void start(Future fut) { 10 | vertx 11 | .createHttpServer() 12 | .requestHandler(r -> 13 | r.response().end("

Hello from my first Vert.x application

")) 14 | .listen(8080, result -> { 15 | if (result.succeeded()) { 16 | fut.complete(); 17 | } else { 18 | fut.fail(result.cause()); 19 | } 20 | }); 21 | } 22 | } -------------------------------------------------------------------------------- /post-1/src/test/java/io/vertx/intro/first/MyFirstVerticleTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.Vertx; 4 | import io.vertx.ext.unit.Async; 5 | import io.vertx.ext.unit.TestContext; 6 | import io.vertx.ext.unit.junit.VertxUnitRunner; 7 | import org.junit.After; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | 12 | @RunWith(VertxUnitRunner.class) 13 | public class MyFirstVerticleTest { 14 | 15 | private Vertx vertx; 16 | 17 | @Before 18 | public void setUp(TestContext context) { 19 | vertx = Vertx.vertx(); 20 | vertx.deployVerticle(MyFirstVerticle.class.getName(), 21 | context.asyncAssertSuccess()); 22 | } 23 | 24 | @After 25 | public void tearDown(TestContext context) { 26 | vertx.close(context.asyncAssertSuccess()); 27 | } 28 | 29 | @Test 30 | public void testMyApplication(TestContext context) { 31 | final Async async = context.async(); 32 | 33 | vertx.createHttpClient().getNow(8080, "localhost", "/", 34 | response -> 35 | response.handler(body -> { 36 | context.assertTrue(body.toString().contains("Hello")); 37 | async.complete(); 38 | })); 39 | } 40 | } -------------------------------------------------------------------------------- /post-2/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.vertx.intro 8 | my-first-app 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.9.3 13 | 1.0.13 14 | 15 | io.vertx.intro.first.MyFirstVerticle 16 | 17 | 18 | 19 | 20 | io.vertx 21 | vertx-core 22 | ${vertx.version} 23 | 24 | 25 | io.vertx 26 | vertx-config 27 | ${vertx.version} 28 | 29 | 30 | junit 31 | junit 32 | 4.13.1 33 | test 34 | 35 | 36 | io.vertx 37 | vertx-unit 38 | ${vertx.version} 39 | test 40 | 41 | 42 | 43 | 44 | 45 | 46 | maven-compiler-plugin 47 | 3.7.0 48 | 49 | 1.8 50 | 1.8 51 | 52 | 53 | 54 | io.fabric8 55 | vertx-maven-plugin 56 | ${vertx-maven-plugin.version} 57 | 58 | 59 | vmp 60 | 61 | initialize 62 | package 63 | 64 | 65 | 66 | 67 | true 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /post-2/src/main/conf/my-application-conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "HTTP_PORT" : 8082 3 | } -------------------------------------------------------------------------------- /post-2/src/main/java/io/vertx/intro/first/MyFirstVerticle.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.config.ConfigRetriever; 4 | import io.vertx.core.AbstractVerticle; 5 | import io.vertx.core.Future; 6 | 7 | public class MyFirstVerticle extends AbstractVerticle { 8 | 9 | @Override 10 | public void start(Future fut) { 11 | ConfigRetriever retriever = ConfigRetriever.create(vertx); 12 | retriever.getConfig( 13 | config -> { 14 | if (config.failed()) { 15 | fut.fail(config.cause()); 16 | } else { 17 | vertx 18 | .createHttpServer() 19 | .requestHandler(r -> 20 | r.response().end("

Hello from my first Vert.x application

")) 21 | .listen(config.result().getInteger("HTTP_PORT", 8080), result -> { 22 | if (result.succeeded()) { 23 | fut.complete(); 24 | } else { 25 | fut.fail(result.cause()); 26 | } 27 | }); 28 | } 29 | } 30 | ); 31 | } 32 | } -------------------------------------------------------------------------------- /post-2/src/test/java/io/vertx/intro/first/MyFirstVerticleTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.DeploymentOptions; 4 | import io.vertx.core.Vertx; 5 | import io.vertx.core.json.JsonObject; 6 | import io.vertx.ext.unit.Async; 7 | import io.vertx.ext.unit.TestContext; 8 | import io.vertx.ext.unit.junit.VertxUnitRunner; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | 14 | import java.io.IOException; 15 | import java.net.ServerSocket; 16 | 17 | @RunWith(VertxUnitRunner.class) 18 | public class MyFirstVerticleTest { 19 | 20 | private Vertx vertx; 21 | private int port = 8081; 22 | 23 | @Before 24 | public void setUp(TestContext context) throws IOException { 25 | vertx = Vertx.vertx(); 26 | 27 | // Pick an available and random 28 | ServerSocket socket = new ServerSocket(0); 29 | port = socket.getLocalPort(); 30 | socket.close(); 31 | 32 | DeploymentOptions options = new DeploymentOptions() 33 | .setConfig(new JsonObject().put("HTTP_PORT", port)); 34 | vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess()); 35 | } 36 | 37 | @After 38 | public void tearDown(TestContext context) { 39 | vertx.close(context.asyncAssertSuccess()); 40 | } 41 | 42 | @Test 43 | public void testMyApplication(TestContext context) { 44 | final Async async = context.async(); 45 | 46 | vertx.createHttpClient().getNow(port, "localhost", "/", 47 | response -> 48 | response.handler(body -> { 49 | context.assertTrue(body.toString().contains("Hello")); 50 | async.complete(); 51 | })); 52 | } 53 | } -------------------------------------------------------------------------------- /post-3/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.vertx.intro 8 | my-first-app 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.9.4 13 | 1.0.13 14 | 15 | io.vertx.intro.first.MyFirstVerticle 16 | 17 | 18 | 19 | 20 | io.vertx 21 | vertx-core 22 | ${vertx.version} 23 | 24 | 25 | io.vertx 26 | vertx-config 27 | ${vertx.version} 28 | 29 | 30 | io.vertx 31 | vertx-web 32 | ${vertx.version} 33 | 34 | 35 | junit 36 | junit 37 | 4.13.1 38 | test 39 | 40 | 41 | io.vertx 42 | vertx-unit 43 | ${vertx.version} 44 | test 45 | 46 | 47 | 48 | 49 | 50 | 51 | maven-compiler-plugin 52 | 3.7.0 53 | 54 | 1.8 55 | 1.8 56 | 57 | 58 | 59 | io.fabric8 60 | vertx-maven-plugin 61 | ${vertx-maven-plugin.version} 62 | 63 | 64 | vmp 65 | 66 | initialize 67 | package 68 | 69 | 70 | 71 | 72 | true 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /post-3/src/main/conf/my-application-conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "HTTP_PORT" : 8082 3 | } -------------------------------------------------------------------------------- /post-3/src/main/java/io/vertx/intro/first/Article.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | public class Article { 7 | 8 | private static final AtomicInteger COUNTER = new AtomicInteger(); 9 | 10 | private final int id; 11 | 12 | private String title; 13 | 14 | private String url; 15 | 16 | public Article(String title, String url) { 17 | this.id = COUNTER.getAndIncrement(); 18 | this.title = title; 19 | this.url = url; 20 | } 21 | 22 | public Article() { 23 | this.id = COUNTER.getAndIncrement(); 24 | } 25 | 26 | public int getId() { 27 | return id; 28 | } 29 | 30 | public String getTitle() { 31 | return title; 32 | } 33 | 34 | public Article setTitle(String title) { 35 | this.title = title; 36 | return this; 37 | } 38 | 39 | public String getUrl() { 40 | return url; 41 | } 42 | 43 | public Article setUrl(String url) { 44 | this.url = url; 45 | return this; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /post-3/src/main/java/io/vertx/intro/first/MyFirstVerticle.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.config.ConfigRetriever; 4 | import io.vertx.core.AbstractVerticle; 5 | import io.vertx.core.Future; 6 | import io.vertx.core.http.HttpServerResponse; 7 | import io.vertx.core.json.Json; 8 | import io.vertx.core.json.JsonObject; 9 | import io.vertx.ext.web.Router; 10 | import io.vertx.ext.web.RoutingContext; 11 | import io.vertx.ext.web.handler.BodyHandler; 12 | import io.vertx.ext.web.handler.StaticHandler; 13 | 14 | import java.util.LinkedHashMap; 15 | import java.util.Map; 16 | 17 | public class MyFirstVerticle extends AbstractVerticle { 18 | 19 | // Store our readingList 20 | private Map readingList = new LinkedHashMap<>(); 21 | 22 | @Override 23 | public void start(Future fut) { 24 | // Populate our set of article 25 | createSomeData(); 26 | 27 | // Create a router object. 28 | Router router = Router.router(vertx); 29 | 30 | // Bind "/" to our hello message - so we are still compatible. 31 | router.route("/").handler(routingContext -> { 32 | HttpServerResponse response = routingContext.response(); 33 | response 34 | .putHeader("content-type", "text/html") 35 | .end("

Hello from my first Vert.x 3 application

"); 36 | }); 37 | // Serve static resources from the /assets directory 38 | router.route("/assets/*").handler(StaticHandler.create("assets")); 39 | router.get("/api/articles").handler(this::getAll); 40 | router.get("/api/articles/:id").handler(this::getOne); 41 | router.route("/api/articles*").handler(BodyHandler.create()); 42 | router.post("/api/articles").handler(this::addOne); 43 | router.delete("/api/articles/:id").handler(this::deleteOne); 44 | router.put("/api/articles/:id").handler(this::updateOne); 45 | 46 | 47 | ConfigRetriever retriever = ConfigRetriever.create(vertx); 48 | retriever.getConfig( 49 | config -> { 50 | if (config.failed()) { 51 | fut.fail(config.cause()); 52 | } else { 53 | // Create the HTTP server and pass the "accept" method to the request handler. 54 | vertx 55 | .createHttpServer() 56 | .requestHandler(router::accept) 57 | .listen( 58 | // Retrieve the port from the configuration, 59 | // default to 8080. 60 | config.result().getInteger("HTTP_PORT", 8080), 61 | result -> { 62 | if (result.succeeded()) { 63 | fut.complete(); 64 | } else { 65 | fut.fail(result.cause()); 66 | } 67 | } 68 | ); 69 | } 70 | } 71 | ); 72 | } 73 | 74 | 75 | // Create a readingList 76 | private void createSomeData() { 77 | Article article1 = new Article("Fallacies of distributed computing", "https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing"); 78 | readingList.put(article1.getId(), article1); 79 | Article article2 = new Article("Reactive Manifesto", "https://www.reactivemanifesto.org/"); 80 | readingList.put(article2.getId(), article2); 81 | } 82 | 83 | private void getAll(RoutingContext routingContext) { 84 | routingContext.response() 85 | .putHeader("content-type", "application/json; charset=utf-8") 86 | .end(Json.encodePrettily(readingList.values())); 87 | } 88 | 89 | private void addOne(RoutingContext routingContext) { 90 | Article article = routingContext.getBodyAsJson().mapTo(Article.class); 91 | readingList.put(article.getId(), article); 92 | routingContext.response() 93 | .setStatusCode(201) 94 | .putHeader("content-type", "application/json; charset=utf-8") 95 | .end(Json.encodePrettily(article)); 96 | } 97 | 98 | private void deleteOne(RoutingContext routingContext) { 99 | String id = routingContext.request().getParam("id"); 100 | try { 101 | Integer idAsInteger = Integer.valueOf(id); 102 | readingList.remove(idAsInteger); 103 | routingContext.response().setStatusCode(204).end(); 104 | } catch (NumberFormatException e) { 105 | routingContext.response().setStatusCode(400).end(); 106 | } 107 | } 108 | 109 | 110 | private void getOne(RoutingContext routingContext) { 111 | String id = routingContext.request().getParam("id"); 112 | try { 113 | Integer idAsInteger = Integer.valueOf(id); 114 | Article article = readingList.get(idAsInteger); 115 | if (article == null) { 116 | // Not found 117 | routingContext.response().setStatusCode(404).end(); 118 | } else { 119 | routingContext.response() 120 | .setStatusCode(200) 121 | .putHeader("content-type", "application/json; charset=utf-8") 122 | .end(Json.encodePrettily(article)); 123 | } 124 | } catch (NumberFormatException e) { 125 | routingContext.response().setStatusCode(400).end(); 126 | } 127 | } 128 | 129 | private void updateOne(RoutingContext routingContext) { 130 | String id = routingContext.request().getParam("id"); 131 | try { 132 | Integer idAsInteger = Integer.valueOf(id); 133 | Article article = readingList.get(idAsInteger); 134 | if (article == null) { 135 | // Not found 136 | routingContext.response().setStatusCode(404).end(); 137 | } else { 138 | JsonObject body = routingContext.getBodyAsJson(); 139 | article.setTitle(body.getString("title")).setUrl(body.getString("url")); 140 | readingList.put(idAsInteger, article); 141 | routingContext.response() 142 | .setStatusCode(200) 143 | .putHeader("content-type", "application/json; charset=utf-8") 144 | .end(Json.encodePrettily(article)); 145 | } 146 | } catch (NumberFormatException e) { 147 | routingContext.response().setStatusCode(400).end(); 148 | } 149 | 150 | } 151 | 152 | } -------------------------------------------------------------------------------- /post-3/src/main/resources/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | My Reading List 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |

My Reading List

15 | 16 |

Just an example of simple CRUD application developed using Eclipse Vert.x and Vertx Web.

17 |
18 | 42 |
43 | 135 | 161 | 162 | -------------------------------------------------------------------------------- /post-3/src/test/java/io/vertx/intro/first/MyFirstVerticleTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.DeploymentOptions; 4 | import io.vertx.core.Vertx; 5 | import io.vertx.core.json.JsonObject; 6 | import io.vertx.ext.unit.Async; 7 | import io.vertx.ext.unit.TestContext; 8 | import io.vertx.ext.unit.junit.VertxUnitRunner; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | import org.junit.runner.RunWith; 13 | 14 | import java.io.IOException; 15 | import java.net.ServerSocket; 16 | 17 | @RunWith(VertxUnitRunner.class) 18 | public class MyFirstVerticleTest { 19 | 20 | private Vertx vertx; 21 | private int port = 8081; 22 | 23 | @Before 24 | public void setUp(TestContext context) throws IOException { 25 | vertx = Vertx.vertx(); 26 | 27 | // Pick an available and random 28 | ServerSocket socket = new ServerSocket(0); 29 | port = socket.getLocalPort(); 30 | socket.close(); 31 | 32 | DeploymentOptions options = new DeploymentOptions() 33 | .setConfig(new JsonObject().put("HTTP_PORT", port)); 34 | vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess()); 35 | } 36 | 37 | @After 38 | public void tearDown(TestContext context) { 39 | vertx.close(context.asyncAssertSuccess()); 40 | } 41 | 42 | @Test 43 | public void testMyApplication(TestContext context) { 44 | final Async async = context.async(); 45 | 46 | vertx.createHttpClient().getNow(port, "localhost", "/", 47 | response -> 48 | response.handler(body -> { 49 | context.assertTrue(body.toString().contains("Hello")); 50 | async.complete(); 51 | })); 52 | } 53 | } -------------------------------------------------------------------------------- /post-4/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.vertx.intro 8 | my-first-app 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.9.4 13 | 1.0.13 14 | 15 | io.vertx.intro.first.MyFirstVerticle 16 | 17 | 18 | 19 | 20 | io.vertx 21 | vertx-core 22 | ${vertx.version} 23 | 24 | 25 | io.vertx 26 | vertx-config 27 | ${vertx.version} 28 | 29 | 30 | io.vertx 31 | vertx-web 32 | ${vertx.version} 33 | 34 | 35 | io.vertx 36 | vertx-jdbc-client 37 | ${vertx.version} 38 | 39 | 40 | org.postgresql 41 | postgresql 42 | 42.3.3 43 | 44 | 45 | junit 46 | junit 47 | 4.13.1 48 | test 49 | 50 | 51 | io.vertx 52 | vertx-unit 53 | ${vertx.version} 54 | test 55 | 56 | 57 | org.hsqldb 58 | hsqldb 59 | 2.4.0 60 | test 61 | 62 | 63 | 64 | 65 | 66 | 67 | maven-compiler-plugin 68 | 3.7.0 69 | 70 | 1.8 71 | 1.8 72 | 73 | 74 | 75 | io.fabric8 76 | vertx-maven-plugin 77 | ${vertx-maven-plugin.version} 78 | 79 | 80 | vmp 81 | 82 | initialize 83 | package 84 | 85 | 86 | 87 | 88 | true 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /post-4/src/main/conf/my-application-conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "HTTP_PORT": 8082, 3 | "url": "jdbc:postgresql://localhost:5432/my_read_list", 4 | "driver_class": "org.postgresql.Driver", 5 | "user": "user", 6 | "password": "password" 7 | } -------------------------------------------------------------------------------- /post-4/src/main/java/io/vertx/intro/first/ActionHelper.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.AsyncResult; 4 | import io.vertx.core.Handler; 5 | import io.vertx.core.json.Json; 6 | import io.vertx.ext.web.RoutingContext; 7 | 8 | import java.util.List; 9 | import java.util.NoSuchElementException; 10 | 11 | /** 12 | * Some helper code. 13 | */ 14 | public class ActionHelper { 15 | 16 | /** 17 | * Returns a handler writing the received {@link AsyncResult} to the routing context and setting the HTTP status to 18 | * the given status. 19 | * @param context the routing context 20 | * @param status the status 21 | * @return the handler 22 | */ 23 | private static Handler> writeJsonResponse(RoutingContext context, int status) { 24 | return ar -> { 25 | if (ar.failed()) { 26 | if (ar.cause() instanceof NoSuchElementException) { 27 | context.response().setStatusCode(404).end(ar.cause().getMessage()); 28 | } else { 29 | context.fail(ar.cause()); 30 | } 31 | } else { 32 | context.response().setStatusCode(status) 33 | .putHeader("content-type", "application/json; charset=utf-8") 34 | .end(Json.encodePrettily(ar.result())); 35 | } 36 | }; 37 | } 38 | 39 | static Handler> ok(RoutingContext rc) { 40 | return writeJsonResponse(rc,200); 41 | } 42 | 43 | static Handler> created(RoutingContext rc) { 44 | return writeJsonResponse(rc,201); 45 | } 46 | 47 | static Handler> noContent(RoutingContext rc) { 48 | return ar -> { 49 | if (ar.failed()) { 50 | if (ar.cause() instanceof NoSuchElementException) { 51 | rc.response().setStatusCode(404).end(ar.cause().getMessage()); 52 | } else { 53 | rc.fail(ar.cause()); 54 | } 55 | } else { 56 | rc.response().setStatusCode(204).end(); 57 | } 58 | }; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /post-4/src/main/java/io/vertx/intro/first/Article.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | 4 | import io.vertx.core.json.JsonObject; 5 | 6 | public class Article { 7 | 8 | private long id = -1; 9 | 10 | private String title; 11 | 12 | private String url; 13 | 14 | public Article(String title, String url) { 15 | this.title = title; 16 | this.url = url; 17 | } 18 | 19 | public Article(long id, String title, String url) { 20 | this.id = id; 21 | this.title = title; 22 | this.url = url; 23 | } 24 | 25 | public Article() { 26 | 27 | } 28 | 29 | public Article(JsonObject json) { 30 | this( 31 | json.getInteger("id", -1), 32 | json.getString("title"), 33 | json.getString("url") 34 | ); 35 | } 36 | 37 | public long getId() { 38 | return id; 39 | } 40 | 41 | public String getTitle() { 42 | return title; 43 | } 44 | 45 | public Article setTitle(String title) { 46 | this.title = title; 47 | return this; 48 | } 49 | 50 | public String getUrl() { 51 | return url; 52 | } 53 | 54 | public Article setUrl(String url) { 55 | this.url = url; 56 | return this; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /post-4/src/main/java/io/vertx/intro/first/MyFirstVerticle.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.config.ConfigRetriever; 4 | import io.vertx.core.AbstractVerticle; 5 | import io.vertx.core.CompositeFuture; 6 | import io.vertx.core.Future; 7 | import io.vertx.core.http.HttpServerResponse; 8 | import io.vertx.core.json.JsonArray; 9 | import io.vertx.core.json.JsonObject; 10 | import io.vertx.ext.jdbc.JDBCClient; 11 | import io.vertx.ext.sql.SQLConnection; 12 | import io.vertx.ext.sql.SQLOptions; 13 | import io.vertx.ext.sql.UpdateResult; 14 | import io.vertx.ext.web.Router; 15 | import io.vertx.ext.web.RoutingContext; 16 | import io.vertx.ext.web.handler.BodyHandler; 17 | import io.vertx.ext.web.handler.StaticHandler; 18 | 19 | import java.util.List; 20 | import java.util.NoSuchElementException; 21 | import java.util.stream.Collectors; 22 | 23 | import static io.vertx.intro.first.ActionHelper.*; 24 | 25 | public class MyFirstVerticle extends AbstractVerticle { 26 | 27 | private JDBCClient jdbc; 28 | 29 | @Override 30 | public void start(Future fut) { 31 | 32 | // Create a router object. 33 | Router router = Router.router(vertx); 34 | 35 | // Bind "/" to our hello message - so we are still compatible. 36 | router.route("/").handler(routingContext -> { 37 | HttpServerResponse response = routingContext.response(); 38 | response 39 | .putHeader("content-type", "text/html") 40 | .end("

Hello from my first Vert.x 3 application

"); 41 | }); 42 | 43 | // Serve static resources from the /assets directory 44 | router.route("/assets/*").handler(StaticHandler.create("assets")); 45 | router.get("/api/articles").handler(this::getAll); 46 | router.get("/api/articles/:id").handler(this::getOne); 47 | router.route("/api/articles*").handler(BodyHandler.create()); 48 | router.post("/api/articles").handler(this::addOne); 49 | router.delete("/api/articles/:id").handler(this::deleteOne); 50 | router.put("/api/articles/:id").handler(this::updateOne); 51 | 52 | ConfigRetriever retriever = ConfigRetriever.create(vertx); 53 | 54 | // Start sequence: 55 | // 1 - Retrieve the configuration 56 | // |- 2 - Create the JDBC client 57 | // |- 3 - Connect to the database (retrieve a connection) 58 | // |- 4 - Create table if needed 59 | // |- 5 - Add some data if needed 60 | // |- 6 - Close connection when done 61 | // |- 7 - Start HTTP server 62 | // |- 9 - we are done! 63 | 64 | ConfigRetriever.getConfigAsFuture(retriever) 65 | .compose(config -> { 66 | jdbc = JDBCClient.createShared(vertx, config, "My-Reading-List"); 67 | 68 | return connect() 69 | .compose(connection -> { 70 | Future future = Future.future(); 71 | createTableIfNeeded(connection) 72 | .compose(this::createSomeDataIfNone) 73 | .setHandler(x -> { 74 | connection.close(); 75 | future.handle(x.mapEmpty()); 76 | }); 77 | return future; 78 | }) 79 | .compose(v -> createHttpServer(config, router)); 80 | 81 | }) 82 | .setHandler(fut); 83 | } 84 | 85 | private Future createHttpServer(JsonObject config, Router router) { 86 | Future future = Future.future(); 87 | vertx 88 | .createHttpServer() 89 | .requestHandler(router::accept) 90 | .listen( 91 | config.getInteger("HTTP_PORT", 8080), 92 | res -> future.handle(res.mapEmpty()) 93 | ); 94 | return future; 95 | } 96 | 97 | private Future connect() { 98 | Future future = Future.future(); 99 | jdbc.getConnection(ar -> 100 | future.handle(ar.map(c -> 101 | c.setOptions(new SQLOptions().setAutoGeneratedKeys(true)) 102 | ) 103 | ) 104 | ); 105 | return future; 106 | } 107 | 108 | private Future
insert(SQLConnection connection, Article article, boolean closeConnection) { 109 | Future
future = Future.future(); 110 | String sql = "INSERT INTO Articles (title, url) VALUES (?, ?)"; 111 | connection.updateWithParams(sql, 112 | new JsonArray().add(article.getTitle()).add(article.getUrl()), 113 | ar -> { 114 | if (closeConnection) { 115 | connection.close(); 116 | } 117 | future.handle( 118 | ar.map(res -> new Article(res.getKeys().getLong(0), article.getTitle(), article.getUrl())) 119 | ); 120 | } 121 | ); 122 | return future; 123 | } 124 | 125 | private Future> query(SQLConnection connection) { 126 | Future> future = Future.future(); 127 | connection.query("SELECT * FROM articles", result -> { 128 | connection.close(); 129 | future.handle( 130 | result.map(rs -> rs.getRows().stream().map(Article::new).collect(Collectors.toList())) 131 | ); 132 | } 133 | ); 134 | return future; 135 | } 136 | 137 | private Future
queryOne(SQLConnection connection, String id) { 138 | Future
future = Future.future(); 139 | String sql = "SELECT * FROM articles WHERE id = ?"; 140 | connection.queryWithParams(sql, new JsonArray().add(Integer.valueOf(id)), result -> { 141 | connection.close(); 142 | future.handle( 143 | result.map(rs -> { 144 | List rows = rs.getRows(); 145 | if (rows.size() == 0) { 146 | throw new NoSuchElementException("No article with id " + id); 147 | } else { 148 | JsonObject row = rows.get(0); 149 | return new Article(row); 150 | } 151 | }) 152 | ); 153 | }); 154 | return future; 155 | } 156 | 157 | private Future update(SQLConnection connection, String id, Article article) { 158 | Future future = Future.future(); 159 | String sql = "UPDATE articles SET title = ?, url = ? WHERE id = ?"; 160 | connection.updateWithParams(sql, new JsonArray().add(article.getTitle()).add(article.getUrl()) 161 | .add(Integer.valueOf(id)), 162 | ar -> { 163 | connection.close(); 164 | if (ar.failed()) { 165 | future.fail(ar.cause()); 166 | } else { 167 | UpdateResult ur = ar.result(); 168 | if (ur.getUpdated() == 0) { 169 | future.fail(new NoSuchElementException("No article with id " + id)); 170 | } else { 171 | future.complete(); 172 | } 173 | } 174 | }); 175 | return future; 176 | } 177 | 178 | private Future delete(SQLConnection connection, String id) { 179 | Future future = Future.future(); 180 | String sql = "DELETE FROM Articles WHERE id = ?"; 181 | connection.updateWithParams(sql, 182 | new JsonArray().add(Integer.valueOf(id)), 183 | ar -> { 184 | connection.close(); 185 | if (ar.failed()) { 186 | future.fail(ar.cause()); 187 | } else { 188 | if (ar.result().getUpdated() == 0) { 189 | future.fail(new NoSuchElementException("Unknown article " + id)); 190 | } else { 191 | future.complete(); 192 | } 193 | } 194 | } 195 | ); 196 | return future; 197 | } 198 | 199 | private Future createTableIfNeeded(SQLConnection connection) { 200 | Future future = Future.future(); 201 | vertx.fileSystem().readFile("tables.sql", ar -> { 202 | if (ar.failed()) { 203 | future.fail(ar.cause()); 204 | } else { 205 | connection.execute(ar.result().toString(), 206 | ar2 -> future.handle(ar2.map(connection)) 207 | ); 208 | } 209 | }); 210 | return future; 211 | } 212 | 213 | private Future createSomeDataIfNone(SQLConnection connection) { 214 | Future future = Future.future(); 215 | connection.query("SELECT * FROM Articles", select -> { 216 | if (select.failed()) { 217 | future.fail(select.cause()); 218 | } else { 219 | if (select.result().getResults().isEmpty()) { 220 | Article article1 = new Article("Fallacies of distributed computing", 221 | "https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing"); 222 | Article article2 = new Article("Reactive Manifesto", 223 | "https://www.reactivemanifesto.org/"); 224 | Future
insertion1 = insert(connection, article1, false); 225 | Future
insertion2 = insert(connection, article2, false); 226 | CompositeFuture.all(insertion1, insertion2) 227 | .setHandler(r -> future.handle(r.map(connection))); 228 | } else { 229 | future.complete(connection); 230 | } 231 | } 232 | }); 233 | return future; 234 | } 235 | 236 | 237 | // ---- HTTP Actions ---- 238 | 239 | private void getAll(RoutingContext rc) { 240 | connect() 241 | .compose(this::query) 242 | .setHandler(ok(rc)); 243 | } 244 | 245 | private void addOne(RoutingContext rc) { 246 | Article article = rc.getBodyAsJson().mapTo(Article.class); 247 | connect() 248 | .compose(connection -> insert(connection, article, true)) 249 | .setHandler(created(rc)); 250 | } 251 | 252 | 253 | private void deleteOne(RoutingContext rc) { 254 | String id = rc.pathParam("id"); 255 | connect() 256 | .compose(connection -> delete(connection, id)) 257 | .setHandler(noContent(rc)); 258 | } 259 | 260 | 261 | private void getOne(RoutingContext rc) { 262 | String id = rc.pathParam("id"); 263 | connect() 264 | .compose(connection -> queryOne(connection, id)) 265 | .setHandler(ok(rc)); 266 | } 267 | 268 | private void updateOne(RoutingContext rc) { 269 | String id = rc.request().getParam("id"); 270 | Article article = rc.getBodyAsJson().mapTo(Article.class); 271 | connect() 272 | .compose(connection -> update(connection, id, article)) 273 | .setHandler(noContent(rc)); 274 | } 275 | 276 | } -------------------------------------------------------------------------------- /post-4/src/main/resources/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | My Reading List 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |

My Reading List

15 | 16 |

Just an example of simple CRUD application developed using Eclipse Vert.x and Vertx Web.

17 |
18 | 42 |
43 | 135 | 161 | 162 | -------------------------------------------------------------------------------- /post-4/src/main/resources/tables.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS Articles (id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, url VARCHAR(200) NOT NULL) -------------------------------------------------------------------------------- /post-4/src/test/java/io/vertx/intro/first/MyFirstVerticleTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.DeploymentOptions; 4 | import io.vertx.core.Vertx; 5 | import io.vertx.core.json.Json; 6 | import io.vertx.core.json.JsonObject; 7 | import io.vertx.ext.unit.Async; 8 | import io.vertx.ext.unit.TestContext; 9 | import io.vertx.ext.unit.junit.VertxUnitRunner; 10 | import org.junit.After; 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.junit.runner.RunWith; 14 | 15 | import java.io.IOException; 16 | import java.net.ServerSocket; 17 | 18 | @RunWith(VertxUnitRunner.class) 19 | public class MyFirstVerticleTest { 20 | 21 | private Vertx vertx; 22 | private int port = 8081; 23 | 24 | @Before 25 | public void setUp(TestContext context) throws IOException { 26 | vertx = Vertx.vertx(); 27 | 28 | // Pick an available and random 29 | ServerSocket socket = new ServerSocket(0); 30 | port = socket.getLocalPort(); 31 | socket.close(); 32 | 33 | DeploymentOptions options = new DeploymentOptions() 34 | .setConfig(new JsonObject() 35 | .put("HTTP_PORT", port) 36 | .put("url", "jdbc:hsqldb:mem:test?shutdown=true") 37 | .put("driver_class", "org.hsqldb.jdbcDriver") 38 | ); 39 | vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess()); 40 | } 41 | 42 | @After 43 | public void tearDown(TestContext context) { 44 | vertx.close(context.asyncAssertSuccess()); 45 | } 46 | 47 | @Test 48 | public void testMyApplication(TestContext context) { 49 | final Async async = context.async(); 50 | 51 | vertx.createHttpClient().getNow(port, "localhost", "/", 52 | response -> 53 | response.handler(body -> { 54 | context.assertTrue(body.toString().contains("Hello")); 55 | async.complete(); 56 | })); 57 | } 58 | 59 | @Test 60 | public void checkThatTheIndexPageIsServed(TestContext context) { 61 | Async async = context.async(); 62 | vertx.createHttpClient().getNow(port, "localhost", "/assets/index.html", response -> { 63 | context.assertEquals(response.statusCode(), 200); 64 | context.assertEquals(response.headers().get("Content-Type"), "text/html;charset=UTF-8"); 65 | response.bodyHandler(body -> { 66 | context.assertTrue(body.toString().contains("My Reading List")); 67 | async.complete(); 68 | }); 69 | }); 70 | } 71 | 72 | @Test 73 | public void checkThatWeCanAdd(TestContext context) { 74 | Async async = context.async(); 75 | final String json = Json.encodePrettily(new Article("Some title", "Some url")); 76 | vertx.createHttpClient().post(port, "localhost", "/api/articles") 77 | .putHeader("Content-Type", "application/json") 78 | .putHeader("Content-Length", Integer.toString(json.length())) 79 | .handler(response -> { 80 | context.assertEquals(response.statusCode(), 201); 81 | context.assertTrue(response.headers().get("content-type").contains("application/json")); 82 | response.bodyHandler(body -> { 83 | Article article = Json.decodeValue(body.toString(), Article.class); 84 | context.assertEquals(article.getTitle(), "Some title"); 85 | context.assertEquals(article.getUrl(), "Some url"); 86 | context.assertNotNull(article.getId()); 87 | async.complete(); 88 | }); 89 | }) 90 | .write(json) 91 | .end(); 92 | } 93 | } -------------------------------------------------------------------------------- /post-4/src/test/resources/tables.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS Articles (id INTEGER IDENTITY, title VARCHAR(200), url varchar(200)) -------------------------------------------------------------------------------- /post-5/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | io.vertx.intro 8 | my-first-app 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 3.9.4 13 | 1.0.13 14 | 15 | io.vertx.intro.first.MyFirstVerticle 16 | 17 | 18 | 19 | 20 | io.vertx 21 | vertx-core 22 | ${vertx.version} 23 | 24 | 25 | io.vertx 26 | vertx-rx-java2 27 | ${vertx.version} 28 | 29 | 30 | io.vertx 31 | vertx-config 32 | ${vertx.version} 33 | 34 | 35 | io.vertx 36 | vertx-web 37 | ${vertx.version} 38 | 39 | 40 | io.vertx 41 | vertx-jdbc-client 42 | ${vertx.version} 43 | 44 | 45 | org.postgresql 46 | postgresql 47 | 42.3.3 48 | 49 | 50 | junit 51 | junit 52 | 4.13.1 53 | test 54 | 55 | 56 | io.vertx 57 | vertx-unit 58 | ${vertx.version} 59 | test 60 | 61 | 62 | org.hsqldb 63 | hsqldb 64 | 2.4.0 65 | test 66 | 67 | 68 | 69 | 70 | 71 | 72 | maven-compiler-plugin 73 | 3.7.0 74 | 75 | 1.8 76 | 1.8 77 | 78 | 79 | 80 | io.fabric8 81 | vertx-maven-plugin 82 | ${vertx-maven-plugin.version} 83 | 84 | 85 | vmp 86 | 87 | initialize 88 | package 89 | 90 | 91 | 92 | 93 | true 94 | 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /post-5/src/main/conf/my-application-conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "HTTP_PORT": 8082, 3 | "url": "jdbc:postgresql://localhost:5432/my_read_list", 4 | "driver_class": "org.postgresql.Driver", 5 | "user": "user", 6 | "password": "password" 7 | } -------------------------------------------------------------------------------- /post-5/src/main/java/io/vertx/intro/first/ActionHelper.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.reactivex.functions.Action; 4 | import io.reactivex.functions.BiConsumer; 5 | import io.reactivex.functions.Consumer; 6 | import io.vertx.core.AsyncResult; 7 | import io.vertx.core.json.Json; 8 | import io.vertx.reactivex.ext.web.RoutingContext; 9 | 10 | import java.util.NoSuchElementException; 11 | 12 | /** 13 | * Some helper code. 14 | */ 15 | public class ActionHelper { 16 | 17 | /** 18 | * Returns a bi-consumer writing the received {@link AsyncResult} to the routing context and setting 19 | * the HTTP status to the given status. 20 | * 21 | * @param context the routing context 22 | * @param status the status 23 | * @return the bi-consumer 24 | */ 25 | private static BiConsumer writeJsonResponse(RoutingContext context, int status) { 26 | return (res, err) -> { 27 | if (err != null) { 28 | if (err instanceof NoSuchElementException) { 29 | context.response().setStatusCode(404).end(err.getMessage()); 30 | } else { 31 | context.fail(err); 32 | } 33 | } else { 34 | context.response().setStatusCode(status) 35 | .putHeader("content-type", "application/json; charset=utf-8") 36 | .end(Json.encodePrettily(res)); 37 | } 38 | }; 39 | } 40 | 41 | static BiConsumer ok(RoutingContext rc) { 42 | return writeJsonResponse(rc, 200); 43 | } 44 | 45 | static BiConsumer created(RoutingContext rc) { 46 | return writeJsonResponse(rc, 201); 47 | } 48 | 49 | static Action noContent(RoutingContext rc) { 50 | return () -> rc.response().setStatusCode(204).end(); 51 | } 52 | 53 | static Consumer onError(RoutingContext rc) { 54 | return err -> { 55 | if (err instanceof NoSuchElementException) { 56 | rc.response().setStatusCode(404).end(err.getMessage()); 57 | } else { 58 | rc.fail(err); 59 | } 60 | }; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /post-5/src/main/java/io/vertx/intro/first/Article.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | 4 | import io.vertx.core.json.JsonObject; 5 | 6 | public class Article { 7 | 8 | private long id = -1; 9 | 10 | private String title; 11 | 12 | private String url; 13 | 14 | public Article(String title, String url) { 15 | this.title = title; 16 | this.url = url; 17 | } 18 | 19 | public Article(long id, String title, String url) { 20 | this.id = id; 21 | this.title = title; 22 | this.url = url; 23 | } 24 | 25 | public Article() { 26 | 27 | } 28 | 29 | public Article(JsonObject json) { 30 | this( 31 | json.getInteger("id", -1), 32 | json.getString("title"), 33 | json.getString("url") 34 | ); 35 | } 36 | 37 | public long getId() { 38 | return id; 39 | } 40 | 41 | public String getTitle() { 42 | return title; 43 | } 44 | 45 | public Article setTitle(String title) { 46 | this.title = title; 47 | return this; 48 | } 49 | 50 | public String getUrl() { 51 | return url; 52 | } 53 | 54 | public Article setUrl(String url) { 55 | this.url = url; 56 | return this; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /post-5/src/main/java/io/vertx/intro/first/MyFirstVerticle.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.reactivex.Completable; 4 | import io.reactivex.Single; 5 | import io.vertx.core.Future; 6 | import io.vertx.core.json.JsonArray; 7 | import io.vertx.core.json.JsonObject; 8 | import io.vertx.ext.sql.SQLOptions; 9 | import io.vertx.reactivex.CompletableHelper; 10 | import io.vertx.reactivex.config.ConfigRetriever; 11 | import io.vertx.reactivex.core.AbstractVerticle; 12 | import io.vertx.reactivex.core.buffer.Buffer; 13 | import io.vertx.reactivex.core.http.HttpServerResponse; 14 | import io.vertx.reactivex.ext.jdbc.JDBCClient; 15 | import io.vertx.reactivex.ext.sql.SQLConnection; 16 | import io.vertx.reactivex.ext.web.Router; 17 | import io.vertx.reactivex.ext.web.RoutingContext; 18 | import io.vertx.reactivex.ext.web.handler.BodyHandler; 19 | import io.vertx.reactivex.ext.web.handler.StaticHandler; 20 | 21 | import java.util.List; 22 | import java.util.NoSuchElementException; 23 | import java.util.stream.Collectors; 24 | 25 | import static io.vertx.intro.first.ActionHelper.*; 26 | 27 | public class MyFirstVerticle extends AbstractVerticle { 28 | 29 | private JDBCClient jdbc; 30 | 31 | @Override 32 | public void start(Future fut) { 33 | 34 | // Create a router object. 35 | Router router = Router.router(vertx); 36 | 37 | // Bind "/" to our hello message - so we are still compatible. 38 | router.route("/").handler(routingContext -> { 39 | HttpServerResponse response = routingContext.response(); 40 | response 41 | .putHeader("content-type", "text/html") 42 | .end("

Hello from my first Vert.x 3 application

"); 43 | }); 44 | 45 | // Serve static resources from the /assets directory 46 | router.route("/assets/*").handler(StaticHandler.create("assets")); 47 | router.get("/api/articles").handler(this::getAll); 48 | router.get("/api/articles/:id").handler(this::getOne); 49 | router.route("/api/articles*").handler(BodyHandler.create()); 50 | router.post("/api/articles").handler(this::addOne); 51 | router.delete("/api/articles/:id").handler(this::deleteOne); 52 | router.put("/api/articles/:id").handler(this::updateOne); 53 | 54 | ConfigRetriever retriever = ConfigRetriever.create(vertx); 55 | 56 | // Start sequence: 57 | // 1 - Retrieve the configuration 58 | // |- 2 - Create the JDBC client 59 | // |- 3 - Connect to the database (retrieve a connection) 60 | // |- 4 - Create table if needed 61 | // |- 5 - Add some data if needed 62 | // |- 6 - Close connection when done 63 | // |- 7 - Start HTTP server 64 | // |- 9 - we are done! 65 | 66 | retriever.rxGetConfig() 67 | .doOnSuccess(config -> 68 | jdbc = JDBCClient.createShared(vertx, config, "My-Reading-List")) 69 | .flatMap(config -> 70 | connect() 71 | .flatMap(connection -> 72 | this.createTableIfNeeded(connection) 73 | .flatMap(this::createSomeDataIfNone) 74 | .doAfterTerminate(connection::close) 75 | ) 76 | .map(x -> config) 77 | ) 78 | .flatMapCompletable(config -> createHttpServer(config, router)) 79 | .subscribe(CompletableHelper.toObserver(fut)); 80 | 81 | } 82 | 83 | private Completable createHttpServer(JsonObject config, Router router) { 84 | return vertx 85 | .createHttpServer() 86 | .requestHandler(router::accept) 87 | .rxListen(config.getInteger("HTTP_PORT", 8080)) 88 | .toCompletable(); 89 | } 90 | 91 | private Single connect() { 92 | return jdbc.rxGetConnection() 93 | .map(c -> c.setOptions(new SQLOptions().setAutoGeneratedKeys(true))); 94 | } 95 | 96 | private Single
insert(SQLConnection connection, Article article, boolean closeConnection) { 97 | String sql = "INSERT INTO Articles (title, url) VALUES (?, ?)"; 98 | return connection 99 | .rxUpdateWithParams(sql, new JsonArray().add(article.getTitle()).add(article.getUrl())) 100 | .map(res -> new Article(res.getKeys().getLong(0), article.getTitle(), article.getUrl())) 101 | .doFinally(() -> { 102 | if (closeConnection) { 103 | connection.close(); 104 | } 105 | }); 106 | } 107 | 108 | private Single> query(SQLConnection connection) { 109 | return connection.rxQuery("SELECT * FROM articles") 110 | .map(rs -> rs.getRows().stream().map(Article::new).collect(Collectors.toList())) 111 | .doFinally(connection::close); 112 | } 113 | 114 | private Single
queryOne(SQLConnection connection, String id) { 115 | String sql = "SELECT * FROM articles WHERE id = ?"; 116 | return connection.rxQueryWithParams(sql, new JsonArray().add(Integer.valueOf(id))) 117 | .doFinally(connection::close) 118 | .map(rs -> { 119 | List rows = rs.getRows(); 120 | if (rows.size() == 0) { 121 | throw new NoSuchElementException("No article with id " + id); 122 | } else { 123 | JsonObject row = rows.get(0); 124 | return new Article(row); 125 | } 126 | }); 127 | } 128 | 129 | private Completable update(SQLConnection connection, String id, Article article) { 130 | String sql = "UPDATE articles SET title = ?, url = ? WHERE id = ?"; 131 | JsonArray params = new JsonArray().add(article.getTitle()) 132 | .add(article.getUrl()) 133 | .add(Integer.valueOf(id)); 134 | return connection.rxUpdateWithParams(sql, params) 135 | .flatMapCompletable(ur -> 136 | ur.getUpdated() == 0 ? 137 | Completable 138 | .error(new NoSuchElementException("No article with id " + id)) 139 | : Completable.complete() 140 | ) 141 | .doFinally(connection::close); 142 | } 143 | 144 | private Completable delete(SQLConnection connection, String id) { 145 | String sql = "DELETE FROM Articles WHERE id = ?"; 146 | JsonArray params = new JsonArray().add(Integer.valueOf(id)); 147 | return connection.rxUpdateWithParams(sql, params) 148 | .doFinally(connection::close) 149 | .flatMapCompletable(ur -> 150 | ur.getUpdated() == 0 ? 151 | Completable 152 | .error(new NoSuchElementException("No article with id " + id)) 153 | : Completable.complete() 154 | ); 155 | } 156 | 157 | private Single createTableIfNeeded(SQLConnection connection) { 158 | return vertx.fileSystem().rxReadFile("tables.sql") 159 | .map(Buffer::toString) 160 | .flatMapCompletable(connection::rxExecute) 161 | .toSingleDefault(connection); 162 | } 163 | 164 | private Single createSomeDataIfNone(SQLConnection connection) { 165 | return connection.rxQuery("SELECT * FROM Articles") 166 | .flatMap(rs -> { 167 | if (rs.getResults().isEmpty()) { 168 | Article article1 = new Article("Fallacies of distributed computing", 169 | "https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing"); 170 | Article article2 = new Article("Reactive Manifesto", 171 | "https://www.reactivemanifesto.org/"); 172 | return Single.zip( 173 | insert(connection, article1, false), 174 | insert(connection, article2, false), 175 | (a1, a2) -> connection 176 | ); 177 | } else { 178 | return Single.just(connection); 179 | } 180 | }); 181 | } 182 | 183 | 184 | // ---- HTTP Actions ---- 185 | 186 | private void getAll(RoutingContext rc) { 187 | connect() 188 | .flatMap(this::query) 189 | .subscribe(ok(rc)); 190 | } 191 | 192 | private void addOne(RoutingContext rc) { 193 | Article article = rc.getBodyAsJson().mapTo(Article.class); 194 | connect() 195 | .flatMap(connection -> insert(connection, article, true)) 196 | .subscribe(created(rc)); 197 | } 198 | 199 | 200 | private void deleteOne(RoutingContext rc) { 201 | String id = rc.pathParam("id"); 202 | connect() 203 | .flatMapCompletable(connection -> delete(connection, id)) 204 | .subscribe(noContent(rc), onError(rc)); 205 | } 206 | 207 | 208 | private void getOne(RoutingContext rc) { 209 | String id = rc.pathParam("id"); 210 | connect() 211 | .flatMap(connection -> queryOne(connection, id)) 212 | .subscribe(ok(rc)); 213 | } 214 | 215 | private void updateOne(RoutingContext rc) { 216 | String id = rc.request().getParam("id"); 217 | Article article = rc.getBodyAsJson().mapTo(Article.class); 218 | connect() 219 | .flatMapCompletable(connection -> update(connection, id, article)) 220 | .subscribe(noContent(rc), onError(rc)); 221 | } 222 | 223 | } -------------------------------------------------------------------------------- /post-5/src/main/resources/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | My Reading List 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |

My Reading List

15 | 16 |

Just an example of simple CRUD application developed using Eclipse Vert.x and Vertx Web.

17 |
18 | 42 |
43 | 135 | 161 | 162 | -------------------------------------------------------------------------------- /post-5/src/main/resources/tables.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS articles (id SERIAL PRIMARY KEY, title VARCHAR(200) NOT NULL, url VARCHAR(200) NOT NULL) -------------------------------------------------------------------------------- /post-5/src/test/java/io/vertx/intro/first/MyFirstVerticleTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.intro.first; 2 | 3 | import io.vertx.core.DeploymentOptions; 4 | import io.vertx.core.Vertx; 5 | import io.vertx.core.json.Json; 6 | import io.vertx.core.json.JsonObject; 7 | import io.vertx.ext.unit.Async; 8 | import io.vertx.ext.unit.TestContext; 9 | import io.vertx.ext.unit.junit.VertxUnitRunner; 10 | import org.junit.After; 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.junit.runner.RunWith; 14 | 15 | import java.io.IOException; 16 | import java.net.ServerSocket; 17 | 18 | @RunWith(VertxUnitRunner.class) 19 | public class MyFirstVerticleTest { 20 | 21 | private Vertx vertx; 22 | private int port = 8081; 23 | 24 | @Before 25 | public void setUp(TestContext context) throws IOException { 26 | vertx = Vertx.vertx(); 27 | 28 | // Pick an available and random 29 | ServerSocket socket = new ServerSocket(0); 30 | port = socket.getLocalPort(); 31 | socket.close(); 32 | 33 | DeploymentOptions options = new DeploymentOptions() 34 | .setConfig(new JsonObject() 35 | .put("HTTP_PORT", port) 36 | .put("url", "jdbc:hsqldb:mem:test?shutdown=true") 37 | .put("driver_class", "org.hsqldb.jdbcDriver") 38 | ); 39 | vertx.deployVerticle(MyFirstVerticle.class.getName(), options, context.asyncAssertSuccess()); 40 | } 41 | 42 | @After 43 | public void tearDown(TestContext context) { 44 | vertx.close(context.asyncAssertSuccess()); 45 | } 46 | 47 | @Test 48 | public void testMyApplication(TestContext context) { 49 | final Async async = context.async(); 50 | 51 | vertx.createHttpClient().getNow(port, "localhost", "/", 52 | response -> 53 | response.handler(body -> { 54 | context.assertTrue(body.toString().contains("Hello")); 55 | async.complete(); 56 | })); 57 | } 58 | 59 | @Test 60 | public void checkThatTheIndexPageIsServed(TestContext context) { 61 | Async async = context.async(); 62 | vertx.createHttpClient().getNow(port, "localhost", "/assets/index.html", response -> { 63 | context.assertEquals(response.statusCode(), 200); 64 | context.assertEquals(response.headers().get("Content-Type"), "text/html;charset=UTF-8"); 65 | response.bodyHandler(body -> { 66 | context.assertTrue(body.toString().contains("My Reading List")); 67 | async.complete(); 68 | }); 69 | }); 70 | } 71 | 72 | @Test 73 | public void checkThatWeCanAdd(TestContext context) { 74 | Async async = context.async(); 75 | final String json = Json.encodePrettily(new Article("Some title", "Some url")); 76 | vertx.createHttpClient().post(port, "localhost", "/api/articles") 77 | .putHeader("Content-Type", "application/json") 78 | .putHeader("Content-Length", Integer.toString(json.length())) 79 | .handler(response -> { 80 | context.assertEquals(response.statusCode(), 201); 81 | context.assertTrue(response.headers().get("content-type").contains("application/json")); 82 | response.bodyHandler(body -> { 83 | Article article = Json.decodeValue(body.toString(), Article.class); 84 | context.assertEquals(article.getTitle(), "Some title"); 85 | context.assertEquals(article.getUrl(), "Some url"); 86 | context.assertNotNull(article.getId()); 87 | async.complete(); 88 | }); 89 | }) 90 | .write(json) 91 | .end(); 92 | } 93 | } -------------------------------------------------------------------------------- /post-5/src/test/resources/tables.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS Articles (id INTEGER IDENTITY, title VARCHAR(200), url varchar(200)) --------------------------------------------------------------------------------