From 4ca7f901671527dc742746aa963ce91f945d0842 Mon Sep 17 00:00:00 2001 From: Julien Viet Date: Thu, 29 Nov 2018 18:58:20 +0100 Subject: [PATCH] Vert.x 4 initial module pruning - https://github.com/vert-x3/issues/issues/426 --- .editorconfig | 9 - .travis.yml | 1 - CONTRIBUTING.md | 41 - LICENSE | 191 ---- README.adoc | 46 +- pom.xml | 167 --- src/main/asciidoc/index.adoc | 233 ----- .../examples/MySQLPostgreSQLExamples.java | 108 -- src/main/java/examples/package-info.java | 23 - .../io/vertx/ext/asyncsql/AsyncSQLClient.java | 31 - .../io/vertx/ext/asyncsql/MySQLClient.java | 120 --- .../vertx/ext/asyncsql/PostgreSQLClient.java | 118 --- .../ext/asyncsql/impl/AsyncSQLClientImpl.java | 58 -- .../asyncsql/impl/AsyncSQLConnectionImpl.java | 387 ------- .../ext/asyncsql/impl/AsyncSQLRowStream.java | 169 ---- .../ext/asyncsql/impl/BaseSQLClient.java | 147 --- .../vertx/ext/asyncsql/impl/ClientHelper.java | 61 -- .../vertx/ext/asyncsql/impl/ClientHolder.java | 68 -- .../ext/asyncsql/impl/ClientWrapper.java | 54 - .../ext/asyncsql/impl/MYSQLClientImpl.java | 60 -- .../asyncsql/impl/MySQLConnectionImpl.java | 30 - .../asyncsql/impl/PostgreSQLClientImpl.java | 60 -- .../impl/PostgreSQLConnectionImpl.java | 29 - .../vertx/ext/asyncsql/impl/ScalaUtils.java | 156 --- .../impl/VertxEventLoopExecutionContext.java | 80 -- .../impl/pool/AsyncConnectionPool.java | 155 --- .../impl/pool/MysqlAsyncConnectionPool.java | 46 - .../pool/PostgresqlAsyncConnectionPool.java | 50 - .../io/vertx/ext/asyncsql/package-info.java | 18 - .../vertx/ext/asyncsql/AbstractTestBase.java | 58 -- .../vertx/ext/asyncsql/ConfigurationTest.java | 107 -- src/test/java/io/vertx/ext/asyncsql/Data.java | 60 -- .../vertx/ext/asyncsql/MySQLClientTest.java | 175 ---- .../ext/asyncsql/MySQLConfigurationTest.java | 57 -- .../ext/asyncsql/PostgreSQLClientTest.java | 181 ---- .../asyncsql/PostgreSQLConfigurationTest.java | 79 -- .../PostgreSQLSslConfigurationTest.java | 125 --- .../io/vertx/ext/asyncsql/PostgreSQLTest.java | 176 ---- .../io/vertx/ext/asyncsql/RefCountTest.java | 114 --- .../io/vertx/ext/asyncsql/SQLTestBase.java | 952 ------------------ .../ext/asyncsql/category/NeedsDocker.java | 4 - .../vertx/ext/asyncsql/impl/MyVerticle.java | 47 - .../VertxEventLoopExecutionContextTest.java | 89 -- .../impl/tool/AsyncConnectionPoolTest.java | 214 ---- src/test/resources/docker/start-db.sh | 8 - src/test/resources/docker/start-mysql.sh | 18 - .../resources/docker/start-postgres-ssl.sh | 17 - src/test/resources/docker/start-postgres.sh | 16 - src/test/resources/docker/stop-db.sh | 4 - src/test/resources/docker/stop-mysql.sh | 8 - .../resources/docker/stop-postgres-ssl.sh | 4 - src/test/resources/docker/stop-postgres.sh | 4 - src/test/resources/ssl-docker/init.sh | 18 - src/test/resources/ssl-docker/server.crt | 22 - src/test/resources/ssl-docker/server.key | 27 - 55 files changed, 1 insertion(+), 5299 deletions(-) delete mode 100644 .editorconfig delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE delete mode 100644 pom.xml delete mode 100644 src/main/asciidoc/index.adoc delete mode 100644 src/main/java/examples/MySQLPostgreSQLExamples.java delete mode 100644 src/main/java/examples/package-info.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/AsyncSQLClient.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/MySQLClient.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/PostgreSQLClient.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLClientImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLConnectionImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLRowStream.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/BaseSQLClient.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/ClientHelper.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/ClientHolder.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/ClientWrapper.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/MYSQLClientImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/MySQLConnectionImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLClientImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLConnectionImpl.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/ScalaUtils.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContext.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/pool/AsyncConnectionPool.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/pool/MysqlAsyncConnectionPool.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/impl/pool/PostgresqlAsyncConnectionPool.java delete mode 100644 src/main/java/io/vertx/ext/asyncsql/package-info.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/AbstractTestBase.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/ConfigurationTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/Data.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/MySQLClientTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/MySQLConfigurationTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/PostgreSQLClientTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/PostgreSQLConfigurationTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/PostgreSQLSslConfigurationTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/PostgreSQLTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/RefCountTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/SQLTestBase.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/category/NeedsDocker.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/impl/MyVerticle.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContextTest.java delete mode 100644 src/test/java/io/vertx/ext/asyncsql/impl/tool/AsyncConnectionPoolTest.java delete mode 100755 src/test/resources/docker/start-db.sh delete mode 100755 src/test/resources/docker/start-mysql.sh delete mode 100755 src/test/resources/docker/start-postgres-ssl.sh delete mode 100755 src/test/resources/docker/start-postgres.sh delete mode 100755 src/test/resources/docker/stop-db.sh delete mode 100755 src/test/resources/docker/stop-mysql.sh delete mode 100755 src/test/resources/docker/stop-postgres-ssl.sh delete mode 100755 src/test/resources/docker/stop-postgres.sh delete mode 100644 src/test/resources/ssl-docker/init.sh delete mode 100644 src/test/resources/ssl-docker/server.crt delete mode 100644 src/test/resources/ssl-docker/server.key diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index fff7c5ff..00000000 --- a/.editorconfig +++ /dev/null @@ -1,9 +0,0 @@ -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true -end_of_line = lf -insert_final_newline = true diff --git a/.travis.yml b/.travis.yml index fdde9cf9..00320fb4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java branches: only: - - master - /^\d+\.\d+$/ services: - docker diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 01651793..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,41 +0,0 @@ -# Guide to contributing - -Please read this if you intend to contribute to the project. - -## First things - -* Get a github account if you don't have one already -* Submit a github issue if there isn't one already. - * Clearly describe the bug or feature - * Provide exact reproducable steps to reproduce the issue if its a bug - * Include the versions of all components -* Fork the repository on github - -## Making your changes - -* Create a new branch for your changes -* Make your changes -* Make sure you include tests -* Make sure the test suite passes after your changes -* Commit your changes into that branch -* Use descriptive and meaningful commit messages -* If you have a lot of commits squash them into a single commit -* Push your changes to your branch in your forked repository - -## Submitting the changes - -Before submitting your pull request you must sign the [Eclipse Foundation Contributor License Agreement](http://www.eclipse.org/legal/CLA.php). - -We will NOT ACCEPT any contributions without this first being signed. - -To sign the Eclipse CLA you need to: - -* Obtain an Eclipse Foundation userid. Anyone who currently uses Eclipse Bugzilla or Gerrit systems already has one of those. -If you don’t, you need to [register](https://dev.eclipse.org/site_login/createaccount.php). - -* Login into the [projects portal](https://projects.eclipse.org/), select “My Account”, and then the “Contributor License Agreement” tab. - -## After submitting - -* Once you have signed the Eclipse CLA, make a note on the github issue that you have signed the CLA, and then you can submit a pull request via github. -* Do not use your branch for any other development, otherwise further changes that you make will be visible in the PR. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 37ec93a1..00000000 --- a/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and -distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright -owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities -that control, are controlled by, or are under common control with that entity. -For the purposes of this definition, "control" means (i) the power, direct or -indirect, to cause the direction or management of such entity, whether by -contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising -permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including -but not limited to software source code, documentation source, and configuration -files. - -"Object" form shall mean any form resulting from mechanical transformation or -translation of a Source form, including but not limited to compiled object code, -generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made -available under the License, as indicated by a copyright notice that is included -in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that -is based on (or derived from) the Work and for which the editorial revisions, -annotations, elaborations, or other modifications represent, as a whole, an -original work of authorship. For the purposes of this License, Derivative Works -shall not include works that remain separable from, or merely link (or bind by -name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version -of the Work and any modifications or additions to that Work or Derivative Works -thereof, that is intentionally submitted to Licensor for inclusion in the Work -by the copyright owner or by an individual or Legal Entity authorized to submit -on behalf of the copyright owner. For the purposes of this definition, -"submitted" means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, and -issue tracking systems that are managed by, or on behalf of, the Licensor for -the purpose of discussing and improving the Work, but excluding communication -that is conspicuously marked or otherwise designated in writing by the copyright -owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf -of whom a Contribution has been received by Licensor and subsequently -incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the Work and such -Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby -grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, -irrevocable (except as stated in this section) patent license to make, have -made, use, offer to sell, sell, import, and otherwise transfer the Work, where -such license applies only to those patent claims licensable by such Contributor -that are necessarily infringed by their Contribution(s) alone or by combination -of their Contribution(s) with the Work to which such Contribution(s) was -submitted. If You institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work or a -Contribution incorporated within the Work constitutes direct or contributory -patent infringement, then any patent licenses granted to You under this License -for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof -in any medium, with or without modifications, and in Source or Object form, -provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -You must retain, in the Source form of any Derivative Works that You distribute, -all copyright, patent, trademark, and attribution notices from the Source form -of the Work, excluding those notices that do not pertain to any part of the -Derivative Works; and -If the Work includes a "NOTICE" text file as part of its distribution, then any -Derivative Works that You distribute must include a readable copy of the -attribution notices contained within such NOTICE file, excluding those notices -that do not pertain to any part of the Derivative Works, in at least one of the -following places: within a NOTICE text file distributed as part of the -Derivative Works; within the Source form or documentation, if provided along -with the Derivative Works; or, within a display generated by the Derivative -Works, if and wherever such third-party notices normally appear. The contents of -the NOTICE file are for informational purposes only and do not modify the -License. You may add Your own attribution notices within Derivative Works that -You distribute, alongside or as an addendum to the NOTICE text from the Work, -provided that such additional attribution notices cannot be construed as -modifying the License. -You may add Your own copyright statement to Your modifications and may provide -additional or different license terms and conditions for use, reproduction, or -distribution of Your modifications, or for any such Derivative Works as a whole, -provided Your use, reproduction, and distribution of the Work otherwise complies -with the conditions stated in this License. - -5. Submission of Contributions. - -Unless You explicitly state otherwise, any Contribution intentionally submitted -for inclusion in the Work by You to the Licensor shall be under the terms and -conditions of this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify the terms of -any separate license agreement you may have executed with Licensor regarding -such Contributions. - -6. Trademarks. - -This License does not grant permission to use the trade names, trademarks, -service marks, or product names of the Licensor, except as required for -reasonable and customary use in describing the origin of the Work and -reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. - -Unless required by applicable law or agreed to in writing, Licensor provides the -Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, -including, without limitation, any warranties or conditions of TITLE, -NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are -solely responsible for determining the appropriateness of using or -redistributing the Work and assume any risks associated with Your exercise of -permissions under this License. - -8. Limitation of Liability. - -In no event and under no legal theory, whether in tort (including negligence), -contract, or otherwise, unless required by applicable law (such as deliberate -and grossly negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, incidental, -or consequential damages of any character arising as a result of this License or -out of the use or inability to use the Work (including but not limited to -damages for loss of goodwill, work stoppage, computer failure or malfunction, or -any and all other commercial damages or losses), even if such Contributor has -been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. - -While redistributing the Work or Derivative Works thereof, You may choose to -offer, and charge a fee for, acceptance of support, warranty, indemnity, or -other liability obligations and/or rights consistent with this License. However, -in accepting such obligations, You may act only on Your own behalf and on Your -sole responsibility, not on behalf of any other Contributor, and only if You -agree to indemnify, defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason of your -accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/README.adoc b/README.adoc index ab240ac7..1b6d2bb9 100644 --- a/README.adoc +++ b/README.adoc @@ -1,47 +1,3 @@ = Vert.x MySQL PostgreSQL client -image:https://travis-ci.org/vert-x3/vertx-mysql-postgresql-client.svg?branch=master["Build Status", link="https://travis-ci.org/vert-x3/vertx-mysql-postgresql-client"] - -This Vert.x client uses the https://github.com/mauricio/postgresql-async[Mauricio Linhares driver] to support -a fully async client for MySQL and PostgreSQL. - -Please see the in source asciidoc documentation or the main documentation on the web-site for a full description: - -* http://vertx.io/docs/vertx-mysql-postgresql-client/java/[Java documentation] -* http://vertx.io/docs/vertx-mysql-postgresql-client/js/[JavaScript documentation] -* http://vertx.io/docs/vertx-mysql-postgresql-client/kotlin/[Kotlin documentation] -* http://vertx.io/docs/vertx-mysql-postgresql-client/groovy/[Groovy documentation] -* http://vertx.io/docs/vertx-mysql-postgresql-client/ruby/[Ruby documentation] - -== Running test suite with Docker - -The test suite is based on testcontainers and will spawn separate instances for the different tests. - -NOTE: Running test with Docker requires enabling the profile as Docker isn't available on Cloudbees: `mvn clean install -Ddocker` - -== (Deprecated) Running test suite on CkoudBees (this is only here for historic docs to help transition to Travis) - -Setting up test databases with Docker: - ----- -docker run --rm --name vertx-postgres -e POSTGRES_USER=vertx -e POSTGRES_PASSWORD=password -e POSTGRES_DB=testdb -p 5432:5432 postgres ----- - ----- -docker run --rm --name vertx-postgres-ssl -p 54321:5432 \ - -e POSTGRES_USER=vertx \ - -e POSTGRES_PASSWORD=password \ - -e POSTGRES_DB=testdb \ - -v $(pwd)/src/test/resources/ssl-docker/server.crt:/docker-entrypoint-initdb.d/server.crt \ - -v $(pwd)/src/test/resources/ssl-docker/server.key:/docker-entrypoint-initdb.d/server.key \ - -v $(pwd)/src/test/resources/ssl-docker/init.sh:/docker-entrypoint-initdb.d/init.sh \ - postgres ----- - -NOTE: If you're working with Fedora, CentOS or RHEL and have selinux enabled, you need to add `:z` to the volume options. -Otherwise Postgres won't be able to read the SSL setup files. -For more details, read http://www.projectatomic.io/blog/2015/06/using-volumes-with-docker-can-cause-problems-with-selinux/[Using Volumes with Docker can Cause Problems with SELinux]. - ----- -docker run --rm --name vertx-mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_USER=vertx -e MYSQL_PASSWORD=password -e MYSQL_DATABASE=testdb -p 3306:3306 mysql/mysql-server:5.6 ----- +Module removed in Vert.x 4. diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 87d02836..00000000 --- a/pom.xml +++ /dev/null @@ -1,167 +0,0 @@ - - - - io.vertx - vertx-ext-parent - 34 - - - 4.0.0 - - vertx-mysql-postgresql-client - 3.6.0 - - Vert.x MySQL/PostgreSQL Client - - - 3.6.0 - 2.12.7 - 0.2.21 - - - - - - io.vertx - vertx-dependencies - ${stack.version} - pom - import - - - - - - - org.slf4j - slf4j-api - 1.7.21 - provided - - - io.vertx - vertx-sql-common - - - io.vertx - vertx-unit - test - - - org.scala-lang - scala-library - ${scala.version} - - - com.github.mauricio - postgresql-async_2.12 - ${asyncdriver.version} - - - org.slf4j - slf4j-api - - - io.netty - netty-all - - - - - com.github.mauricio - mysql-async_2.12 - ${asyncdriver.version} - - - org.slf4j - slf4j-api - - - io.netty - netty-all - - - - - io.vertx - vertx-codegen - true - - - io.vertx - vertx-docgen - true - - - io.vertx - vertx-core - test-jar - test - - - junit - junit - test - 4.12 - - - com.jayway.awaitility - awaitility - 1.6.3 - test - - - org.mockito - mockito-core - 2.10.0 - test - - - org.testcontainers - testcontainers - 1.8.3 - test - - - org.testcontainers - mysql - 1.8.3 - test - - - mysql - mysql-connector-java - 5.1.6 - test - - - org.testcontainers - postgresql - 1.8.3 - test - - - org.slf4j - slf4j-simple - 1.7.25 - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - 60 - PARANOID - - -server -Xms128m -Xmx1024m -XX:NewRatio=2 - - - - - - diff --git a/src/main/asciidoc/index.adoc b/src/main/asciidoc/index.adoc deleted file mode 100644 index ca3aa7c8..00000000 --- a/src/main/asciidoc/index.adoc +++ /dev/null @@ -1,233 +0,0 @@ -= Vert.x MySQL / PostgreSQL client - -The Async MySQL / PostgreSQL Client is responsible for providing an -interface for Vert.x applications that need to interact with a MySQL or PostgreSQL database. - -It uses Mauricio Linhares https://github.com/mauricio/postgresql-async[async driver] to interact with the MySQL -or PostgreSQL databases in a non blocking way. - -== Using the MySQL and PostgreSQL client - -This section describes how to configure your project to be able to use the MySQL / PostgreSQL client in your -application. - -=== In a regular application - -To use this client, you need to add the following jar to your `CLASSPATH`: - -* ${maven.artifactId} ${maven.version} (the client) -* scala-library 2.11.4 -* the postgress-async-2.11 and mysdql-async-2.11 from https://github.com/mauricio/postgresql-async -* joda time - -All these jars are downloadable from Maven Central. - -=== In an application packaged in a fat jar - -If you are building a _Fat-jar_ using Maven or Gradle, just add the following dependencies: - -* Maven (in your `pom.xml`): - -[source,xml,subs="+attributes"] ----- - - io.vertx - vertx-mysql-postgresql-client - ${maven.version} - ----- - -* Gradle (in your `build.gradle` file): - -[source,groovy,subs="+attributes"] ----- -compile 'io.vertx:vertx-mysql-postgresql-client:${maven.version}' ----- - -=== In an application using a vert.x distributions - -If you are using a vert.x distribution, add the jar files listed above to the `$VERTX_HOME/lib` directory. - -Alternatively, you can edit the `vertx-stack.json` file located in `$VERTX_HOME`, and set `"included": true` -for the `vertx-mysql-postgresql-client` dependency. Once done, launch: `vertx resolve --dir=lib --stack= -./vertx-stack.json`. It downloads the client and its dependencies. - -== Creating a client - -There are several ways to create a client. Let's go through them all. - -=== Using default shared pool - -In most cases you will want to share a pool between different client instances. - -E.g. you scale your application by deploying multiple instances of your verticle and you want each verticle instance -to share the same pool so you don't end up with multiple pools - -You do this as follows: - -[source,java] ----- -{@link examples.MySQLPostgreSQLExamples#exampleCreateDefault} ----- - -The first call to {@link io.vertx.ext.asyncsql.MySQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject)} -or {@link io.vertx.ext.asyncsql.PostgreSQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject)} -will actually create the data source, and the specified config will be used. - -Subsequent calls will return a new client instance that uses the same data source, so the configuration won't be used. - -=== Specifying a pool name - -You can create a client specifying a pool name as follows - -[source,java] ----- -{@link examples.MySQLPostgreSQLExamples#exampleCreatePoolName} ----- - -If different clients are created using the same Vert.x instance and specifying the same pool name, they will -share the same data source. - -The first call to {@link io.vertx.ext.asyncsql.MySQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject, String)} -or {@link io.vertx.ext.asyncsql.PostgreSQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject, String)} -will actually create the data source, and the specified config will be used. - -Subsequent calls will return a new client instance that uses the same pool, so the configuration won't be used. - -Use this way of creating if you wish different groups of clients to have different pools, e.g. they're -interacting with different databases. - -=== Creating a client with a non shared data source - -In most cases you will want to share a pool between different client instances. -However, it's possible you want to create a client instance that doesn't share its pool with any other client. - -In that case you can use {@link io.vertx.ext.asyncsql.MySQLClient#createNonShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject)} -or {@link io.vertx.ext.asyncsql.PostgreSQLClient#createNonShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject)} - -[source,java] ----- -{@link examples.MySQLPostgreSQLExamples#exampleCreateNonShared} ----- - -This is equivalent to calling {@link io.vertx.ext.asyncsql.MySQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject, String)} -or {@link io.vertx.ext.asyncsql.PostgreSQLClient#createShared(io.vertx.core.Vertx, io.vertx.core.json.JsonObject, String)} -with a unique pool name each time. - -== Closing the client - -You can hold on to the client for a long time (e.g. the life-time of your verticle), but once you have finished with -it, you should close it using {@link io.vertx.ext.asyncsql.AsyncSQLClient#close(io.vertx.core.Handler)} or -{@link io.vertx.ext.asyncsql.AsyncSQLClient#close()} - -== Getting a connection - -Use {@link io.vertx.ext.asyncsql.AsyncSQLClient#getConnection(io.vertx.core.Handler)} to get a connection. - -This will return the connection in the handler when one is ready from the pool. - -[source,java] ----- -{@link examples.MySQLPostgreSQLExamples#example4} ----- - -Once you've finished with the connection make sure you close it afterwards. - -The connection is an instance of {@link io.vertx.ext.sql.SQLConnection} which is a common interface used by -other SQL clients. - -You can learn how to use it in the http://vertx.io/docs/vertx-sql-common/$lang/[common sql interface] documentation. - -=== Configuring reconnections - -This service is able to recover from temporary database outages, such as those which occur during a database restart or -brief loss of network connectivity. You can configure the expected behaviour when acquiring connections via the -following properties: - -* `maxConnectionRetries` -* `connectionRetryDelay` - -When the internal connection pool attempts to acquire an open connection and fails, it will retry up to -`maxConnectionRetries` times, with a delay of `connectionRetryDelay` milliseconds between each attempt. -If all attempts fail, any clients waiting for connections from the pool will be notified with an Error, indicating that -a Connection could not be acquired. Note that clients will not be notified with an Error until a full round of attempts -fail, which may be some time after the initial connection attempt. - -If `maxConnectionRetries` is set to `0`, the internal connection pool will not perform any reconnection (default). If -`maxConnectionRetries` is set to `-1`, the internal connection pool will attempt to acquire new connections indefinitely, -so any call to {@link io.vertx.ext.asyncsql.AsyncSQLClient#getConnection(io.vertx.core.Handler)} -may be indefinitely waiting for a successful acquisition. - -Once a full round of acquisition attempts fails, the internal connection pool will remain active, and will try -again to acquire connections in response to future requests for connections. - -Note that if a database restart occurs, a pool may contain previously acquired but now stale Connections that will only be -detected and purged lazily, when the pool attempts to reuse them. - -=== Note about date and timestamps - -Whenever you get dates back from the database, this service will implicitly convert them into ISO 8601 -(`yyyy-MM-ddTHH:mm:ss.SSS`) formatted strings. MySQL usually discards milliseconds, so you will regularly see `.000`. - -=== Note about last inserted ids - -When inserting new rows into a table, you might want to retrieve auto-incremented ids from the database. The JDBC API -usually lets you retrieve the last inserted id from a connection. If you use MySQL, it will work the way it does like -the JDBC API. In PostgreSQL you can add the -http://www.postgresql.org/docs/current/static/sql-insert.html["RETURNING" clause] to get the latest inserted ids. Use -one of the `query` methods to get access to the returned columns. - -=== Note about stored procedures - -The `call` and `callWithParams` methods are not implemented currently. - -== Configuration - -Both the PostgreSql and MySql clients take the same configuration: - ----- -{ - "host" : , - "port" : , - "maxPoolSize" : , - "username" : , - "password" : , - "database" : , - "charset" : , - "connectTimeout" : , - "testTimeout" : , - "queryTimeout" : , - "maxConnectionRetries" : , - "connectionRetryDelay" : , - "sslMode" : <"disable"|"prefer"|"require"|"verify-ca"|"verify-full">, - "sslRootCert" : -} ----- - -`host`:: The host of the database. Defaults to `localhost`. -`port`:: The port of the database. Defaults to `5432` for PostgreSQL and `3306` for MySQL. -`maxPoolSize`:: The number of connections that may be kept open. Defaults to `10`. -`username`:: The username to connect to the database. Defaults to `vertx`. -`password`:: The password to connect to the database. Defaults to `password`. -`database`:: The name of the database you want to connect to. Defaults to `testdb`. -`charset`:: The name of the character set you want to use for the connection. Defaults to `UTF-8`. -`connectTimeout`:: The timeout to wait for connecting to the database. Defaults to `10000` (= 10 seconds). -`testTimeout`:: The timeout for connection tests performed by pools. Defaults to `10000` (= 10 seconds). -`queryTimeout`:: The timeout to wait for a query in milliseconds. Default is not set. -`maxConnectionRetries`:: Maximum number of connection retries. Defaults to `0` (no retries). + - Special values: - -1 ::: Unlimited number of connection retries - 0 ::: No connection retries will be done -`connectionRetryDelay`:: Delay in milliseconds between each retry attempt. Defaults to `5000` (= 5 seconds). -`sslMode` :: If you want to enable SSL support you should enable this parameter. - For example to connect Heroku you will need to use *prefer*. - - "disable" ::: only try a non-SSL connection - "prefer" ::: first try an SSL connection; if that fails, try a non-SSL connection - "require" ::: only try an SSL connection, but don't verify Certificate Authority - "verify-ca" ::: only try an SSL connection, and verify that the server certificate is issued by a trusted - certificate authority (CA) - "verify-full" ::: only try an SSL connection, verify that the server certificate is issued by a trusted CA and - that the server host name matches that in the certificate -`sslRootCert` :: Path to SSL root certificate file. Is used if you want to verify privately issued certificate. - Refer to https://github.com/mauricio/postgresql-async[postgresql-async] documentation for more details. diff --git a/src/main/java/examples/MySQLPostgreSQLExamples.java b/src/main/java/examples/MySQLPostgreSQLExamples.java deleted file mode 100644 index 7a6c797f..00000000 --- a/src/main/java/examples/MySQLPostgreSQLExamples.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package examples; - -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.MySQLClient; -import io.vertx.ext.asyncsql.PostgreSQLClient; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.sql.SQLConnection; - -/** - * - * @author Tim Fox - */ -public class MySQLPostgreSQLExamples { - - public void exampleCreateDefault(Vertx vertx) { - - // To create a MySQL client: - - JsonObject mySQLClientConfig = new JsonObject().put("host", "mymysqldb.mycompany"); - SQLClient mySQLClient = MySQLClient.createShared(vertx, mySQLClientConfig); - - // To create a PostgreSQL client: - - JsonObject postgreSQLClientConfig = new JsonObject().put("host", "mypostgresqldb.mycompany"); - SQLClient postgreSQLClient = PostgreSQLClient.createShared(vertx, postgreSQLClientConfig); - - } - - public void exampleCreatePoolName(Vertx vertx) { - - // To create a MySQL client: - - JsonObject mySQLClientConfig = new JsonObject().put("host", "mymysqldb.mycompany"); - SQLClient mySQLClient = MySQLClient.createShared(vertx, mySQLClientConfig, "MySQLPool1"); - - // To create a PostgreSQL client: - - JsonObject postgreSQLClientConfig = new JsonObject().put("host", "mypostgresqldb.mycompany"); - SQLClient postgreSQLClient = PostgreSQLClient.createShared(vertx, postgreSQLClientConfig, "PostgreSQLPool1"); - - } - - public void exampleCreateNonShared(Vertx vertx) { - - // To create a MySQL client: - - JsonObject mySQLClientConfig = new JsonObject().put("host", "mymysqldb.mycompany"); - SQLClient mySQLClient = MySQLClient.createNonShared(vertx, mySQLClientConfig); - - // To create a PostgreSQL client: - - JsonObject postgreSQLClientConfig = new JsonObject().put("host", "mypostgresqldb.mycompany"); - SQLClient postgreSQLClient = PostgreSQLClient.createNonShared(vertx, postgreSQLClientConfig); - - } - - public void example2(Vertx vertx) { - - JsonObject config = new JsonObject().put("host", "mymysqldb.mycompany"); - - SQLClient mySQLClient = MySQLClient.createNonShared(vertx, config); - - } - - public void example3(Vertx vertx) { - - JsonObject config = new JsonObject().put("host", "mypostgresqldb.mycompany"); - - SQLClient postgreSQLClient = PostgreSQLClient.createNonShared(vertx, config); - } - - public void example4(SQLClient client) { - - // Now do stuff with it: - - client.getConnection(res -> { - if (res.succeeded()) { - - SQLConnection connection = res.result(); - - // Got a connection - - } else { - // Failed to get connection - deal with it - } - }); - - } - - -} diff --git a/src/main/java/examples/package-info.java b/src/main/java/examples/package-info.java deleted file mode 100644 index c75de2ba..00000000 --- a/src/main/java/examples/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -/** - * @author Julien Viet - */ -@Source -package examples; - -import io.vertx.docgen.Source; \ No newline at end of file diff --git a/src/main/java/io/vertx/ext/asyncsql/AsyncSQLClient.java b/src/main/java/io/vertx/ext/asyncsql/AsyncSQLClient.java deleted file mode 100644 index 20421b8a..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/AsyncSQLClient.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.codegen.annotations.VertxGen; -import io.vertx.ext.sql.SQLClient; - -/** - * Represents an asynchronous SQL client - * - * @author Joern Bernhardt. - * @author Tim Fox - */ -@VertxGen -public interface AsyncSQLClient extends SQLClient { - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/MySQLClient.java b/src/main/java/io/vertx/ext/asyncsql/MySQLClient.java deleted file mode 100644 index 59db3567..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/MySQLClient.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.codegen.annotations.VertxGen; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.impl.ClientHelper; -import io.vertx.ext.sql.SQLClient; - -import java.util.UUID; - -/** - * Represents an asynchronous MySQL client - * - * @author Joern Bernhardt. - * @author Tim Fox - */ -@VertxGen -public interface MySQLClient extends AsyncSQLClient { - - /** - * The default name used for the MySQL pool. - */ - String DEFAULT_POOL_NAME = "DEFAULT_MYSQL_POOL"; - - /** - * The default host. - */ - String DEFAULT_HOST = "localhost"; - - /** - * The default port. - */ - int DEFAULT_PORT = 3306; - - /** - * The default database. - */ - String DEFAULT_DATABASE = "testdb"; - - /** - * The default database user. - */ - String DEFAULT_USER = "vertx"; - - /** - * The default database password. - */ - String DEFAULT_PASSWORD = "password"; - - /** - * The default charset. - */ - String DEFAULT_CHARSET = "UTF-8"; - - /** - * The default timeout for connect. - */ - long DEFAULT_CONNECT_TIMEOUT = 10000L; - - /** - * The default timeout for tests. - */ - long DEFAULT_TEST_TIMEOUT = 10000L; - - - /** - * Create a MySQL client which maintains its own pool. - * - * @param vertx the Vert.x instance - * @param config the configuration - * @return the client - */ - static AsyncSQLClient createNonShared(Vertx vertx, JsonObject config) { - return ClientHelper.getOrCreate(vertx, config, UUID.randomUUID().toString(), true); - } - - - /** - * Create a MySQL client which shares its data source with any other MySQL clients created with the same - * data source name - * - * @param vertx the Vert.x instance - * @param config the configuration - * @param poolName the pool name - * @return the client - */ - static AsyncSQLClient createShared(Vertx vertx, JsonObject config, String poolName) { - return ClientHelper.getOrCreate(vertx, config, poolName, true); - } - - - /** - * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default pool name - * - * @param vertx the Vert.x instance - * @param config the configuration - * @return the client - */ - static AsyncSQLClient createShared(Vertx vertx, JsonObject config) { - return ClientHelper.getOrCreate(vertx, config, DEFAULT_POOL_NAME, true); - } - - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/PostgreSQLClient.java b/src/main/java/io/vertx/ext/asyncsql/PostgreSQLClient.java deleted file mode 100644 index a8dbecfe..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/PostgreSQLClient.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.codegen.annotations.VertxGen; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.impl.ClientHelper; -import io.vertx.ext.sql.SQLClient; - -import java.util.UUID; - -/** - * Represents an PostgreSQL client - * - * @author Joern Bernhardt. - * @author Tim Fox - */ -@VertxGen -public interface PostgreSQLClient extends AsyncSQLClient { - - /** - * The default name used for the PostGreSQL pool. - */ - String DEFAULT_DS_NAME = "DEFAULT_POSTGRESQL_DS"; - - /** - * The default host. - */ - String DEFAULT_HOST = "localhost"; - - /** - * The default port. - */ - int DEFAULT_PORT = 5432; - - /** - * The default database name. - */ - String DEFAULT_DATABASE = "testdb"; - - /** - * The default database user. - */ - String DEFAULT_USER = "vertx"; - - /** - * The default user password. - */ - String DEFAULT_PASSWORD = "password"; - - /** - * The default charset. - */ - String DEFAULT_CHARSET = "UTF-8"; - - /** - * The default timeout for connect. - */ - long DEFAULT_CONNECT_TIMEOUT = 10000L; - - /** - * The default timeout for tests. - */ - long DEFAULT_TEST_TIMEOUT = 10000L; - - - /** - * Create a PostgreSQL client which maintains its own pool. - * - * @param vertx the Vert.x instance - * @param config the configuration - * @return the client - */ - static AsyncSQLClient createNonShared(Vertx vertx, JsonObject config) { - return ClientHelper.getOrCreate(vertx, config, UUID.randomUUID().toString(), false); - } - - /** - * Create a PostgreSQL client which shares its pool with any other MySQL clients created with the same pool name. - * - * @param vertx the Vert.x instance - * @param config the configuration - * @param poolName the pool name - * @return the client - */ - static AsyncSQLClient createShared(Vertx vertx, JsonObject config, String poolName) { - return ClientHelper.getOrCreate(vertx, config, poolName, false); - } - - - /** - * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default pool name - * - * @param vertx the Vert.x instance - * @param config the configuration - * @return the client - */ - static AsyncSQLClient createShared(Vertx vertx, JsonObject config) { - return ClientHelper.getOrCreate(vertx, config, DEFAULT_DS_NAME, false); - } - - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLClientImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLClientImpl.java deleted file mode 100644 index 8bda55e1..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLClientImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.AsyncSQLClient; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.sql.SQLConnection; - -/** - * @author Joern Bernhardt. - */ -public class AsyncSQLClientImpl implements AsyncSQLClient { - - private final BaseSQLClient baseClient; - - public AsyncSQLClientImpl(Vertx vertx, JsonObject config, boolean mysql) { - if (mysql) { - baseClient = new MYSQLClientImpl(vertx, config); - } else { - baseClient = new PostgreSQLClientImpl(vertx, config); - } - } - - @Override - public void close() { - baseClient.close(null); - } - - @Override - public void close(Handler> completionHandler) { - baseClient.close(completionHandler); - } - - @Override - public SQLClient getConnection(Handler> handler) { - baseClient.getConnection(handler); - return this; - } - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLConnectionImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLConnectionImpl.java deleted file mode 100644 index 1802df30..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLConnectionImpl.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.QueryResult; -import com.github.mauricio.async.db.RowData; -import io.vertx.core.AsyncResult; -import io.vertx.core.Future; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.sql.ResultSet; -import io.vertx.ext.sql.SQLConnection; -import io.vertx.ext.sql.SQLOptions; -import io.vertx.ext.sql.SQLRowStream; -import io.vertx.ext.sql.TransactionIsolation; -import io.vertx.ext.sql.UpdateResult; -import scala.Option; -import scala.concurrent.ExecutionContext; -import scala.runtime.AbstractFunction1; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Implementation of {@link SQLConnection} using the {@link AsyncConnectionPool}. - * - * @author Clement Escoffier - */ -public abstract class AsyncSQLConnectionImpl implements SQLConnection { - - private final ExecutionContext executionContext; - private volatile boolean inTransaction = false; - private boolean inAutoCommit = true; - - private final Connection connection; - private final AsyncConnectionPool pool; - - public AsyncSQLConnectionImpl(Connection connection, AsyncConnectionPool pool, ExecutionContext executionContext) { - this.connection = connection; - this.pool = pool; - this.executionContext = executionContext; - } - - /** - * Returns a vendor specific start transaction statement - */ - protected abstract String getStartTransactionStatement(); - - @Override - public SQLConnection call(String sql, Handler> resultHandler) { - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection callWithParams(String sql, JsonArray params, JsonArray outputs, Handler> resultHandler) { - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection setOptions(SQLOptions options) { - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection setAutoCommit(boolean autoCommit, Handler> handler) { - Future fut; - - synchronized (this) { - if (inTransaction && autoCommit) { - inTransaction = false; - fut = ScalaUtils.scalaToVertxVoid(connection.sendQuery("COMMIT"), executionContext); - } else { - fut = Future.succeededFuture(); - } - inAutoCommit = autoCommit; - } - - fut.setHandler(handler); - return this; - - } - - @Override - public SQLConnection execute(String sql, Handler> handler) { - beginTransactionIfNeeded(v -> { - final scala.concurrent.Future future = connection.sendQuery(sql); - future.onComplete(ScalaUtils.toFunction1(ar -> { - if (ar.succeeded()) { - handler.handle(Future.succeededFuture()); - } else { - handler.handle(Future.failedFuture(ar.cause())); - } - }), executionContext); - }); - - return this; - } - - @Override - public SQLConnection query(String sql, Handler> handler) { - beginTransactionIfNeeded(v -> { - final Future future = ScalaUtils.scalaToVertx(connection.sendQuery(sql), executionContext); - future.setHandler(handleAsyncQueryResultToResultSet(handler)); - }); - - return this; - } - - @Override - public SQLConnection queryStream(String sql, Handler> handler) { - beginTransactionIfNeeded(v -> { - final Future future = ScalaUtils.scalaToVertx(connection.sendQuery(sql), executionContext); - future.setHandler(handleAsyncQueryResultToRowStream(handler)); - }); - - return this; - } - - @Override - public SQLConnection queryWithParams(String sql, JsonArray params, Handler> handler) { - beginTransactionIfNeeded(v -> { - final scala.concurrent.Future future = connection.sendPreparedStatement(sql, - ScalaUtils.toScalaList(params.getList())); - future.onComplete(ScalaUtils.toFunction1(handleAsyncQueryResultToResultSet(handler)), executionContext); - }); - - return this; - } - - @Override - public SQLConnection queryStreamWithParams(String sql, JsonArray params, Handler> handler) { - beginTransactionIfNeeded(v -> { - final Future future = ScalaUtils.scalaToVertx(connection.sendPreparedStatement(sql, ScalaUtils.toScalaList(params.getList())), executionContext); - future.setHandler(handleAsyncQueryResultToRowStream(handler)); - }); - - return this; - } - - @Override - public SQLConnection update(String sql, Handler> handler) { - beginTransactionIfNeeded(v -> { - final scala.concurrent.Future future = connection.sendQuery(sql); - future.onComplete(ScalaUtils.toFunction1(handleAsyncUpdateResultToResultSet(handler)), executionContext); - }); - - return this; - } - - @Override - public SQLConnection updateWithParams(String sql, JsonArray params, Handler> handler) { - beginTransactionIfNeeded(v -> { - final scala.concurrent.Future future = connection.sendPreparedStatement(sql, - ScalaUtils.toScalaList(params.getList())); - future.onComplete(ScalaUtils.toFunction1(handleAsyncUpdateResultToResultSet(handler)), executionContext); - }); - - return this; - } - - @Override - public synchronized void close(Handler> handler) { - inAutoCommit = true; - if (inTransaction) { - inTransaction = false; - Future future = ScalaUtils.scalaToVertx(connection.sendQuery("COMMIT"), executionContext); - future.setHandler((v) -> { - pool.giveBack(connection); - handler.handle(Future.succeededFuture()); - }); - } else { - pool.giveBack(connection); - handler.handle(Future.succeededFuture()); - } - } - - @Override - public void close() { - close((ar) -> { - // Do nothing by default. - }); - } - - @Override - public SQLConnection commit(Handler> handler) { - return endAndStartTransaction("COMMIT", handler); - } - - @Override - public SQLConnection rollback(Handler> handler) { - return endAndStartTransaction("ROLLBACK", handler); - } - - @Override - public SQLConnection setTransactionIsolation(TransactionIsolation transactionIsolation, Handler> handler) { - String sql; - switch (transactionIsolation) { - case READ_UNCOMMITTED: - sql = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; - break; - case REPEATABLE_READ: - sql = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"; - break; - case READ_COMMITTED: - sql = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; - break; - case SERIALIZABLE: - sql = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"; - break; - case NONE: - default: - sql = null; - break; - } - - if (sql == null) { - handler.handle(Future.succeededFuture()); - return this; - } - - return execute(sql, handler); - } - - @Override - public SQLConnection getTransactionIsolation(Handler> handler) { - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection batch(List sqlStatements, Handler>> handler) { - // This should be simple in postgres, since it is just append the query separator after each query and send as a big - // sql statement, however it does not seem to work on mysql - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection batchWithParams(String sqlStatement, List args, Handler>> handler) { - // This should be simple in postgres, since it is just append the query separator after each query and send as a big - // sql statement, however it does not seem to work on mysql - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - public SQLConnection batchCallableWithParams(String sqlStatement, List inArgs, List outArgs, Handler>> handler) { - // No idea how to implement this - throw new UnsupportedOperationException("Not implemented"); - } - - @Override - @SuppressWarnings("unchecked") - public C unwrap() { - return (C) connection; - } - - private SQLConnection endAndStartTransaction(String command, Handler> handler) { - if (inTransaction) { - inTransaction = false; - ScalaUtils.scalaToVertx(connection.sendQuery(command), executionContext).setHandler( - ar -> { - if (ar.failed()) { - handler.handle(Future.failedFuture(ar.cause())); - } else { - ScalaUtils.scalaToVertx(connection.sendQuery("BEGIN"), executionContext).setHandler( - ar2 -> { - if (ar2.failed()) { - handler.handle(Future.failedFuture(ar.cause())); - } else { - inTransaction = true; - handler.handle(Future.succeededFuture()); - } - } - ); - } - }); - } else { - handler.handle(Future.failedFuture( - new IllegalStateException("Not in transaction currently"))); - } - return this; - } - - private synchronized void beginTransactionIfNeeded(Handler> action) { - if (!inAutoCommit && !inTransaction) { - inTransaction = true; - ScalaUtils.scalaToVertxVoid(connection.sendQuery(getStartTransactionStatement()), executionContext) - .setHandler(action); - } else { - action.handle(Future.succeededFuture()); - } - } - - private Handler> handleAsyncQueryResultToResultSet(Handler> handler) { - return ar -> { - if (ar.succeeded()) { - ResultSet result; - try { - result = queryResultToResultSet(ar.result()); - } catch (Throwable e) { - handler.handle(Future.failedFuture(e)); - return; - } - handler.handle(Future.succeededFuture(result)); - } else { - handler.handle(Future.failedFuture(ar.cause())); - } - }; - } - - private Handler> handleAsyncQueryResultToRowStream(Handler> handler) { - return ar -> { - if (ar.succeeded()) { - AsyncSQLRowStream rowStream; - try { - rowStream = new AsyncSQLRowStream(ar.result()); - } catch (Throwable e) { - handler.handle(Future.failedFuture(e)); - return; - } - handler.handle(Future.succeededFuture(rowStream)); - } else { - handler.handle(Future.failedFuture(ar.cause())); - } - }; - } - - private ResultSet queryResultToResultSet(QueryResult qr) { - final Option rows = qr.rows(); - if (!rows.isDefined()) { - return new ResultSet(Collections.emptyList(), Collections.emptyList(), null); - } else { - final List names = ScalaUtils.toJavaList(rows.get().columnNames().toList()); - final List arrays = rowDataSeqToJsonArray(rows.get()); - return new ResultSet(names, arrays, null); - } - } - - private Handler> handleAsyncUpdateResultToResultSet(Handler> handler) { - return ar -> { - if (ar.succeeded()) { - UpdateResult result; - try { - result = queryResultToUpdateResult(ar.result()); - } catch (Throwable e) { - handler.handle(Future.failedFuture(e)); - return; - } - handler.handle(Future.succeededFuture(result)); - } else { - handler.handle(Future.failedFuture(ar.cause())); - } - }; - } - - protected UpdateResult queryResultToUpdateResult(QueryResult qr) { - int affected = (int) qr.rowsAffected(); - return new UpdateResult(affected, new JsonArray()); - } - - private List rowDataSeqToJsonArray(com.github.mauricio.async.db.ResultSet set) { - List list = new ArrayList<>(); - set.foreach(new AbstractFunction1() { - @Override - public Void apply(RowData row) { - list.add(ScalaUtils.rowToJsonArray(row)); - return null; - } - }); - return list; - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLRowStream.java b/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLRowStream.java deleted file mode 100644 index 04962a11..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/AsyncSQLRowStream.java +++ /dev/null @@ -1,169 +0,0 @@ -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.QueryResult; -import com.github.mauricio.async.db.ResultSet; -import com.github.mauricio.async.db.RowData; -import io.vertx.core.AsyncResult; -import io.vertx.core.Future; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import io.vertx.ext.sql.SQLRowStream; -import scala.Option; -import scala.collection.Iterator; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; - -class AsyncSQLRowStream implements SQLRowStream { - - private final ResultSet rs; - private final Iterator cursor; - private List columns; - - private long demand = 0L; - private final AtomicBoolean ended = new AtomicBoolean(false); - - private Handler handler; - private Handler endHandler; - private Handler rsClosedHandler; - - AsyncSQLRowStream(QueryResult qr) { - final Option rows = qr.rows(); - if (rows.isDefined()) { - rs = rows.get(); - cursor = rs.iterator(); - } else { - rs = null; - cursor = null; - } - } - - @Override - public int column(String name) { - if (rs == null) { - throw new IndexOutOfBoundsException("'" + name + "' not found"); - } - - // the columns value will be cached - return columns().indexOf(name); - } - - @Override - public List columns() { - // populate the cache - if (columns == null) { - // quick escape - if (rs == null) { - return Collections.emptyList(); - } - // this list is always read only - columns = Collections.unmodifiableList(ScalaUtils.toJavaList(rs.columnNames().toList())); - } - return columns; - } - - @Override - public SQLRowStream exceptionHandler(Handler handler) { - return this; - } - - @Override - public SQLRowStream handler(Handler handler) { - this.handler = handler; - // start pumping data once the handler is set - resume(); - return this; - } - - @Override - public SQLRowStream pause() { - demand = 0L; - return this; - } - - @Override - public synchronized SQLRowStream fetch(long amount) { - if (amount > 0L) { - if ((demand += amount) < 0L) { - demand = Long.MAX_VALUE; - } - nextRow(); - } - return this; - } - - @Override - public SQLRowStream resume() { - return fetch(Long.MAX_VALUE); - } - - private void nextRow() { - while (demand > 0L) { - if (cursor.hasNext()) { - if (demand != Long.MAX_VALUE) { - demand--; - } - handler.handle(ScalaUtils.rowToJsonArray(cursor.next())); - } else { - // mark as ended if the handler was registered too late - ended.set(true); - // automatically close resources - if (rsClosedHandler != null) { - // only notify (since the rs is closed by the underlying driver) - rsClosedHandler.handle(null); - } else { - // default behavior notify that everything ended - close(c -> { - if (endHandler != null) { - endHandler.handle(null); - } - }); - } - break; - } - } - } - - @Override - public SQLRowStream endHandler(Handler handler) { - this.endHandler = handler; - // registration was late but we're already ended, notify - if (ended.compareAndSet(true, false)) { - // only notify once - endHandler.handle(null); - } - return this; - } - - @Override - public SQLRowStream resultSetClosedHandler(Handler handler) { - this.rsClosedHandler = handler; - // registration was late but we're already ended, notify - if (ended.compareAndSet(true, false)) { - // only notify once - rsClosedHandler.handle(null); - } - return this; - } - - @Override - public void moreResults() { - // NO-OP since the underlying driver only returns 1 ResultSet - } - - @Override - public void close() { - close(null); - } - - @Override - public void close(Handler> handler) { - // make sure we stop pumping data - pause(); - // call the provided handler - if (handler != null) { - handler.handle(Future.succeededFuture()); - } - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/BaseSQLClient.java b/src/main/java/io/vertx/ext/asyncsql/impl/BaseSQLClient.java deleted file mode 100644 index 33bc0e19..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/BaseSQLClient.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Configuration; -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.SSLConfiguration; -import io.netty.buffer.PooledByteBufAllocator; -import io.vertx.core.AsyncResult; -import io.vertx.core.Future; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.core.logging.Logger; -import io.vertx.core.logging.LoggerFactory; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.sql.SQLConnection; -import scala.Option; -import scala.Tuple2; -import scala.collection.Map$; -import scala.collection.immutable.Map; -import scala.concurrent.ExecutionContext; -import scala.concurrent.duration.Duration; - -import java.nio.charset.Charset; -import java.util.concurrent.TimeUnit; - -/** - * Base class for the SQL client. - * - * @author Clement Escoffier - */ -public abstract class BaseSQLClient { - - protected final Logger log = LoggerFactory.getLogger(this.getClass()); - protected final Vertx vertx; - - protected final JsonObject globalConfig; - - public BaseSQLClient(Vertx vertx, JsonObject globalConfig) { - this.vertx = vertx; - this.globalConfig = globalConfig; - } - - protected abstract AsyncConnectionPool pool(); - - protected abstract SQLConnection createFromPool(Connection conn, AsyncConnectionPool pool, ExecutionContext ec); - - public void getConnection(Handler> handler) { - pool().take(ar -> { - if (ar.succeeded()) { - final AsyncConnectionPool pool = pool(); - ExecutionContext ec = VertxEventLoopExecutionContext.create(vertx); - handler.handle(Future.succeededFuture(createFromPool(ar.result(), pool, ec))); - } else { - handler.handle(Future.failedFuture(ar.cause())); - } - }); - } - - public void close(Handler> handler) { - log.info("Stopping async SQL client " + this); - pool().close(ar -> { - if (ar.succeeded()) { - if (handler != null) { - handler.handle(Future.succeededFuture()); - } - } else { - if (handler != null) { - handler.handle(Future.failedFuture(ar.cause())); - } - } - } - ); - } - - public void close() { - close(null); - } - - protected Configuration getConnectionConfiguration( - String defaultHost, - int defaultPort, - String defaultDatabase, - String defaultUser, - String defaultPassword, - String defaultCharset, - long defaultConnectTimeout, - long defaultTestTimeout, - JsonObject config) { - - String host = config.getString("host", defaultHost); - int port = config.getInteger("port", defaultPort); - String username = config.getString("username", defaultUser); - String password = config.getString("password", defaultPassword); - String database = config.getString("database", defaultDatabase); - Charset charset = Charset.forName(config.getString("charset", defaultCharset)); - long connectTimeout = config.getLong("connectTimeout", defaultConnectTimeout); - long testTimeout = config.getLong("testTimeout", defaultTestTimeout); - Long queryTimeout = config.getLong("queryTimeout"); - Option queryTimeoutOption = (queryTimeout == null) ? - Option.empty() : Option.apply(Duration.apply(queryTimeout, TimeUnit.MILLISECONDS)); - - Map sslConfig = buildSslConfig(config); - - log.info("Creating configuration for " + host + ":" + port); - return new Configuration( - username, - host, - port, - Option.apply(password), - Option.apply(database), - SSLConfiguration.apply(sslConfig), - charset, - 16777216, - PooledByteBufAllocator.DEFAULT, - Duration.apply(connectTimeout, TimeUnit.MILLISECONDS), - Duration.apply(testTimeout, TimeUnit.MILLISECONDS), - queryTimeoutOption); - } - - private Map buildSslConfig(JsonObject config) { - Map sslConfig = Map$.MODULE$.empty(); - if (config.getString("sslMode")!= null) { - sslConfig = sslConfig.$plus(Tuple2.apply("sslmode", config.getString("sslMode"))); - } - if (config.getString("sslRootCert") != null) { - sslConfig = sslConfig.$plus(Tuple2.apply("sslrootcert", config.getString("sslRootCert"))); - } - return sslConfig; - } - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/ClientHelper.java b/src/main/java/io/vertx/ext/asyncsql/impl/ClientHelper.java deleted file mode 100644 index bcde0c59..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/ClientHelper.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.core.shareddata.LocalMap; -import io.vertx.ext.asyncsql.AsyncSQLClient; -import io.vertx.ext.sql.SQLClient; - - -/** - * This class handles sharing the client instances by using a local shared map. - * - * @author Tim Fox - */ -public class ClientHelper { - - private static final String DS_LOCAL_MAP_NAME_BASE = "__vertx.MySQLPostgreSQL.pools."; - - public static AsyncSQLClient getOrCreate(Vertx vertx, JsonObject config, String poolName, boolean - mySQL) { - synchronized (vertx) { - LocalMap map = vertx.sharedData().getLocalMap( - DS_LOCAL_MAP_NAME_BASE + (mySQL ? "MySQL" : "PostgreSQL")); - - ClientHolder theHolder = map.get(poolName); - if (theHolder == null) { - theHolder = new ClientHolder(vertx, config, mySQL, () -> removeFromMap(vertx, map, poolName)); - map.put(poolName, theHolder); - } else { - theHolder.incRefCount(); - } - return new ClientWrapper(theHolder); - } - } - - private static void removeFromMap(Vertx vertx, LocalMap map, String poolName) { - synchronized (vertx) { - map.remove(poolName); - if (map.isEmpty()) { - map.close(); - } - } - } - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/ClientHolder.java b/src/main/java/io/vertx/ext/asyncsql/impl/ClientHolder.java deleted file mode 100644 index 8ca966a5..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/ClientHolder.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.core.shareddata.Shareable; -import io.vertx.ext.asyncsql.AsyncSQLClient; - -/** - * @author Tim Fox - */ -class ClientHolder implements Shareable { - - private final Vertx vertx; - private final JsonObject config; - private final boolean mySQL; - private final Runnable closeRunner; - - private AsyncSQLClient client; - private int refCount = 1; - - ClientHolder(Vertx vertx, JsonObject config, boolean mySQL, Runnable closeRunner) { - this.vertx = vertx; - this.config = config; - this.mySQL = mySQL; - this.closeRunner = closeRunner; - } - - synchronized AsyncSQLClient client() { - if (client == null) { - client = new AsyncSQLClientImpl(vertx, config, mySQL); - } - return client; - } - - synchronized void incRefCount() { - refCount++; - } - - synchronized void close(Handler> whenDone) { - if (--refCount == 0) { - if (client != null) { - client.close(whenDone); - } - if (closeRunner != null) { - closeRunner.run(); - } - } - } -} - diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/ClientWrapper.java b/src/main/java/io/vertx/ext/asyncsql/impl/ClientWrapper.java deleted file mode 100644 index 8e396c89..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/ClientWrapper.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.ext.asyncsql.AsyncSQLClient; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.sql.SQLConnection; - -/** - * Wraps a client with the {@link ClientHolder} in order to keep track of the references. - * - * @author Tim Fox - */ -public class ClientWrapper implements AsyncSQLClient { - - private final ClientHolder holder; - private final AsyncSQLClient client; - - public ClientWrapper(ClientHolder holder) { - this.holder = holder; - this.client = holder.client(); - } - - @Override - public void close(Handler> whenDone) { - holder.close(whenDone); - } - - @Override - public void close() { - holder.close(null); - } - - @Override - public SQLClient getConnection(Handler> handler) { - return client.getConnection(handler); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/MYSQLClientImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/MYSQLClientImpl.java deleted file mode 100644 index 1a104a91..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/MYSQLClientImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Connection; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.MySQLClient; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.asyncsql.impl.pool.MysqlAsyncConnectionPool; -import io.vertx.ext.sql.SQLConnection; -import scala.concurrent.ExecutionContext; - -/** - * Implementation of the {@link BaseSQLClient} for MYSQL. - * - * @author Clement Escoffier - */ -public class MYSQLClientImpl extends BaseSQLClient { - - private final MysqlAsyncConnectionPool pool; - - public MYSQLClientImpl(Vertx vertx, JsonObject globalConfig) { - super(vertx, globalConfig); - pool = new MysqlAsyncConnectionPool(vertx, globalConfig, getConnectionConfiguration( - MySQLClient.DEFAULT_HOST, - MySQLClient.DEFAULT_PORT, - MySQLClient.DEFAULT_DATABASE, - MySQLClient.DEFAULT_USER, - MySQLClient.DEFAULT_PASSWORD, - MySQLClient.DEFAULT_CHARSET, - MySQLClient.DEFAULT_CONNECT_TIMEOUT, - MySQLClient.DEFAULT_TEST_TIMEOUT, - globalConfig)); - } - - @Override - protected AsyncConnectionPool pool() { - return pool; - } - - @Override - protected SQLConnection createFromPool(Connection conn, AsyncConnectionPool pool, ExecutionContext ec) { - return new MySQLConnectionImpl(conn, pool, ec); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/MySQLConnectionImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/MySQLConnectionImpl.java deleted file mode 100644 index 8362ef6e..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/MySQLConnectionImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.QueryResult; -import com.github.mauricio.async.db.mysql.MySQLQueryResult; -import io.vertx.core.json.JsonArray; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.sql.UpdateResult; -import scala.concurrent.ExecutionContext; - -/** - * @author Joern Bernhardt. - */ -public class MySQLConnectionImpl extends AsyncSQLConnectionImpl { - public MySQLConnectionImpl(Connection conn, AsyncConnectionPool pool, ExecutionContext ec) { - super(conn, pool, ec); - } - - @Override - protected String getStartTransactionStatement() { - return "BEGIN"; - } - - @Override - protected UpdateResult queryResultToUpdateResult(QueryResult qr) { - int affected = (int)qr.rowsAffected(); - MySQLQueryResult mySQLQueryResult = (MySQLQueryResult) qr; - return new UpdateResult(affected, new JsonArray().add(mySQLQueryResult.lastInsertId())); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLClientImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLClientImpl.java deleted file mode 100644 index f5a0b04e..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLClientImpl.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Connection; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.PostgreSQLClient; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.asyncsql.impl.pool.PostgresqlAsyncConnectionPool; -import io.vertx.ext.sql.SQLConnection; -import scala.concurrent.ExecutionContext; - -/** - * Implementation of the {@link BaseSQLClient} for PostGreSQL. - * - * @author Clement Escoffier - */ -public class PostgreSQLClientImpl extends BaseSQLClient { - - private final PostgresqlAsyncConnectionPool pool; - - public PostgreSQLClientImpl(Vertx vertx, JsonObject globalConfig) { - super(vertx, globalConfig); - pool = new PostgresqlAsyncConnectionPool(vertx, globalConfig, getConnectionConfiguration( - PostgreSQLClient.DEFAULT_HOST, - PostgreSQLClient.DEFAULT_PORT, - PostgreSQLClient.DEFAULT_DATABASE, - PostgreSQLClient.DEFAULT_USER, - PostgreSQLClient.DEFAULT_PASSWORD, - PostgreSQLClient.DEFAULT_CHARSET, - PostgreSQLClient.DEFAULT_CONNECT_TIMEOUT, - PostgreSQLClient.DEFAULT_TEST_TIMEOUT, - globalConfig)); - } - - @Override - protected AsyncConnectionPool pool() { - return pool; - } - - @Override - protected SQLConnection createFromPool(Connection conn, AsyncConnectionPool pool, ExecutionContext ec) { - return new PostgreSQLConnectionImpl(conn, pool, ec); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLConnectionImpl.java b/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLConnectionImpl.java deleted file mode 100644 index ee0c5242..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/PostgreSQLConnectionImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.QueryResult; -import io.vertx.core.json.JsonArray; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.sql.UpdateResult; -import scala.concurrent.ExecutionContext; - -/** - * @author Paulo Lopes. - */ -public class PostgreSQLConnectionImpl extends AsyncSQLConnectionImpl { - public PostgreSQLConnectionImpl(Connection conn, AsyncConnectionPool pool, ExecutionContext ec) { - super(conn, pool, ec); - } - - @Override - protected String getStartTransactionStatement() { - // TODO: consider the tx isolation level - return "BEGIN"; - } - - @Override - protected UpdateResult queryResultToUpdateResult(QueryResult qr) { - int affected = (int) qr.rowsAffected(); - return new UpdateResult(affected, new JsonArray()); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/ScalaUtils.java b/src/main/java/io/vertx/ext/asyncsql/impl/ScalaUtils.java deleted file mode 100644 index 53f8cbab..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/ScalaUtils.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import com.github.mauricio.async.db.RowData; -import io.vertx.core.AsyncResult; -import io.vertx.core.Future; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.LocalDateTime; -import org.joda.time.LocalTime; -import scala.Function1; -import scala.collection.immutable.List; -import scala.concurrent.ExecutionContext; -import scala.concurrent.duration.FiniteDuration; -import scala.runtime.AbstractFunction1; -import scala.util.Try; - -import java.time.Instant; -import java.util.UUID; - -/** - * Some Scala <=> Java conversion utilities. - * - * @author Clement Escoffier - */ -public final class ScalaUtils { - - private ScalaUtils () {} - - public static Future scalaToVertx(scala.concurrent.Future future, ExecutionContext ec) { - Future fut = Future.future(); - future.onComplete(new AbstractFunction1, Void>() { - @Override - public Void apply(Try v1) { - if (v1.isSuccess()) { - fut.complete(v1.get()); - } else { - fut.fail(v1.failed().get()); - } - return null; - } - }, ec); - return fut; - } - - public static Future scalaToVertxVoid(scala.concurrent.Future future, ExecutionContext ec) { - Future fut = Future.future(); - future.onComplete(new AbstractFunction1, Void>() { - @Override - public Void apply(Try v1) { - if (v1.isSuccess()) { - fut.complete(); - } else { - fut.fail(v1.failed().get()); - } - return null; - } - }, ec); - return fut; - } - - - public static java.util.List toJavaList(List list) { - return scala.collection.JavaConversions.bufferAsJavaList(list.toBuffer()); - } - - public static List toScalaList(java.util.List list) { - return scala.collection.JavaConversions.asScalaBuffer(list).toList(); - } - - public static Function1, Void> toFunction1(Handler> code) { - return new AbstractFunction1, Void>() { - @Override - public Void apply(Try v1) { - if (v1.isSuccess()) { - code.handle(Future.succeededFuture(v1.get())); - } else { - code.handle(Future.failedFuture(v1.failed().get())); - } - return null; - } - }; - } - - public static JsonArray rowToJsonArray(RowData data) { - JsonArray array = new JsonArray(); - data.foreach(new AbstractFunction1() { - @Override - public Void apply(Object value) { - convertValue(array, value); - return null; - } - }); - return array; - } - private static void convertValue(JsonArray array, Object value) { - if (value == null) { - array.addNull(); - } else if (value instanceof scala.math.BigDecimal) { - array.add(value.toString()); - } else if (value instanceof LocalDateTime) { - array.add(value.toString()); - } else if (value instanceof LocalDate) { - array.add(value.toString()); - } else if (value instanceof LocalTime) { - array.add(value.toString()); - } else if (value instanceof FiniteDuration) { - String time = durationToString(((FiniteDuration) value).toMillis()); - array.add(time); - } else if (value instanceof DateTime) { - array.add(Instant.ofEpochMilli(((DateTime) value).getMillis())); - } else if (value instanceof UUID) { - array.add(value.toString()); - } else if (value instanceof scala.collection.mutable.ArrayBuffer) { - scala.collection.mutable.ArrayBuffer arrayBuffer = (scala.collection.mutable.ArrayBuffer) value; - JsonArray subArray = new JsonArray(); - arrayBuffer.foreach(new AbstractFunction1() { - - @Override - public Void apply(Object subValue) { - convertValue(subArray, subValue); - return null; - } - - }); - array.add(subArray); - } else { - array.add(value); - } - } - - private static String durationToString(long allInMillis) { - long hours = allInMillis / 1000 / 60 / 60; - long minutes = allInMillis / 1000 / 60 % 60; - long seconds = allInMillis / 1000 % 60; - long millis = allInMillis % 1000; - return String.format("%02d:%02d:%02d.%03d", hours, minutes, seconds, millis); - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContext.java b/src/main/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContext.java deleted file mode 100644 index 6e542165..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContext.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.Context; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import scala.concurrent.ExecutionContext; - -import java.util.Objects; - -/** - * Execution environment for Scala Future. The submitted {@link Runnable} are executed in the Vert.x Event Loop. - * - * @author Clement Escoffier - */ -public class VertxEventLoopExecutionContext implements ExecutionContext { - - public static ExecutionContext create(Vertx vertx) { - return new VertxEventLoopExecutionContext(vertx); - } - - private final Context context; - - private VertxEventLoopExecutionContext(Vertx vertx) { - Objects.requireNonNull(vertx); - Context ctx = Vertx.currentContext(); - if (ctx == null) { - ctx = vertx.getOrCreateContext(); - } - this.context = ctx; - } - - @Override - public void execute(Runnable runnable) { - if (context == Vertx.currentContext()) { - try { - runnable.run(); - } catch (Throwable e) { - reportFailure(e); - } - } else { - context.runOnContext(v -> { - try { - runnable.run(); - } catch (Throwable e) { - reportFailure(e); - } - }); - } - } - - @Override - public void reportFailure(Throwable cause) { - Handler exceptionHandler = context.exceptionHandler(); - if (exceptionHandler != null) { - exceptionHandler.handle(cause); - } - } - - @Override - public ExecutionContext prepare() { - // No preparation required. - return this; - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/pool/AsyncConnectionPool.java b/src/main/java/io/vertx/ext/asyncsql/impl/pool/AsyncConnectionPool.java deleted file mode 100644 index 6f434ff4..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/pool/AsyncConnectionPool.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl.pool; - -import com.github.mauricio.async.db.Configuration; -import com.github.mauricio.async.db.Connection; -import io.vertx.core.AsyncResult; -import io.vertx.core.Future; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.core.logging.Logger; -import io.vertx.core.logging.LoggerFactory; -import io.vertx.ext.asyncsql.impl.ScalaUtils; -import io.vertx.ext.asyncsql.impl.VertxEventLoopExecutionContext; - -import java.util.ArrayDeque; -import java.util.Deque; - -/** - * Manages a pool of connection. - * - * @author Clement Escoffier - */ -public abstract class AsyncConnectionPool { - - public static final int DEFAULT_MAX_POOL_SIZE = 10; - public static final int DEFAULT_MAX_CONNECTION_RETRIES = 0; // No connection retries by default - public static final int DEFAULT_CONNECTION_RETRY_DELAY = 5_000; // 5 seconds between retries by default - - private static final Logger logger = LoggerFactory.getLogger(AsyncConnectionPool.class); - - private final int maxPoolSize; - private final int maxConnectionRetries; - private final int connectionRetryDelay; - - protected final Configuration connectionConfig; - protected final Vertx vertx; - - private int poolSize = 0; - private final Deque availableConnections = new ArrayDeque<>(); - private final Deque>> waiters = new ArrayDeque<>(); - - public AsyncConnectionPool(Vertx vertx, JsonObject globalConfig, Configuration connectionConfig) { - this.vertx = vertx; - this.maxPoolSize = globalConfig.getInteger("maxPoolSize", DEFAULT_MAX_POOL_SIZE); - this.maxConnectionRetries = globalConfig.getInteger("maxConnectionRetries", DEFAULT_MAX_CONNECTION_RETRIES); - this.connectionRetryDelay = globalConfig.getInteger("connectionRetryDelay", DEFAULT_CONNECTION_RETRY_DELAY); - this.connectionConfig = connectionConfig; - } - - protected abstract Connection create(); - - private synchronized void createConnection(Handler> handler) { - poolSize += 1; - createAndConnect(new Handler>() { - int retries = 0; - @Override - public void handle(AsyncResult connectionResult) { - if (connectionResult.succeeded()) { - handler.handle(connectionResult); - } else if (maxConnectionRetries < 0 || retries < maxConnectionRetries) { - retries++; - logger.debug("Error creating connection. Waiting " + connectionRetryDelay + " ms for retry " + - retries + (maxConnectionRetries >= 0 ? " of " + maxConnectionRetries : "")); - vertx.setTimer(connectionRetryDelay, timerId -> - createAndConnect(this) // Try to connect again using this handler - ); - } else { - poolSize -= 1; - notifyWaitersAboutAvailableConnection(); - handler.handle(connectionResult); - } - } - }); - } - - private synchronized void createAndConnect(Handler> handler) { - try { - create() - .connect() - .onComplete(ScalaUtils.toFunction1(handler), VertxEventLoopExecutionContext.create(vertx)); - } catch (Throwable e) { - logger.info("creating a connection went wrong", e); - handler.handle(Future.failedFuture(e)); - } - } - - private synchronized void waitForAvailableConnection(Handler> handler) { - waiters.add(handler); - } - - private synchronized void createOrWaitForAvailableConnection(Handler> handler) { - if (poolSize < maxPoolSize) { - createConnection(handler); - } else { - waitForAvailableConnection(handler); - } - } - - public synchronized void take(Handler> handler) { - Connection connection = availableConnections.poll(); - if (connection == null) { - createOrWaitForAvailableConnection(handler); - } else { - if (connection.isConnected()) { - handler.handle(Future.succeededFuture(connection)); - } else { - poolSize -= 1; - take(handler); - } - } - } - - private synchronized void notifyWaitersAboutAvailableConnection() { - Handler> handler = waiters.poll(); - if (handler != null) { - take(handler); - } - } - - public synchronized void giveBack(Connection connection) { - if (connection.isConnected()) { - availableConnections.add(connection); - } else { - poolSize -= 1; - } - notifyWaitersAboutAvailableConnection(); - } - - public synchronized void close() { - availableConnections.forEach(Connection::disconnect); - } - - public synchronized void close(Handler> handler) { - close(); - if (handler != null) { - handler.handle(Future.succeededFuture()); - } - } -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/pool/MysqlAsyncConnectionPool.java b/src/main/java/io/vertx/ext/asyncsql/impl/pool/MysqlAsyncConnectionPool.java deleted file mode 100644 index 6e491901..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/pool/MysqlAsyncConnectionPool.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl.pool; - -import com.github.mauricio.async.db.Configuration; -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.mysql.MySQLConnection; -import com.github.mauricio.async.db.mysql.util.CharsetMapper; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.impl.VertxEventLoopExecutionContext; - -/** - * Implementation of the {@link AsyncConnectionPool} for MySQL. - * - * @author Clement Escoffier - */ -public class MysqlAsyncConnectionPool extends AsyncConnectionPool { - - public MysqlAsyncConnectionPool(Vertx vertx, JsonObject globalConfig, Configuration connectionConfig) { - super(vertx, globalConfig, connectionConfig); - } - - @Override - protected Connection create() { - return new MySQLConnection(connectionConfig, CharsetMapper.Instance(), - vertx.nettyEventLoopGroup().next(), - VertxEventLoopExecutionContext.create(vertx) - ); - } - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/impl/pool/PostgresqlAsyncConnectionPool.java b/src/main/java/io/vertx/ext/asyncsql/impl/pool/PostgresqlAsyncConnectionPool.java deleted file mode 100644 index 63f3e92e..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/impl/pool/PostgresqlAsyncConnectionPool.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl.pool; - -import com.github.mauricio.async.db.Configuration; -import com.github.mauricio.async.db.Connection; -import com.github.mauricio.async.db.postgresql.PostgreSQLConnection; -import com.github.mauricio.async.db.postgresql.column.PostgreSQLColumnDecoderRegistry; -import com.github.mauricio.async.db.postgresql.column.PostgreSQLColumnEncoderRegistry; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.impl.VertxEventLoopExecutionContext; - -/** - * Implementation of the {@link AsyncConnectionPool} for PostGresSQL. - * - * @author Clement Escoffier - */ -public class PostgresqlAsyncConnectionPool extends AsyncConnectionPool { - - public PostgresqlAsyncConnectionPool(Vertx vertx, JsonObject globalConfig, Configuration connectionConfig) { - super(vertx, globalConfig, connectionConfig); - } - - @Override - protected Connection create() { - return new PostgreSQLConnection( - connectionConfig, - PostgreSQLColumnEncoderRegistry.Instance(), - PostgreSQLColumnDecoderRegistry.Instance(), - vertx.nettyEventLoopGroup().next(), - VertxEventLoopExecutionContext.create(vertx) - ); - } - -} diff --git a/src/main/java/io/vertx/ext/asyncsql/package-info.java b/src/main/java/io/vertx/ext/asyncsql/package-info.java deleted file mode 100644 index 8b20a345..00000000 --- a/src/main/java/io/vertx/ext/asyncsql/package-info.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ -@ModuleGen(name = "vertx-mysql-postgresql", groupPackage = "io.vertx") package io.vertx.ext.asyncsql; - -import io.vertx.codegen.annotations.ModuleGen; diff --git a/src/test/java/io/vertx/ext/asyncsql/AbstractTestBase.java b/src/test/java/io/vertx/ext/asyncsql/AbstractTestBase.java deleted file mode 100644 index 389502eb..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/AbstractTestBase.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.vertx.ext.asyncsql; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.sql.SQLConnection; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; - -@RunWith(VertxUnitRunner.class) -public abstract class AbstractTestBase { - - protected SQLClient client; - protected SQLClient clientNoDatabase; - protected static Vertx vertx; - protected SQLConnection conn; - - @BeforeClass - public static void setUp() { - vertx = Vertx.vertx(); - } - - @AfterClass - public static void tearDown(TestContext context) { - vertx.close(context.asyncAssertSuccess()); - } - - @After - public void cleanup(TestContext context) { - if (conn != null) { - conn.close(context.asyncAssertSuccess()); - } - if (client != null) { - client.close(context.asyncAssertSuccess()); - } - } - - protected void ensureSuccess(TestContext context, AsyncResult result) { - if (result.failed()) { - context.fail(result.cause()); - } - } - - protected Handler> onSuccess(TestContext context, Handler fn) { - return ar -> { - if (ar.succeeded()) { - fn.handle(ar.result()); - } else { - context.fail("Should have been a success"); - } - }; - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/ConfigurationTest.java b/src/test/java/io/vertx/ext/asyncsql/ConfigurationTest.java deleted file mode 100644 index 2b695728..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/ConfigurationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package io.vertx.ext.asyncsql; - -import com.github.mauricio.async.db.exceptions.ConnectionTimeoutedException; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.TimeoutException; - -public abstract class ConfigurationTest extends AbstractTestBase { - - protected abstract SQLClient createClient(Vertx vertx, JsonObject config); - - protected abstract String sleepCommand(int seconds); - - protected abstract String getEncodingStatement(); - - protected abstract String getEncodingValueFromResults(List results); - - @Test - public void testCharset(TestContext context) { - Async async = context.async(); - showEncoding(context, "iso-8859-1", encoding1 -> { - showEncoding(context, "utf-8", encoding2 -> { - context.assertNotEquals(encoding1, encoding2); - async.complete(); - }); - }); - } - - private void showEncoding(TestContext context, String charSetString, Handler encodingHandler) { - - client = createClient(vertx, - new JsonObject() - .put("charset", charSetString) - ); - - client.getConnection(sqlConnectionAsyncResult -> { - ensureSuccess(context, sqlConnectionAsyncResult); - conn = sqlConnectionAsyncResult.result(); - conn.query(getEncodingStatement(), showEncodingAr -> { - ensureSuccess(context, showEncodingAr); - String encoding = getEncodingValueFromResults(showEncodingAr.result().getResults()); - conn.close(connCloseAr -> { - ensureSuccess(context, connCloseAr); - conn = null; - - client.close(clientCloseAr -> { - ensureSuccess(context, clientCloseAr); - client = null; - - encodingHandler.handle(encoding); - - }); - }); - }); - }); - } - - @Ignore("Not implemented in driver yet, see https://github.com/mauricio/postgresql-async/issues/6") - @Test - public void testConnectionTimeout(TestContext context) { - Async async = context.async(); - client = createClient(vertx, - new JsonObject() - .put("connectTimeout", Long.parseLong(System.getProperty("db.connectTimeout", "1"))) - ); - - client.getConnection(sqlConnectionAsyncResult -> { - if (sqlConnectionAsyncResult.failed()) { - context.assertTrue(sqlConnectionAsyncResult.cause() instanceof ConnectionTimeoutedException); - async.complete(); - } else { - context.fail("Should fail due to a connection timeout exception"); - } - }); - } - - @Test - public void testQueryTimeout(TestContext context) { - Async async = context.async(); - client = createClient(vertx, - new JsonObject() - .put("queryTimeout", Long.parseLong(System.getProperty("db.queryTimeout", "1"))) - ); - - client.getConnection(sqlConnectionAsyncResult -> { - conn = sqlConnectionAsyncResult.result(); - conn.query("SELECT " + sleepCommand(2), ar -> { - if (ar.failed()) { - context.assertTrue(ar.cause() instanceof TimeoutException); - async.complete(); - } else { - context.fail("Should fail due to a connection timeout exception"); - } - }); - }); - } - -} diff --git a/src/test/java/io/vertx/ext/asyncsql/Data.java b/src/test/java/io/vertx/ext/asyncsql/Data.java deleted file mode 100644 index 4f0ec7b3..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/Data.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -public class Data { - - public static final List NAMES = Arrays.asList( - "Albert", "Bertram", "Cornelius", "Dieter", "Emil", "Friedrich", "Gustav", "Heinrich", "Ingolf", - "Johann", "Klaus", "Ludwig", "Max", "Norbert", "Otto", "Paul", "Quirin", "Rudolf", "Stefan", "Thorsten", "Ulrich", - "Viktor", "Wilhelm", "Xaver", "Yoda", "Zacharias" - ); - - public static final Map TABLE = new TreeMap<>(); - - static { - int i = 0; - for (String n : NAMES) { - TABLE.put(i, n); - i++; - } - } - - public static String get() { - StringBuilder builder = new StringBuilder(); - for (Map.Entry entry : TABLE.entrySet()) { - if (builder.length() != 0) { - builder.append(","); - } - builder - .append("(") - .append(entry.getKey()) - .append(",") - .append("'") - .append(entry.getValue()) - .append("'") - .append(")"); - } - return builder.toString(); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/MySQLClientTest.java b/src/test/java/io/vertx/ext/asyncsql/MySQLClientTest.java deleted file mode 100644 index 057944de..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/MySQLClientTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.ext.asyncsql.category.NeedsDocker; -import org.junit.*; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.sql.SQLConnection; -import io.vertx.ext.sql.UpdateResult; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.MySQLContainer; - -@Category(NeedsDocker.class) -public class MySQLClientTest extends SQLTestBase { - - public static GenericContainer mysql = new MySQLContainer("mysql:5.6") - .withDatabaseName(MYSQL_DATABASE) - .withUsername(MYSQL_USERNAME) - .withPassword(MYSQL_PASSWORD) - .withExposedPorts(3306); - - static { - mysql.start(); - } - - @Before - public void init() { - mysql.start(); - client = MySQLClient.createNonShared(vertx, new JsonObject() - .put("host", mysql.getContainerIpAddress()) - .put("port", mysql.getMappedPort(3306)) - .put("database", MYSQL_DATABASE) - .put("username", MYSQL_USERNAME) - .put("password", MYSQL_PASSWORD)); - clientNoDatabase = MySQLClient.createNonShared(vertx, - new JsonObject() - .put("host", "localhost") - .put("port", 65000) - .put("maxPoolSize", 2) - ); - } - - // Configure the expected time used in the date test - - /** - * @return the String form of the time returned for "2015-02-22T07:15:01.234". - */ - @Override - public String getExpectedTime1() { - return "2015-02-22T07:15:01.000"; - } - - /** - * @return the String form of the time returned for "2014-06-27T17:50:02.468". - */ - @Override - public String getExpectedTime2() { - return "2014-06-27T17:50:02.000"; - } - - @Override - protected void setSqlModeIfPossible(Handler handler) { - conn.execute("set SQL_MODE = 'STRICT_ALL_TABLES'", ar1 -> { - // INFO: we ignore the result of this call because it is a mysql specific feature and not all versions support it - // what is means is that we want the sql parser to be strict even if the engine e.g.: myisam does not implement - // all constraints such as is the date Feb 31 a valid date. By specifying this we will tell for example that the - // previous date is invalid. - handler.handle(null); - }); - } - - @Test - public void testInsertedIds(TestContext context) { - String name1 = "Adele"; - String name2 = "Betty"; - Async async = context.async(); - - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupAutoIncrementTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.updateWithParams("INSERT INTO test_table (name) VALUES (?)", new JsonArray().add(name1), ar3 -> { - ensureSuccess(context, ar3); - UpdateResult updateResult1 = ar3.result(); - long id1 = updateResult1.getKeys().getLong(0); - conn.updateWithParams("INSERT INTO test_table (name) VALUES (?)", new JsonArray().add(name2), ar4 -> { - ensureSuccess(context, ar4); - UpdateResult updateResult2 = ar4.result(); - long id2 = updateResult2.getKeys().getLong(0); - checkConsistency(context, async, conn, id1, name1, id2, name2); - }); - }); - }); - }); - } - - @Override - protected void compareInstantStrings(TestContext context, String result, String expected) { - // mysql will perform some rounding since it does not have the precision to store the full TS - - // this will perform a small hack it will parse the dates and assert that they difference is less or equal to 1 second - JsonObject test = new JsonObject() - .put("expected", expected + "Z") - .put("result", result + "Z"); - - final int oneSecond = 1000000000; - - context.assertTrue(Math.abs(test.getInstant("expected").getNano() - test.getInstant("result").getNano()) <= oneSecond); - } - - @Override - protected void compareTimeStrings(TestContext context, String result, String expected) { - // MySQL always only delivers seconds and truncates milliseconds to ".000" - context.assertEquals(result, expected.replaceAll("\\.\\d{3}$", ".000")); - } - - @Override - protected String createByteArray1TableColumn() { - return "BIT(1)"; - } - - @Override - protected String createByteArray2TableColumn() { - return "BIT(2)"; - } - - @Override - protected String createByteArray3TableColumn() { - return "BIT(9)"; - } - - @Override - protected String[] insertByteArray1Values() { - return new String[]{"B'1'", "B'0'", "B'1'"}; - } - - @Override - protected String[] insertByteArray2Values() { - return new String[]{"B'10'", "B'01'", "B'11'"}; - } - - @Override - protected String[] insertByteArray3Values() { - return new String[]{"B'100000000'", "B'000000001'", "B'100000001'"}; - } - - private void setupAutoIncrementTable(SQLConnection conn, Handler> handler) { - conn.execute("BEGIN", - ar -> conn.execute("DROP TABLE IF EXISTS test_table", - ar2 -> conn.execute("CREATE TABLE test_table (id BIGINT AUTO_INCREMENT, name VARCHAR(255), PRIMARY KEY(id))", - ar3 -> conn.execute("COMMIT", handler::handle)))); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/MySQLConfigurationTest.java b/src/test/java/io/vertx/ext/asyncsql/MySQLConfigurationTest.java deleted file mode 100644 index 31fd0917..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/MySQLConfigurationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package io.vertx.ext.asyncsql; - -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.category.NeedsDocker; -import io.vertx.ext.sql.SQLClient; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.MySQLContainer; - -import java.util.List; - -import static io.vertx.ext.asyncsql.SQLTestBase.*; - -/** - * Tests the configuration options of the MySQL client. - */ -@Category(NeedsDocker.class) -public class MySQLConfigurationTest extends ConfigurationTest { - - public static GenericContainer mysql = new MySQLContainer("mysql:5.6") - .withDatabaseName(MYSQL_DATABASE) - .withUsername(MYSQL_USERNAME) - .withPassword(MYSQL_PASSWORD) - .withExposedPorts(3306); - - static { - mysql.start(); - } - - @Override - protected SQLClient createClient(Vertx vertx, JsonObject config) { - return MySQLClient.createNonShared(vertx, config.mergeIn(new JsonObject() - .put("host", mysql.getContainerIpAddress()) - .put("port", mysql.getMappedPort(3306)) - .put("database", MYSQL_DATABASE) - .put("username", MYSQL_USERNAME) - .put("password", MYSQL_PASSWORD))); - } - - @Override - public String sleepCommand(int seconds) { - return "sleep(" + seconds + ")"; - } - - @Override - protected String getEncodingStatement() { - return "SHOW VARIABLES LIKE 'character_set_connection'"; - } - - @Override - protected String getEncodingValueFromResults(List results) { - return results.get(0).getString(1); - } - -} diff --git a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLClientTest.java b/src/test/java/io/vertx/ext/asyncsql/PostgreSQLClientTest.java deleted file mode 100644 index 6b6b90cd..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLClientTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.core.AsyncResult; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.category.NeedsDocker; -import io.vertx.ext.sql.ResultSet; -import io.vertx.ext.sql.SQLConnection; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.util.UUID; - -@Category(NeedsDocker.class) -public class PostgreSQLClientTest extends SQLTestBase { - - public static GenericContainer postgresql = new PostgreSQLContainer() - .withDatabaseName(POSTGRESQL_DATABASE) - .withUsername(POSTGRESQL_USERNAME) - .withPassword(POSTGRESQL_PASSWORD) - .withExposedPorts(5432); - - static { - postgresql.start(); - } - - @Before - public void init() { - client = PostgreSQLClient.createNonShared(vertx, new JsonObject() - .put("host", postgresql.getContainerIpAddress()) - .put("port", postgresql.getMappedPort(5432)) - .put("database", POSTGRESQL_DATABASE) - .put("username", POSTGRESQL_USERNAME) - .put("password", POSTGRESQL_PASSWORD)); - - clientNoDatabase = PostgreSQLClient.createNonShared(vertx, - new JsonObject() - .put("host", "localhost") - .put("port", 65000) - .put("maxPoolSize", 2) - ); - } - - // Configure the expected time used in the date test - - - /** - * @return the String form of the time returned for "2015-02-22T07:15:01.234". - */ - @Override - public String getExpectedTime1() { - return "2015-02-22T07:15:01.234"; - } - - /** - * @return the String form of the time returned for "2014-06-27T17:50:02.468". - */ - @Override - public String getExpectedTime2() { - return "2014-06-27T17:50:02.468"; - } - - @Test - public void testInsertedIds(TestContext context) { - String name1 = "Adele"; - String name2 = "Betty"; - Async async = context.async(); - - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupAutoIncrementTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.queryWithParams("INSERT INTO test_table (name) VALUES (?) RETURNING id", new JsonArray().add(name1), ar3 -> { - ensureSuccess(context, ar3); - ResultSet updateResult1 = ar3.result(); - long id1 = updateResult1.getResults().get(0).getLong(0); - conn.queryWithParams("INSERT INTO test_table (name) VALUES (?) RETURNING id", new JsonArray().add(name2), ar4 -> { - ensureSuccess(context, ar4); - ResultSet updateResult2 = ar4.result(); - long id2 = updateResult2.getResults().get(0).getLong(0); - checkConsistency(context, async, conn, id1, name1, id2, name2); - }); - }); - }); - }); - } - - @Test - public void testUsingUUIDsInTables(TestContext context) { - Async async = context.async(); - final UUID uuid = UUID.randomUUID(); - final String name = "xyz"; - - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupTableWithUUIDs(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.queryWithParams("INSERT INTO test_table (some_uuid, name) VALUES (?, ?)", new JsonArray().add(uuid.toString()).add(name), ar3 -> { - ensureSuccess(context, ar3); - conn.queryWithParams("SELECT some_uuid FROM test_table WHERE name = ?", new JsonArray().add(name), ar4 -> { - ensureSuccess(context, ar4); - ResultSet resultSet = ar4.result(); - context.assertEquals(1, resultSet.getNumRows()); - context.assertEquals("some_uuid", resultSet.getColumnNames().get(0)); - context.assertEquals(new JsonObject().put("some_uuid", uuid.toString()), resultSet.getRows().get(0)); - - async.complete(); - }); - }); - }); - }); - } - - @Override - protected String createByteArray1TableColumn() { - return "BYTEA"; - } - - @Override - protected String createByteArray2TableColumn() { - return "BYTEA"; - } - - @Override - protected String createByteArray3TableColumn() { - return "BYTEA"; - } - - @Override - protected String[] insertByteArray1Values() { - return new String[]{"E'\\x01'", "E'\\\\x00'", "E'\\\\x01'"}; - } - - @Override - protected String[] insertByteArray2Values() { - return new String[]{"E'\\\\x02'", "E'\\\\x01'", "E'\\\\x03'"}; - } - - @Override - protected String[] insertByteArray3Values() { - return new String[]{"E'\\\\x0100'", "E'\\\\x0001'", "E'\\\\x0101'"}; - } - - private void setupAutoIncrementTable(SQLConnection conn, Handler> handler) { - conn.execute("BEGIN", - ar -> conn.execute("DROP TABLE IF EXISTS test_table", - ar2 -> conn.execute("CREATE TABLE test_table (id BIGSERIAL, name VARCHAR(255), PRIMARY KEY(id))", - ar3 -> conn.execute("COMMIT", handler::handle)))); - } - - private void setupTableWithUUIDs(SQLConnection conn, Handler> handler) { - conn.execute("BEGIN", - ar -> conn.execute("DROP TABLE IF EXISTS test_table", - ar2 -> conn.execute("CREATE TABLE test_table (some_uuid UUID, name VARCHAR(255))", - ar3 -> conn.execute("COMMIT", handler::handle)))); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLConfigurationTest.java b/src/test/java/io/vertx/ext/asyncsql/PostgreSQLConfigurationTest.java deleted file mode 100644 index 6a48d8b6..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLConfigurationTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package io.vertx.ext.asyncsql; - -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.category.NeedsDocker; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.util.List; - -import static io.vertx.ext.asyncsql.SQLTestBase.*; - -/** - * Tests the configuration options of the PostgreSQL client. - */ -@Category(NeedsDocker.class) -public class PostgreSQLConfigurationTest extends ConfigurationTest { - - public static GenericContainer postgresql = new PostgreSQLContainer() - .withDatabaseName(POSTGRESQL_DATABASE) - .withUsername(POSTGRESQL_USERNAME) - .withPassword(POSTGRESQL_PASSWORD) - .withExposedPorts(5432); - - static { - postgresql.start(); - } - - @Override - protected SQLClient createClient(Vertx vertx, JsonObject config) { - return PostgreSQLClient.createNonShared(vertx, config.mergeIn(new JsonObject() - .put("host", postgresql.getContainerIpAddress()) - .put("port", postgresql.getMappedPort(5432)) - .put("database", POSTGRESQL_DATABASE) - .put("username", POSTGRESQL_USERNAME) - .put("password", POSTGRESQL_PASSWORD))); - } - - @Test - public void testPreferSslConfigurationOnNoneSSLInstance(TestContext context) { - Async async = context.async(); - - SQLClient clientSsl = createClient(vertx, new JsonObject().put("sslMode", "prefer")); - - clientSsl.getConnection(sqlConnectionAsyncResult -> { - context.assertTrue(sqlConnectionAsyncResult.succeeded()); - conn = sqlConnectionAsyncResult.result(); - conn.query("SELECT 1", ar -> { - if (ar.failed()) { - context.fail("Should not fail on ssl connection"); - } else { - async.complete(); - } - }); - }); - } - - @Override - public String sleepCommand(int seconds) { - return "pg_sleep(" + seconds + ")"; - } - - @Override - protected String getEncodingStatement() { - return "SHOW client_encoding"; - } - - @Override - protected String getEncodingValueFromResults(List results) { - return results.get(0).getString(0); - } - -} diff --git a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLSslConfigurationTest.java b/src/test/java/io/vertx/ext/asyncsql/PostgreSQLSslConfigurationTest.java deleted file mode 100644 index e66e73d9..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLSslConfigurationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package io.vertx.ext.asyncsql; - -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.category.NeedsDocker; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.*; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.util.List; - -import static io.vertx.ext.asyncsql.SQLTestBase.*; -import static org.testcontainers.containers.BindMode.READ_ONLY; - -/** - * Tests the configuration options of the PostgreSQL client. - */ -@Category(NeedsDocker.class) -public class PostgreSQLSslConfigurationTest extends ConfigurationTest { - - public static GenericContainer postgresql = new PostgreSQLContainer() - .withDatabaseName(POSTGRESQL_DATABASE) - .withUsername(POSTGRESQL_USERNAME) - .withPassword(POSTGRESQL_PASSWORD) - .withExposedPorts(5432) - .withClasspathResourceMapping("/ssl-docker/server.crt","/docker-entrypoint-initdb.d/server.crt", READ_ONLY) - .withClasspathResourceMapping("/ssl-docker/server.key","/docker-entrypoint-initdb.d/server.key", READ_ONLY) - .withClasspathResourceMapping("/ssl-docker/init.sh","/docker-entrypoint-initdb.d/init.sh", READ_ONLY); - - static { - postgresql.start(); - } - - @Override - protected SQLClient createClient(Vertx vertx, JsonObject config) { - JsonObject json = new JsonObject() - .put("host", postgresql.getContainerIpAddress()) - .put("port", postgresql.getMappedPort(5432)) - .put("database", POSTGRESQL_DATABASE) - .put("username", POSTGRESQL_USERNAME) - .put("password", POSTGRESQL_PASSWORD) - .put("sslMode", "prefer").mergeIn(config.copy()); - System.out.println("Creating client " + json.toString()); - return PostgreSQLClient.createNonShared(vertx, json); - } - - @Override - public String sleepCommand(int seconds) { - return "pg_sleep(" + seconds + ")"; - } - - @Override - protected String getEncodingStatement() { - return "SHOW client_encoding"; - } - - @Override - protected String getEncodingValueFromResults(List results) { - return results.get(0).getString(0); - } - - @Test - public void testCorrectSslConfiguration(TestContext context) { - Async async = context.async(); - String path = getClass() - .getResource("/ssl-docker/server.crt") - .getPath(); - - JsonObject sslConfig = new JsonObject() - .put("sslMode", "require") - .put("sslRootCert", path); - - client = createClient(vertx, sslConfig); - - client.getConnection(sqlConnectionAsyncResult -> { - context.assertTrue(sqlConnectionAsyncResult.succeeded()); - conn = sqlConnectionAsyncResult.result(); - conn.query("SELECT 1", ar -> { - if (ar.failed()) { - context.fail("Should not fail on ssl connection"); - } else { - async.complete(); - } - }); - }); - } - - @Test - public void testWrongSslConfiguration(TestContext context) { - Async async = context.async(); - client = createClient(vertx,new JsonObject() - .put("sslMode", "verify-ca") - .put("sslRootCert", "something-wrong.crt") - ); - - client.getConnection(sqlConnectionAsyncResult -> { - context.assertTrue(sqlConnectionAsyncResult.failed()); - async.complete(); - }); - } - - @Test - public void testPreferSslConfiguration(TestContext context) { - Async async = context.async(); - - SQLClient clientSsl = createClient(vertx, new JsonObject().put("sslMode", "prefer")); - - clientSsl.getConnection(sqlConnectionAsyncResult -> { - context.assertTrue(sqlConnectionAsyncResult.succeeded()); - conn = sqlConnectionAsyncResult.result(); - conn.query("SELECT 1", ar -> { - if (ar.failed()) { - context.fail("Should not fail on ssl connection"); - } else { - async.complete(); - } - }); - }); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLTest.java b/src/test/java/io/vertx/ext/asyncsql/PostgreSQLTest.java deleted file mode 100644 index 51e1baf7..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/PostgreSQLTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.category.NeedsDocker; -import io.vertx.ext.sql.ResultSet; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; - -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.PostgreSQLContainer; - -import static io.vertx.ext.asyncsql.SQLTestBase.*; - -/** - * @author Joern Bernhardt. - */ -@Category(NeedsDocker.class) -public class PostgreSQLTest extends AbstractTestBase { - - public static GenericContainer postgresql = new PostgreSQLContainer() - .withDatabaseName(POSTGRESQL_DATABASE) - .withUsername(POSTGRESQL_USERNAME) - .withPassword(POSTGRESQL_PASSWORD) - .withExposedPorts(5432); - - static { - postgresql.start(); - } - - @Before - public void init() { - client = PostgreSQLClient.createNonShared(vertx, new JsonObject() - .put("host", postgresql.getContainerIpAddress()) - .put("port", postgresql.getMappedPort(5432)) - .put("database", POSTGRESQL_DATABASE) - .put("username", POSTGRESQL_USERNAME) - .put("password", POSTGRESQL_PASSWORD)); - } - - @Test - public void someTest(TestContext context) throws Exception { - Async async = context.async(); - client.getConnection(connAr -> { - ensureSuccess(context, connAr); - conn = connAr.result(); - conn.query("SELECT 1 AS something", resultSetAr -> { - ensureSuccess(context, resultSetAr); - ResultSet resultSet = resultSetAr.result(); - context.assertNotNull(resultSet); - context.assertNotNull(resultSet.getColumnNames()); - context.assertNotNull(resultSet.getResults()); - context.assertEquals(new JsonArray().add(1), resultSet.getResults().get(0)); - async.complete(); - }); - }); - } - - @Test - public void queryTypeTimestampWithTimezoneTest(TestContext context) throws Exception { - Async async = context.async(); - client.getConnection(connAr -> { - ensureSuccess(context, connAr); - conn = connAr.result(); - conn.execute("DROP TABLE IF EXISTS test_table", onSuccess(context, dropped -> { - conn.execute("CREATE TABLE IF NOT EXISTS test_table (ts timestamp with time zone)", onSuccess(context, created -> { - conn.execute("INSERT INTO test_table (ts) VALUES (now())", onSuccess(context, inserted -> { - conn.query("SELECT * FROM test_table;", onSuccess(context, timestampSelect -> { - context.assertNotNull(timestampSelect); - context.assertNotNull(timestampSelect.getResults()); - context.assertTrue(timestampSelect.getResults().get(0).getString(0).matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}(Z|[+-]\\d{2}:\\d{2})")); - async.complete(); - })); - })); - })); - })); - }); - } - - @Test - public void queryTypeTimestampWithoutTimezoneTest(TestContext context) throws Exception { - Async async = context.async(); - client.getConnection(connAr -> { - ensureSuccess(context, connAr); - conn = connAr.result(); - conn.execute("DROP TABLE IF EXISTS test_table", onSuccess(context, dropped -> { - conn.execute("CREATE TABLE IF NOT EXISTS test_table (ts timestamp without time zone)", onSuccess(context, created -> { - conn.execute("INSERT INTO test_table (ts) VALUES (now())", onSuccess(context, inserted -> { - conn.query("SELECT * FROM test_table;", onSuccess(context, timestampSelect -> { - context.assertNotNull(timestampSelect); - context.assertNotNull(timestampSelect.getResults()); - context.assertTrue(timestampSelect.getResults().get(0).getString(0).matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}")); - async.complete(); - })); - })); - })); - })); - }); - } - - @Test - public void testUpdatingNumericField(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - conn.execute("DROP TABLE IF EXISTS test_table", ar1 -> { - ensureSuccess(context, ar1); - conn.execute("CREATE TABLE test_table (id BIGSERIAL, numcol NUMERIC)", ar2 -> { - ensureSuccess(context, ar2); - conn.query("INSERT INTO test_table DEFAULT VALUES RETURNING id", ar3 -> { - ensureSuccess(context, ar3); - final long id = ar3.result().getResults().get(0).getLong(0); - conn.updateWithParams("UPDATE test_table SET numcol = ? WHERE id = ?", new JsonArray().add(1234).add(id), ar4 -> { - ensureSuccess(context, ar4); - conn.updateWithParams("UPDATE test_table SET numcol = ? WHERE id = ?", new JsonArray().addNull().add(id), ar5 -> { - ensureSuccess(context, ar5); - conn.updateWithParams("UPDATE test_table SET numcol = ? WHERE id = ?", new JsonArray().add(123.123).add(id), ar6 -> { - ensureSuccess(context, ar6); - - async.complete(); - }); - }); - }); - }); - }); - }); - }); - } - - @Test - public void queryArrayTypeTest(TestContext context) throws Exception { - Async async = context.async(); - client.getConnection(connAr -> { - ensureSuccess(context, connAr); - conn = connAr.result(); - conn.execute("DROP TABLE IF EXISTS test_table", onSuccess(context, dropped -> { - conn.execute("CREATE TABLE IF NOT EXISTS test_table (arr_int integer[], arr_str text[][])", onSuccess(context, created -> { - conn.execute("INSERT INTO test_table (arr_int,arr_str) VALUES ('{10000, 10000, 10000, 10000}', '{{\"meeting\", \"lunch\"}, {\"training\", \"presentation\"}}')", onSuccess(context, inserted -> { - conn.query("SELECT * FROM test_table;", onSuccess(context, arraySelect -> { - context.assertNotNull(arraySelect); - context.assertNotNull(arraySelect.getResults()); - List results = arraySelect.getResults(); - JsonArray resultRow = results.get(0); - context.assertEquals(resultRow.getJsonArray(0), new JsonArray("[10000,10000,10000,10000]")); - context.assertEquals(resultRow.getJsonArray(1), new JsonArray("[[\"meeting\",\"lunch\"],[\"training\",\"presentation\"]]")); - async.complete(); - })); - })); - })); - })); - }); - } - -} diff --git a/src/test/java/io/vertx/ext/asyncsql/RefCountTest.java b/src/test/java/io/vertx/ext/asyncsql/RefCountTest.java deleted file mode 100644 index 442ceded..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/RefCountTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - -import io.vertx.core.json.JsonObject; -import io.vertx.core.shareddata.LocalMap; -import io.vertx.ext.sql.SQLClient; -import io.vertx.ext.unit.junit.RunTestOnContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import io.vertx.test.core.VertxTestBase; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -/** - * @author Tim Fox - */ -@RunWith(VertxUnitRunner.class) -public class RefCountTest extends VertxTestBase { - - private LocalMap getLocalMap() { - return vertx.sharedData().getLocalMap("__vertx.MySQLPostgreSQL.pools.MySQL"); - } - - @Rule - public RunTestOnContext rule = new RunTestOnContext(); - - @Test - public void testNonShared() { - LocalMap map = getLocalMap(); - JsonObject config = new JsonObject(); - SQLClient client1 = MySQLClient.createNonShared(vertx, config); - assertEquals(1, map.size()); - SQLClient client2 = MySQLClient.createNonShared(vertx, config); - assertEquals(2, map.size()); - SQLClient client3 = MySQLClient.createNonShared(vertx, config); - assertEquals(3, map.size()); - client1.close(); - assertEquals(2, map.size()); - client2.close(); - assertEquals(1, map.size()); - client3.close(); - assertEquals(0, map.size()); - assertWaitUntil(() -> getLocalMap().size() == 0); - assertWaitUntil(() -> map != getLocalMap()); // Map has been closed - } - - @Test - public void testSharedDefault() throws Exception { - LocalMap map = getLocalMap(); - JsonObject config = new JsonObject(); - SQLClient client1 = MySQLClient.createShared(vertx, config); - assertEquals(1, map.size()); - SQLClient client2 = MySQLClient.createShared(vertx, config); - assertEquals(1, map.size()); - SQLClient client3 = MySQLClient.createShared(vertx, config); - assertEquals(1, map.size()); - client1.close(); - assertEquals(1, map.size()); - client2.close(); - assertEquals(1, map.size()); - client3.close(); - assertWaitUntil(() -> map.size() == 0); - assertWaitUntil(() -> map != getLocalMap()); // Map has been closed - } - - @Test - public void testSharedNamed() throws Exception { - LocalMap map = getLocalMap(); - JsonObject config = new JsonObject(); - SQLClient client1 = MySQLClient.createShared(vertx, config, "ds1"); - assertEquals(1, map.size()); - SQLClient client2 = MySQLClient.createShared(vertx, config, "ds1"); - assertEquals(1, map.size()); - SQLClient client3 = MySQLClient.createShared(vertx, config, "ds1"); - assertEquals(1, map.size()); - - SQLClient client4 = MySQLClient.createShared(vertx, config, "ds2"); - assertEquals(2, map.size()); - SQLClient client5 = MySQLClient.createShared(vertx, config, "ds2"); - assertEquals(2, map.size()); - SQLClient client6 = MySQLClient.createShared(vertx, config, "ds2"); - assertEquals(2, map.size()); - - client1.close(); - assertEquals(2, map.size()); - client2.close(); - assertEquals(2, map.size()); - client3.close(); - assertWaitUntil(() -> map.size() == 1); - - client4.close(); - assertEquals(1, map.size()); - client5.close(); - assertEquals(1, map.size()); - client6.close(); - assertWaitUntil(() -> map.size() == 0); - assertWaitUntil(() -> map != getLocalMap()); // Map has been closed - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/SQLTestBase.java b/src/test/java/io/vertx/ext/asyncsql/SQLTestBase.java deleted file mode 100644 index 4d853464..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/SQLTestBase.java +++ /dev/null @@ -1,952 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql; - - -import io.vertx.core.AsyncResult; -import io.vertx.core.Context; -import io.vertx.core.Handler; -import io.vertx.core.json.JsonArray; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.sql.ResultSet; -import io.vertx.ext.sql.SQLConnection; -import io.vertx.ext.sql.SQLRowStream; -import io.vertx.ext.sql.UpdateResult; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import org.junit.Test; - -import java.math.BigDecimal; -import java.time.Instant; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static java.util.concurrent.TimeUnit.SECONDS; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.*; - -public abstract class SQLTestBase extends AbstractTestBase { - - static final String POSTGRESQL_DATABASE = "testdb"; - static final String POSTGRESQL_USERNAME = "vertx"; - static final String POSTGRESQL_PASSWORD = "password"; - - static final String MYSQL_DATABASE = "testdb"; - static final String MYSQL_USERNAME = "vertx"; - static final String MYSQL_PASSWORD = "password"; - - - - @Test - public void testSimpleConnection(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - conn = ar.result(); - conn.query("SELECT 1 AS something", ar2 -> { - if (ar2.failed()) { - context.fail(ar2.cause()); - } else { - ResultSet result = ar2.result(); - context.assertNotNull(result); - JsonObject expected = new JsonObject() - .put("columnNames", new JsonArray().add("something")) - .put("numColumns", 1) - .put("numRows", 1) - .put("rows", new JsonArray().add(new JsonObject().put("something", 1))) - .put("results", new JsonArray().add(new JsonArray().add(1))); - context.assertEquals(expected, result.toJson()); - async.complete(); - } - }); - }); - } - - @Test - public void testSimpleSelect(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - // Create table - conn = ar.result(); - setupSimpleTable(conn, ar2 -> conn.queryWithParams("SELECT name FROM test_table WHERE id=?", - new JsonArray().add(2), ar3 -> { - if (ar3.failed()) { - context.fail(ar3.cause()); - } else { - final ResultSet res = ar3.result(); - context.assertNotNull(res); - context.assertEquals(res.getColumnNames().size(), 1); - context.assertEquals(res.getColumnNames().get(0), "name"); - context.assertEquals(Data.NAMES.get(2), res.getResults().get(0).getString(0)); - async.complete(); - } - })); - }); - } - - - @Test - public void testTwoTransactionsAfterEachOther(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - conn = ar.result(); - conn.setAutoCommit(false, ar2 -> { - ensureSuccess(context, ar2); - conn.query("SELECT 1", ar3 -> { - ensureSuccess(context, ar3); - conn.commit(ar4 -> { - ensureSuccess(context, ar4); - conn.query("SELECT 2", ar5 -> { - ensureSuccess(context, ar5); - conn.commit(ar6 -> { - ensureSuccess(context, ar6); - conn.setAutoCommit(true, ar7 -> { - ensureSuccess(context, ar7); - async.complete(); - }); - }); - }); - }); - }); - }); - }); - } - - @Test - public void testUpdatingRow(TestContext context) { - int id = 0; - String name = "Adele"; - - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), - ar3 -> { - ensureSuccess(context, ar3); - UpdateResult updateRes = ar3.result(); - conn.query("SELECT name FROM test_table ORDER BY id", ar4 -> { - ensureSuccess(context, ar4); - ResultSet selectRes = ar4.result(); - context.assertNotNull(updateRes); - context.assertNotNull(selectRes); - context.assertEquals(1, updateRes.getUpdated()); - context.assertEquals("Adele", selectRes.getResults().get(0).getString(0)); - async.complete(); - }); - }); - }); - }); - - } - - - @Test - public void testRollback(TestContext context) { - int id = 0; - String name = "Adele"; - - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.setAutoCommit(false, ar3 -> { - ensureSuccess(context, ar3); - conn.updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), - ar4 -> { - ensureSuccess(context, ar4); - UpdateResult updateRes = ar4.result(); - conn.rollback(ar5 -> { - ensureSuccess(context, ar5); - conn.query("SELECT name FROM test_table ORDER BY id", ar6 -> { - ensureSuccess(context, ar6); - ResultSet selectRes = ar6.result(); - context.assertNotNull(updateRes); - context.assertNotNull(selectRes); - context.assertEquals(1, updateRes.getUpdated()); - context.assertEquals("Albert", - selectRes.getResults().get(0).getString(0)); - async.complete(); - }); - }); - }); - }); - }); - }); - } - - @Test - public void testMultipleConnections(TestContext context) { - int id = 0; - String name = "Adele"; - - SQLConnection[] connections = new SQLConnection[2]; - - Async async1 = context.async(); - Async async2 = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - client.getConnection(ar3 -> { - ensureSuccess(context, ar3); - connections[0] = ar3.result(); - connections[0].setAutoCommit(false, ar31 -> { - ensureSuccess(context, ar31); - connections[0].updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), ar32 -> { - ensureSuccess(context, ar32); - context.assertEquals(ar32.result().getUpdated(), 1); - connections[0].rollback(ar33 -> { - ensureSuccess(context, ar33); - connections[0].close(v -> { - ensureSuccess(context, v); - async1.complete(); - }); - }); - }); - }); - }); - client.getConnection(ar4 -> { - ensureSuccess(context, ar4); - connections[1] = ar4.result(); - connections[1].query("SELECT name FROM test_table ORDER BY id", ar41 -> { - ensureSuccess(context, ar41); - ResultSet resultSet = ar41.result(); - context.assertEquals(resultSet.getResults().get(0).getString(0), "Albert"); - connections[1].close(v -> { - ensureSuccess(context, v); - async2.complete(); - }); - }); - }); - }); - }); - } - - @Test - public void testSetAutocommitWhileInTransaction(TestContext context) { - int id = 0; - String name = "Adele"; - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - client.getConnection(ar3 -> { - ensureSuccess(context, ar3); - SQLConnection conn1 = ar3.result(); - conn1.setAutoCommit(false, ar4 -> { - ensureSuccess(context, ar4); - conn1.updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), - ar5 -> { - ensureSuccess(context, ar5); - conn1.setAutoCommit(true, ar6 -> { - ensureSuccess(context, ar6); - context.assertEquals(1, ar5.result().getUpdated()); - client.getConnection(ar7 -> { - ensureSuccess(context, ar7); - SQLConnection conn2 = ar7.result(); - conn2.query("SELECT name FROM test_table ORDER BY id", ar8 -> { - ensureSuccess(context, ar8); - context.assertEquals(ar8.result().getResults() - .get(0).getString(0), name); - conn2.close(v -> conn1.close(v2 -> async.complete())); - }); - }); - }); - }); - }); - }); - }); - }); - - - } - - @Test - public void testRollingBackWhenNotInTransaction(TestContext context) { - int id = 0; - String name = "adele"; - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.setAutoCommit(false, ar3 -> { - ensureSuccess(context, ar3); - conn.updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), ar4 -> { - ensureSuccess(context, ar4); - conn.setAutoCommit(true, ar5 -> { - ensureSuccess(context, ar5); - conn.rollback(ar6 -> { - context.assertTrue(ar6.failed()); - async.complete(); - }); - }); - }); - }); - }); - }); - } - - @Test - public void testCommitWhenNotInTransaction(TestContext context) { - int id = 0; - String name = "adele"; - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.setAutoCommit(false, ar3 -> { - ensureSuccess(context, ar3); - conn.updateWithParams("UPDATE test_table SET name=? WHERE id=?", - new JsonArray().add(name).add(id), ar4 -> { - ensureSuccess(context, ar4); - conn.setAutoCommit(true, ar5 -> { - ensureSuccess(context, ar5); - conn.commit(ar6 -> { - context.assertTrue(ar6.failed()); - async.complete(); - }); - }); - }); - }); - }); - }); - } - - @Test - public void testInsertion(TestContext context) { - int id = 27; - String name = "Adele"; - Async async = context.async(); - - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - ensureSuccess(context, ar2); - conn.updateWithParams("INSERT INTO test_table (id, name) VALUES (?, ?)", - new JsonArray().add(id).add(name), ar3 -> { - ensureSuccess(context, ar3); - conn.query("SELECT id, name FROM test_table ORDER BY id", ar4 -> { - ensureSuccess(context, ar4); - ResultSet resultSet = ar4.result(); - context.assertEquals("Adele", - resultSet.getResults().get(id - 1).getString(1)); - async.complete(); - }); - }); - }); - }); - } - - @Test - public void testSelectionOfNullValues(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - conn.execute("DROP TABLE IF EXISTS test_nulls_table", ar2 -> { - ensureSuccess(context, ar2); - conn.execute("CREATE TABLE test_nulls_table (id BIGINT, name VARCHAR(255) NULL)", - ar3 -> { - ensureSuccess(context, ar3); - conn.execute("INSERT INTO test_nulls_table (id, name) VALUES (1, NULL)", ar4 -> { - ensureSuccess(context, ar4); - conn.query("SELECT id, name FROM test_nulls_table ORDER BY id", ar5 -> { - ensureSuccess(context, ar5); - ResultSet rs = ar5.result(); - - List columns = rs.getColumnNames(); - context.assertEquals(2, columns.size()); - context.assertEquals(columns.get(0), "id"); - context.assertEquals(columns.get(1), "name"); - - context.assertEquals(rs.getResults().size(), 1); - context.assertEquals(rs.getResults().get(0).getInteger(0), 1); - context.assertEquals(rs.getResults().get(0).getString(1), null); - async.complete(); - }); - }); - }); - }); - }); - } - - // note that mysql and the DDL of the table bellow do not take the TZ in consideration - public static final String insertedTime1 = "2015-02-22T07:15:01.234"; - public static final String insertedTime2 = "2014-06-27T17:50:02.468"; - - /** - * @return the String form of the time returned for "2015-02-22T07:15:01.234". - */ - public abstract String getExpectedTime1(); - - /** - * @return the String form of the time returned for "2014-06-27T17:50:02.468". - */ - public abstract String getExpectedTime2(); - - @Test - public void testDateValueSelection(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - setSqlModeIfPossible(nothing -> { - conn.execute("DROP TABLE IF EXISTS test_date_table", ar2 -> { - ensureSuccess(context, ar2); - conn.execute("CREATE TABLE test_date_table (id BIGINT, some_date DATE,some_timestamp TIMESTAMP)", ar3 -> { - ensureSuccess(context, ar3); - conn.updateWithParams("INSERT INTO test_date_table (id, some_date, some_timestamp) VALUES (?, ?, ?)", new JsonArray().add(1).add("2015-02-22").add(insertedTime1), ar4 -> { - ensureSuccess(context, ar4); - conn.updateWithParams("INSERT INTO test_date_table (id, some_date, some_timestamp) VALUES (?, ?, ?)", new JsonArray().add(2).add("2007-07-20").add(insertedTime2), ar5 -> { - ensureSuccess(context, ar5); - conn.query("SELECT id, some_date, some_timestamp FROM test_date_table ORDER BY id", ar6 -> { - ensureSuccess(context, ar6); - ResultSet results = ar6.result(); - List columns = results.getColumnNames(); - context.assertEquals(3, columns.size()); - context.assertEquals("id", columns.get(0)); - context.assertEquals("some_date", columns.get(1)); - context.assertEquals("some_timestamp", columns.get(2)); - - context.assertEquals(2, results.getResults().size()); - JsonArray row1 = results.getResults().get(0); - context.assertEquals(row1.getString(1), "2015-02-22"); - context.assertEquals(row1.getString(2), getExpectedTime1()); - JsonArray row2 = results.getResults().get(1); - context.assertEquals(row2.getString(1), "2007-07-20"); - context.assertEquals(row2.getString(2), getExpectedTime2()); - - async.complete(); - }); - }); - }); - }); - }); - }); - }); - } - - @Test - public void testDecimalFields(TestContext context) { - Async async = context.async(); - client.getConnection(arConn -> { - ensureSuccess(context, arConn); - conn = arConn.result(); - conn.execute("DROP TABLE IF EXISTS test_table", arDrop -> { - ensureSuccess(context, arDrop); - conn.execute("CREATE TABLE test_table (id INT, some_decimal DECIMAL(65,6))", arCreate -> { - ensureSuccess(context, arCreate); - conn.execute("INSERT INTO test_table (id, some_decimal) VALUES " + - "(1, 43210987654321098765432109876543210987654321098765432109871.123451)," + - "(2, 43210987654321098765432109876543210987654321098765432109872.123452)," + - "(3, 43210987654321098765432109876543210987654321098765432109873.123453)", arInsert -> { - ensureSuccess(context, arInsert); - conn.query("SELECT some_decimal FROM test_table ORDER BY id", arQuery -> { - ensureSuccess(context, arQuery); - ResultSet res = arQuery.result(); - context.assertEquals(new BigDecimal("43210987654321098765432109876543210987654321098765432109871.123451"), new BigDecimal(res.getRows().get(0).getString("some_decimal"))); - context.assertEquals(new BigDecimal("43210987654321098765432109876543210987654321098765432109872.123452"), new BigDecimal(res.getResults().get(1).getString(0))); - context.assertEquals(new BigDecimal("43210987654321098765432109876543210987654321098765432109873.123453"), new BigDecimal(res.getRows().get(2).getString("some_decimal"))); - // This will convert both (big) numbers into a double which will loose some information - context.assertEquals(43210987654321098765432109876543210987654321098765432109873.123453, Double.parseDouble(res.getRows().get(2).getString("some_decimal"))); - async.complete(); - }); - }); - }); - }); - }); - } - - protected abstract String createByteArray1TableColumn(); - - protected abstract String createByteArray2TableColumn(); - - protected abstract String createByteArray3TableColumn(); - - protected abstract String[] insertByteArray1Values(); - - protected abstract String[] insertByteArray2Values(); - - protected abstract String[] insertByteArray3Values(); - - @Test - public void testByteA1Fields(TestContext context) { - Async async = context.async(); - client.getConnection(arConn -> { - ensureSuccess(context, arConn); - conn = arConn.result(); - conn.execute("DROP TABLE IF EXISTS test_table", arDrop -> { - ensureSuccess(context, arDrop); - conn.execute("CREATE TABLE test_table (id INT, some_bit " + createByteArray1TableColumn() + ")", arCreate -> { - ensureSuccess(context, arCreate); - String[] s = insertByteArray1Values(); - conn.execute("INSERT INTO test_table (id, some_bit) VALUES (1, " + s[0] + "),(2, " + s[1] + "),(3, " + s[2] + ")", arInsert -> { - ensureSuccess(context, arInsert); - conn.query("SELECT some_bit FROM test_table ORDER BY id", arQuery -> { - ensureSuccess(context, arQuery); - ResultSet res = arQuery.result(); - context.assertTrue(Arrays.equals(new byte[]{0b1}, res.getRows().get(0).getBinary("some_bit"))); - context.assertTrue(Arrays.equals(new byte[]{0b0}, res.getResults().get(1).getBinary(0))); - context.assertTrue(Arrays.equals(new byte[]{0b1}, res.getRows().get(2).getBinary("some_bit"))); - async.complete(); - }); - }); - }); - }); - }); - } - - @Test - public void testByteA2Fields(TestContext context) { - Async async = context.async(); - client.getConnection(arConn -> { - ensureSuccess(context, arConn); - conn = arConn.result(); - conn.execute("DROP TABLE IF EXISTS test_table", arDrop -> { - ensureSuccess(context, arDrop); - conn.execute("CREATE TABLE test_table (id INT, some_bit " + createByteArray2TableColumn() + ")", arCreate -> { - ensureSuccess(context, arCreate); - String[] s = insertByteArray2Values(); - conn.execute("INSERT INTO test_table (id, some_bit) VALUES (1, " + s[0] + "),(2, " + s[1] + "),(3, " + s[2] + ")", arInsert -> { - ensureSuccess(context, arInsert); - conn.query("SELECT some_bit FROM test_table ORDER BY id", arQuery -> { - ensureSuccess(context, arQuery); - ResultSet res = arQuery.result(); - context.assertTrue(Arrays.equals(new byte[]{0b10}, res.getRows().get(0).getBinary("some_bit"))); - context.assertTrue(Arrays.equals(new byte[]{0b01}, res.getResults().get(1).getBinary(0))); - context.assertTrue(Arrays.equals(new byte[]{0b11}, res.getRows().get(2).getBinary("some_bit"))); - async.complete(); - }); - }); - }); - }); - }); - } - - @Test - public void testByteA3Fields(TestContext context) { - Async async = context.async(); - client.getConnection(arConn -> { - ensureSuccess(context, arConn); - conn = arConn.result(); - conn.execute("DROP TABLE IF EXISTS test_table", arDrop -> { - ensureSuccess(context, arDrop); - conn.execute("CREATE TABLE test_table (id INT, some_bit " + createByteArray3TableColumn() + ")", arCreate -> { - ensureSuccess(context, arCreate); - String[] s = insertByteArray3Values(); - conn.execute("INSERT INTO test_table (id, some_bit) VALUES (1, " + s[0] + "),(2, " + s[1] + "),(3, " + s[2] + ")", arInsert -> { - ensureSuccess(context, arInsert); - conn.query("SELECT some_bit FROM test_table ORDER BY id", arQuery -> { - ensureSuccess(context, arQuery); - ResultSet res = arQuery.result(); - context.assertTrue(Arrays.equals(new byte[]{0b1, 0b0}, res.getRows().get(0).getBinary("some_bit"))); - context.assertTrue(Arrays.equals(new byte[]{0b0, 0b1}, res.getResults().get(1).getBinary(0))); - context.assertTrue(Arrays.equals(new byte[]{0b1, 0b1}, res.getRows().get(2).getBinary("some_bit"))); - async.complete(); - }); - }); - }); - }); - }); - } - - @Test - public void testInvalidInsertStatement(TestContext context) { - Async async = context.async(); - - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - conn.updateWithParams("INVALID INSERT", new JsonArray(), ar2 -> { - if (ar2.failed() && ar2.cause() instanceof com.github.mauricio.async.db.exceptions.DatabaseException) { - async.complete(); - } else { - context.fail("Should receive an exception of type DatabaseException."); - } - }); - }); - } - - // Does not pass with MySQL 5.6 - @Test - public void testInstant(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - conn.execute("DROP TABLE IF EXISTS test_table", ar1 -> { - ensureSuccess(context, ar1); - conn.execute("CREATE TABLE test_table (instant TIMESTAMP)", ar2 -> { - ensureSuccess(context, ar2); - JsonArray args = new JsonArray().add(Instant.now()); - String now = args.getString(0); - conn.queryWithParams("INSERT INTO test_table (instant) VALUES (?)", args, ar3 -> { - ensureSuccess(context, ar3); - conn.query("SELECT instant FROM test_table", ar4 -> { - ensureSuccess(context, ar4); - // timestamps with out time zone are returned as strings, so we must compare to the original instant - // ignoring the timezone offset (meaning ignore everything after char 23) - compareInstantStrings( - context, - ar4.result().getResults().get(0).getString(0), - now.substring(0, 23) - ); - async.complete(); - }); - }); - }); - }); - }); - } - - protected void compareInstantStrings(TestContext context, String result, String expected) { - context.assertEquals(result, expected); - } - - protected void setSqlModeIfPossible(Handler handler) { - handler.handle(null); - } - - protected void checkConsistency(TestContext context, Async async, SQLConnection conn, long id1, String name1, long id2, String name2) { - conn.queryWithParams("SELECT name FROM test_table WHERE id = ?", new JsonArray().add(id1), ar5 -> { - ensureSuccess(context, ar5); - ResultSet resultSet1 = ar5.result(); - context.assertEquals(name1, resultSet1.getResults().get(0).getString(0)); - conn.queryWithParams("SELECT name FROM test_table WHERE id = ?", new JsonArray().add(id2), ar6 -> { - ensureSuccess(context, ar6); - ResultSet resultSet2 = ar6.result(); - context.assertNotEquals(id1, id2); - context.assertEquals(name2, resultSet2.getResults().get(0).getString(0)); - async.complete(); - }); - }); - } - - private void setupSimpleTable(SQLConnection conn, Handler> handler) { - conn.execute("BEGIN", - ar -> conn.execute("DROP TABLE IF EXISTS test_table", - ar2 -> conn.execute(CREATE_TABLE_STATEMENT, - ar3 -> conn.update("INSERT INTO test_table (id, name) VALUES " + Data.get(), - ar4 -> conn.execute("COMMIT", handler))))); - } - - private static final String CREATE_TABLE_STATEMENT = "CREATE TABLE test_table " + - "(id BIGINT, name VARCHAR(255))"; - - @Test - public void testSimpleStream(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - // Create table - conn = ar.result(); - setupSimpleTable(conn, ar2 -> { - - conn.queryStream("SELECT name, id FROM test_table ORDER BY name ASC", ar3 -> { - if (ar3.failed()) { - context.fail(ar3.cause()); - } else { - final SQLRowStream res = ar3.result(); - context.assertNotNull(res); - - final AtomicInteger count = new AtomicInteger(); - - res - .handler(row -> { - context.assertEquals(Data.NAMES.get(count.getAndIncrement()), row.getString(0)); - }) - .endHandler(v -> { - context.assertEquals(Data.NAMES.size(), count.get()); - async.complete(); - }); - } - }); - }); - }); - } - - private void setupTestTable(SQLConnection conn, Supplier idNameValuesSupplier, Handler> handler) { - conn.execute("BEGIN", - ar -> conn.execute("DROP TABLE IF EXISTS test_table", - ar2 -> conn.execute(CREATE_TABLE_STATEMENT, - ar3 -> conn.update("INSERT INTO test_table (id, name) VALUES " + idNameValuesSupplier.get(), - ar4 -> conn.execute("COMMIT", handler))))); - } - - @Test - public void testColumnsFromStream(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - // Create table - conn = ar.result(); - setupTestTable(conn, () -> "(1,'NOTHING')", ar2 -> { - conn.queryStream("SELECT name, id FROM test_table ORDER BY name ASC", ar3 -> { - if (ar3.failed()) { - context.fail(ar3.cause()); - } else { - final SQLRowStream res = ar3.result(); - context.assertNotNull(res); - - // assert that we have columns and they are valid - assertNotNull(res.columns()); - assertEquals(Arrays.asList("name", "id"), res.columns()); - - // assert the collection is immutable - try { - res.columns().add("durp!"); - fail(); - } catch (RuntimeException e) { - // expected! - } - } - async.complete(); - }); - }); - }); - } - - @Test - public void testLongStream(TestContext context) { - final int NUM_ROWS = 10000; - Async async = context.async(); - client.getConnection(ar -> { - if (ar.failed()) { - context.fail(ar.cause()); - return; - } - - // Create and populate table - conn = ar.result(); - - Map data = new HashMap<>(); - for (int i=0; i { - StringBuilder builder = new StringBuilder(); - for (int i=0; i 0) { - builder.append(","); - } - builder.append("(") - .append(i) - .append(",'") - .append(data.get(i)) - .append("')"); - } - return builder.toString(); - }, ar2 -> { - - conn.queryStream("SELECT id, name FROM test_table ORDER BY id ASC", ar3 -> { - if (ar3.failed()) { - context.fail(ar3.cause()); - } else { - final SQLRowStream res = ar3.result(); - context.assertNotNull(res); - - final AtomicInteger count = new AtomicInteger(); - - res - .handler(row -> { - int rowNum = count.getAndIncrement(); - context.assertEquals(rowNum, row.getInteger(0)); - context.assertEquals(data.get(rowNum), row.getString(1)); - - }) - .endHandler(v -> { - context.assertEquals(NUM_ROWS, count.get()); - async.complete(); - }); - } - }); - }); - }); - } - - private static class UserDefinedException extends RuntimeException { - } - - @Test - public void testUncaughtException(TestContext testContext) { - Async async = testContext.async(); - Context context = vertx.getOrCreateContext(); - context.exceptionHandler(throwable -> { - assertThat(throwable, instanceOf(UserDefinedException.class)); - async.complete(); - }); - context.runOnContext(v -> { - client.getConnection(connection -> { - try { - throw new UserDefinedException(); - } finally { - if (connection.succeeded()) { - connection.result().close(); - } - } - }); - }); - } - - @Test - public void testUnavailableDatabase(TestContext testContext) { - Async async = testContext.async(3); - - Handler> handler = new Handler>() { - @Override - public void handle(AsyncResult sqlConnectionAsyncResult) { - testContext.assertFalse(sqlConnectionAsyncResult.succeeded()); - async.countDown(); - } - }; - clientNoDatabase.getConnection(handler); - clientNoDatabase.getConnection(handler); - clientNoDatabase.getConnection(handler); - } - - @Test - public void testTimeColumn(TestContext context) { - Async async = context.async(); - client.getConnection(ar -> { - ensureSuccess(context, ar); - conn = ar.result(); - conn.execute("DROP TABLE IF EXISTS test_table", ar1 -> { - ensureSuccess(context, ar1); - conn.execute("CREATE TABLE test_table (timecolumn TIME)", ar2 -> { - ensureSuccess(context, ar2); - String someTime1 = "11:12:13.456"; - String someTime2 = "01:02:00.120"; - String someTime3 = "00:00:01.001"; - JsonArray args = new JsonArray().add(someTime1).add(someTime2).add(someTime3); - conn.queryWithParams("INSERT INTO test_table (timecolumn) VALUES (?), (?), (?)", args, ar3 -> { - ensureSuccess(context, ar3); - conn.query("SELECT timecolumn FROM test_table", ar4 -> { - ensureSuccess(context, ar4); - String result1 = ar4.result().getResults().get(0).getString(0); - String result2 = ar4.result().getResults().get(1).getString(0); - String result3 = ar4.result().getResults().get(2).getString(0); - compareTimeStrings(context, result1, someTime1); - compareTimeStrings(context, result2, someTime2); - compareTimeStrings(context, result3, someTime3); - async.complete(); - }); - }); - }); - }); - }); - } - - protected void compareTimeStrings(TestContext context, String result, String expected) { - context.assertEquals(result, expected); - } - - @Test - public void testUnhandledExceptionInHandlerResultSet(TestContext testContext) { - this.testUnhandledExceptionInHandler(testContext, (sqlConnection, handler) -> { - sqlConnection.query("SELECT name FROM test_table", handler); - }); - } - - @Test - public void testUnhandledExceptionInHandlerRowStream(TestContext testContext) { - this.testUnhandledExceptionInHandler(testContext, (sqlConnection, handler) -> { - sqlConnection.queryStream("SELECT name FROM test_table", handler); - }); - } - - @Test - public void testUnhandledExceptionInHandlerUpdateResult(TestContext testContext) { - this.testUnhandledExceptionInHandler(testContext, (sqlConnection, handler) -> { - sqlConnection.update("INSERT INTO test_table (name) VALUES ('pimpo')", handler); - }); - } - - private void testUnhandledExceptionInHandler(TestContext testContext, BiConsumer>> testMethod) { - AtomicInteger count = new AtomicInteger(); - Async async = testContext.async(); - Context context = vertx.getOrCreateContext(); - context.exceptionHandler(t -> { - async.complete(); - }).runOnContext(v -> { - client.getConnection(testContext.asyncAssertSuccess(connection -> { - setupSimpleTable(connection, testContext.asyncAssertSuccess(st -> { - vertx.runOnContext(v2 -> { - testMethod.accept(connection, ar -> { - count.incrementAndGet(); - throw new RuntimeException(); - }); - }); - })); - })); - }); - async.await(MILLISECONDS.convert(5, SECONDS)); - assertEquals(1, count.get()); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/category/NeedsDocker.java b/src/test/java/io/vertx/ext/asyncsql/category/NeedsDocker.java deleted file mode 100644 index f5b7ca14..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/category/NeedsDocker.java +++ /dev/null @@ -1,4 +0,0 @@ -package io.vertx.ext.asyncsql.category; - -public interface NeedsDocker { -} diff --git a/src/test/java/io/vertx/ext/asyncsql/impl/MyVerticle.java b/src/test/java/io/vertx/ext/asyncsql/impl/MyVerticle.java deleted file mode 100644 index 7f7431be..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/impl/MyVerticle.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.AbstractVerticle; -import io.vertx.core.Context; -import io.vertx.core.Vertx; -import scala.concurrent.impl.Promise; -import scala.util.Success; - -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -/** - * @author Clement Escoffier - */ -public class MyVerticle extends AbstractVerticle { - - public static final Set CONTEXTS = new CopyOnWriteArraySet<>(); - - @Override - public void start() throws Exception { - final Promise.DefaultPromise promise = new Promise.DefaultPromise<>(); - CONTEXTS.add(context); - promise.onComplete(ScalaUtils.toFunction1(v -> { - if (context != Vertx.currentContext()) { - throw new RuntimeException("Bad context"); - } - CONTEXTS.add(Vertx.currentContext()); - }), VertxEventLoopExecutionContext.create(vertx)); - promise.complete(new Success<>("hello")); - } -} diff --git a/src/test/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContextTest.java b/src/test/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContextTest.java deleted file mode 100644 index a5e87918..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/impl/VertxEventLoopExecutionContextTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl; - -import io.vertx.core.Context; -import io.vertx.core.DeploymentOptions; -import io.vertx.core.Vertx; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import scala.concurrent.impl.Promise; -import scala.util.Success; - -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; - -/** - * @author Clement Escoffier - */ -@RunWith(VertxUnitRunner.class) -public class VertxEventLoopExecutionContextTest { - - protected static Vertx vertx; - - @BeforeClass - public static void setUp() { - vertx = Vertx.vertx(); - } - - @AfterClass - public static void tearDown(TestContext context) { - vertx.close(context.asyncAssertSuccess()); - } - - - @Test - public void testThatTaskSubmittedOnVertxEventLoopAreExecutedOnThisEventLoop(TestContext tc) { - Async async = tc.async(); - vertx.runOnContext(any -> { - final Context context = Vertx.currentContext(); - final Promise.DefaultPromise promise = new Promise.DefaultPromise<>(); - promise.onComplete(ScalaUtils.toFunction1(v -> { - tc.assertEquals(context, Vertx.currentContext()); - async.complete(); - }), VertxEventLoopExecutionContext.create(vertx)); - promise.complete(new Success<>("hello")); - }); - } - - @Test - public void testThatTaskNotSubmittedOnVertxEventLoopAreExecutedOnTheEventLoop(TestContext tc) { - Async async = tc.async(); - final Context context = Vertx.currentContext(); - tc.assertNull(context); - final Promise.DefaultPromise promise = new Promise.DefaultPromise<>(); - promise.onComplete(ScalaUtils.toFunction1(v -> { - tc.assertNotNull(Vertx.currentContext()); - async.complete(); - }), VertxEventLoopExecutionContext.create(vertx)); - promise.complete(new Success<>("hello")); - } - - @Test - public void testWithVerticles(TestContext tc) { - vertx.deployVerticle(MyVerticle.class.getName(), new DeploymentOptions().setInstances(2)); - await().atMost(10, TimeUnit.SECONDS).until(() -> MyVerticle.CONTEXTS.size() == 2); - } - - -} \ No newline at end of file diff --git a/src/test/java/io/vertx/ext/asyncsql/impl/tool/AsyncConnectionPoolTest.java b/src/test/java/io/vertx/ext/asyncsql/impl/tool/AsyncConnectionPoolTest.java deleted file mode 100644 index de090dd3..00000000 --- a/src/test/java/io/vertx/ext/asyncsql/impl/tool/AsyncConnectionPoolTest.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2015 Red Hat, Inc. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Apache License v2.0 which accompanies this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * The Apache License v2.0 is available at - * http://www.opensource.org/licenses/apache2.0.php - * - * You may elect to redistribute this code under either of these licenses. - */ - -package io.vertx.ext.asyncsql.impl.tool; - -import com.github.mauricio.async.db.Connection; -import io.vertx.core.Handler; -import io.vertx.core.Vertx; -import io.vertx.core.json.JsonObject; -import io.vertx.ext.asyncsql.impl.pool.AsyncConnectionPool; -import io.vertx.ext.unit.Async; -import io.vertx.ext.unit.TestContext; -import io.vertx.ext.unit.junit.VertxUnitRunner; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import scala.concurrent.impl.Promise; - -import java.util.LinkedList; -import java.util.Queue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -/** - * AsyncConnectionPoolTest.java - * - * @author Ernesto J. Perez - */ -@RunWith(VertxUnitRunner.class) -public class AsyncConnectionPoolTest { - - private final int MAX_POOL_SIZE = 15; - - private Vertx vertx; - - @Before - public void setUp() { - this.vertx = Mockito.mock(Vertx.class); - Mockito.when(vertx.setTimer(Mockito.anyLong(),Mockito.any())) - .then(invocation -> { - final Handler handler = invocation.getArgument(1); - handler.handle(ThreadLocalRandom.current().nextLong()); - return null; - }); - } - - // We will try to obtain 50 connections from a pool with a maxPoolSize of 15 - @Test - public void testMaxPoolSize(TestContext context) throws InterruptedException { - final int TEST_LENGTH = 50; - final CountDownLatch countDownLatch = new CountDownLatch(TEST_LENGTH); - - final AsyncConnectionPoolMock pool = new AsyncConnectionPoolMock( - new JsonObject().put("maxPoolSize", MAX_POOL_SIZE), - this::getGoodConnection); - - final Queue connectionSet = new LinkedList<>(); - // Ask for 50 connections - for (int i = 0; i < TEST_LENGTH; i++) { - pool.take(result -> { - // We will decrease our CountDownLatch with each obtained connection - countDownLatch.countDown(); - context.assertTrue(result.succeeded()); - connectionSet.add(result.result()); - }); - } - - // Wait up to 1 second to obtain the 50 connections (it should not happen) - context.assertFalse(countDownLatch.await(1, TimeUnit.SECONDS)); - // We will check that we only had 15 connections (MAX_POOL_SIZE) - context.assertEquals(MAX_POOL_SIZE, pool.connectionAttempts); - context.assertEquals(MAX_POOL_SIZE, pool.createdConnections); - context.assertEquals(MAX_POOL_SIZE, connectionSet.size()); - context.assertEquals(TEST_LENGTH - MAX_POOL_SIZE, (int)countDownLatch.getCount()); // Counter should be 35 - - // We will give back the connections one by one. No new connections should be created - for (int i = MAX_POOL_SIZE + 1; i <= TEST_LENGTH; i++) { - pool.giveBack(connectionSet.poll()); - context.assertEquals(MAX_POOL_SIZE, pool.connectionAttempts); - context.assertEquals(MAX_POOL_SIZE, pool.createdConnections); - context.assertEquals(MAX_POOL_SIZE, connectionSet.size()); - context.assertEquals(TEST_LENGTH - i, (int)countDownLatch.getCount()); - } - } - - // Test that by default we don't do any retry - @Test - public void testNoRetriesByDefault(TestContext context) { - - final Async async = context.async(); - - final AsyncConnectionPoolMock pool = new AsyncConnectionPoolMock(new JsonObject(), - this::getFailingConnection); - - pool.take(result -> { - context.assertTrue(result.failed()); - context.assertTrue(result.cause() instanceof RuntimeException); - context.assertEquals(1, pool.connectionAttempts); - context.assertEquals(0, pool.createdConnections); - Mockito.verifyNoMoreInteractions(vertx); - async.complete(); - }); - } - - // Try to obtain a connection and fails in all retries - @Test - public void testRetriesAndFail(TestContext context) { - final int MAX_RETRIES = 5; - - final Async async = context.async(); - - final AsyncConnectionPoolMock pool = new AsyncConnectionPoolMock( - new JsonObject() - .put("maxConnectionRetries", MAX_RETRIES) - .put("connectionRetryDelay", 100L), - this::getFailingConnection); - - pool.take(result -> { - context.assertTrue(result.failed()); - context.assertTrue(result.cause() instanceof RuntimeException); - context.assertEquals(MAX_RETRIES + 1, pool.connectionAttempts); - context.assertEquals(0, pool.createdConnections); - - // Verify the the Vert.x timer has been used 5 times (MAX_RETRIES) - Mockito.verify(vertx, Mockito.times(MAX_RETRIES)).setTimer(Mockito.eq(100L), Mockito.any()); - Mockito.verifyNoMoreInteractions(vertx); - - async.complete(); - }); - } - - // Try to obtain a connection, fails, and success in the last retry - @Test - public void testRetriesAndSuccess(TestContext context) { - final int MAX_RETRIES = 5; - - final Async async = context.async(); - - final AsyncConnectionPoolMock pool = new AsyncConnectionPoolMock( - new JsonObject() - .put("maxConnectionRetries", MAX_RETRIES) - .put("connectionRetryDelay", 100L), - new Supplier() { - int count=0; - @Override public Connection get() { - count++; - if (count < MAX_RETRIES + 1) - return getFailingConnection(); - else - return getGoodConnection(); - } - }); - - pool.take(result -> { - context.assertTrue(result.succeeded()); - context.assertEquals(MAX_RETRIES + 1, pool.connectionAttempts); - context.assertEquals(1, pool.createdConnections); - - // Verify the the Vert.x timer has been used 5 times (MAX_RETRIES) - Mockito.verify(vertx, Mockito.times(MAX_RETRIES)).setTimer(Mockito.eq(100L), Mockito.any()); - async.complete(); - }); - } - - private Connection getGoodConnection() { - final Connection connection = Mockito.mock(Connection.class); - Mockito.when(connection.connect()).thenReturn(new Promise.DefaultPromise().success(connection).future()); - Mockito.when(connection.isConnected()).thenReturn(true); - return connection; - } - - private Connection getFailingConnection() { - throw new RuntimeException("Expected exception"); - } - - /** - * This class just extends from the abstract class AsyncConnectionPool that we want to test. - */ - private class AsyncConnectionPoolMock extends AsyncConnectionPool { - - int connectionAttempts = 0; - int createdConnections = 0; - private Supplier connectionSupplier; - - AsyncConnectionPoolMock(JsonObject globalConfig, Supplier connectionSupplier) { - super(AsyncConnectionPoolTest.this.vertx, globalConfig, null); - this.connectionSupplier = connectionSupplier; - } - - @Override - protected Connection create() { - this.connectionAttempts++; - final Connection connection = connectionSupplier.get(); - this.createdConnections++; - return connection; - } - } -} diff --git a/src/test/resources/docker/start-db.sh b/src/test/resources/docker/start-db.sh deleted file mode 100755 index cf40840c..00000000 --- a/src/test/resources/docker/start-db.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash -./start-mysql.sh -sleep 5 -./start-postgres.sh -sleep 5 -./start-postgres-ssl.sh -sleep 5 -# Since the migration to docker-machine, the startup takes much more time. diff --git a/src/test/resources/docker/start-mysql.sh b/src/test/resources/docker/start-mysql.sh deleted file mode 100755 index b9f88296..00000000 --- a/src/test/resources/docker/start-mysql.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -export MYSQL_DATABASE=testdb -export MYSQL_USER=vertx -export MYSQL_ROOT_PASSWORD=password -export MYSQL_PASSWORD=password - -docker run -d \ - -e MYSQL_USER \ - -e MYSQL_PASSWORD \ - -e MYSQL_ROOT_PASSWORD \ - -e MYSQL_DATABASE \ - --name "some-mysql" \ - -p 3306:3306 \ - "mysql/mysql-server:5.6" - - - diff --git a/src/test/resources/docker/start-postgres-ssl.sh b/src/test/resources/docker/start-postgres-ssl.sh deleted file mode 100755 index fe1ad003..00000000 --- a/src/test/resources/docker/start-postgres-ssl.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env bash - -export POSTGRES_DB=testdb -export POSTGRES_USER=vertx -export POSTGRES_PASSWORD=password - -docker run -d \ - -e POSTGRES_USER \ - -e POSTGRES_PASSWORD \ - -e POSTGRES_DB \ - --name "some-postgres-ssl" \ - -v $(pwd)/src/test/resources/ssl-docker/server.crt:/docker-entrypoint-initdb.d/server.crt \ - -v $(pwd)/src/test/resources/ssl-docker/server.key:/docker-entrypoint-initdb.d/server.key \ - -v $(pwd)/src/test/resources/ssl-docker/init.sh:/docker-entrypoint-initdb.d/init.sh \ - -p 54321:5432 \ - "postgres:9.4.4" - diff --git a/src/test/resources/docker/start-postgres.sh b/src/test/resources/docker/start-postgres.sh deleted file mode 100755 index a8cf2a2f..00000000 --- a/src/test/resources/docker/start-postgres.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -export POSTGRES_DB=testdb -export POSTGRES_USER=vertx -export POSTGRES_PASSWORD=password - -docker run -d \ - -e POSTGRES_USER \ - -e POSTGRES_PASSWORD \ - -e POSTGRES_DB \ - --name "some-postgres" \ - -p 5432:5432 \ - "postgres:9.4.4" - - - diff --git a/src/test/resources/docker/stop-db.sh b/src/test/resources/docker/stop-db.sh deleted file mode 100755 index a371c98c..00000000 --- a/src/test/resources/docker/stop-db.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash -./stop-mysql.sh -./stop-postgres.sh -./stop-postgres-ssl.sh diff --git a/src/test/resources/docker/stop-mysql.sh b/src/test/resources/docker/stop-mysql.sh deleted file mode 100755 index 678b1da2..00000000 --- a/src/test/resources/docker/stop-mysql.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -docker stop some-mysql -docker rm -f some-mysql - - - - diff --git a/src/test/resources/docker/stop-postgres-ssl.sh b/src/test/resources/docker/stop-postgres-ssl.sh deleted file mode 100755 index dd77a6d1..00000000 --- a/src/test/resources/docker/stop-postgres-ssl.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -docker stop some-postgres-ssl -docker rm -f some-postgres-ssl diff --git a/src/test/resources/docker/stop-postgres.sh b/src/test/resources/docker/stop-postgres.sh deleted file mode 100755 index 5a3d4491..00000000 --- a/src/test/resources/docker/stop-postgres.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -docker stop some-postgres -docker rm -f some-postgres diff --git a/src/test/resources/ssl-docker/init.sh b/src/test/resources/ssl-docker/init.sh deleted file mode 100644 index 10c4b873..00000000 --- a/src/test/resources/ssl-docker/init.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -set -e - -echo "SSL INIT SCRIPT RUNNING..." -sed -i 's/^host/hostssl/g' "$PGDATA"/pg_hba.conf - -cp /docker-entrypoint-initdb.d/server.{crt,key} "$PGDATA" -chown postgres:postgres "$PGDATA"/server.{crt,key} -chmod 0600 "$PGDATA"/server.key - -echo "pg_hba.conf now:" -cat "$PGDATA"/pg_hba.conf - -sed -ri "s/^#?(ssl\s*=\s*)\S+/\1'on'/" "$PGDATA/postgresql.conf" - -cat "$PGDATA"/postgresql.conf - -echo "SSL INIT SCRIPT DONE." diff --git a/src/test/resources/ssl-docker/server.crt b/src/test/resources/ssl-docker/server.crt deleted file mode 100644 index 4dadc0ca..00000000 --- a/src/test/resources/ssl-docker/server.crt +++ /dev/null @@ -1,22 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDtTCCAp2gAwIBAgIJALgkNdbdFc/9MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQwHhcNMTcwNjI2MTAwNTIxWhcNMTcwNzI2MTAwNTIxWjBF -MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 -ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEA47bVEKn+W0r2QIMPS2xuxCSUe1SwzcFKm7Br1ymSA6xp4boQXgpPA6f2 -nzviOcoT/c4o/L+UDT5b0VISDd4JdArcKG3HGEeJ6SPHnRtI1HR+X8jTBK4ZqDIE -Ws1ah0e9NiokmCJjl3Z5FzkX9n/EAxiM/MR09rHdcscVLhT4l8Q2fNOLSBkXgQ23 -fDd/cW/DoXSp0ESv0FQpGeQ6XxVAn21KUJCKbILl/Nl++hW/DT7vjnJtAJj84GkQ -j6kC3OA2DpnRdtBNv+B4SHQtCRVCBX8uYrLDuYxa+mLiw3tzEI0qk+i9JjtZptyH -P5B/CkhHlAjPRqH9L03VdzqYGYKgbwIDAQABo4GnMIGkMB0GA1UdDgQWBBSAqhCw -WPgOqUl2F12QauStXSDi1jB1BgNVHSMEbjBsgBSAqhCwWPgOqUl2F12QauStXSDi -1qFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV -BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJALgkNdbdFc/9MAwGA1UdEwQF -MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADAleheNLLcTEAEAcmYGHPU0lKSeeagg -jbYv2UQUNA8aW5R+TtJF9d06F/ECKJdFfaQULjoMdVfin83QKSW73C94KmJ1jGZJ -i3YPWNRbkjlAT6qqQOsR6rJ4+6+8PFhK5vbvtTMuj8ysL/B2TpNS9pD4ztkIRivg -9Mq/5w1yhf4mUMvHjQl87P2Gj2/4m8pSI7zRN+DHCSoBBu3Z8TQzRTeVc2K7ZUQ5 -G/FXWDRKf0RwZu421UcqxSyoyRYLPdCaHW+6o79jGBw16qfaHGSxgWqK4KHehaY2 -8jOsi19AzyTr3ubh67pvqxGi7IC7ICa/xlork6GDNy4h1gB3bnckII0= ------END CERTIFICATE----- diff --git a/src/test/resources/ssl-docker/server.key b/src/test/resources/ssl-docker/server.key deleted file mode 100644 index 7a8c2e07..00000000 --- a/src/test/resources/ssl-docker/server.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA47bVEKn+W0r2QIMPS2xuxCSUe1SwzcFKm7Br1ymSA6xp4boQ -XgpPA6f2nzviOcoT/c4o/L+UDT5b0VISDd4JdArcKG3HGEeJ6SPHnRtI1HR+X8jT -BK4ZqDIEWs1ah0e9NiokmCJjl3Z5FzkX9n/EAxiM/MR09rHdcscVLhT4l8Q2fNOL -SBkXgQ23fDd/cW/DoXSp0ESv0FQpGeQ6XxVAn21KUJCKbILl/Nl++hW/DT7vjnJt -AJj84GkQj6kC3OA2DpnRdtBNv+B4SHQtCRVCBX8uYrLDuYxa+mLiw3tzEI0qk+i9 -JjtZptyHP5B/CkhHlAjPRqH9L03VdzqYGYKgbwIDAQABAoIBAQCr7RnXOBIESYe9 -U3aTwq2qx9eXemz3HG5BOCVj0U4eGenjdMDwz6Wyo/kvZl46tZj8ctA9bEPS7/cR -Bn79G1xV0fFBUQkWCsVUUiBfPP9y8PWNSioQiYZzmDfzesJUC1UPdSgl+SjqbZel -cgTmpraOg9XG7mlE7Su+ghM6tLiwlBbaPwQpsXCAlhW4lmBgaTR7OqdQbOAs8Eav -6oUXeAahZgWRBDbLeBX7xhOOGpQDXcZsayBGQL31bmG0tiIlkkOyPWZMcisHKGzZ -7kRe0UyyTHssQ66NQjJuIy8sOd7r5P7K0yNSnsAQ2oos5ZVun3ogsu/NuTogNpkr -y94999uBAoGBAPM5051kRD30DLdaGnDs+BgfaKnre9rVl30ahbHfwhe1K0Xl/uDE -KLc8hYci1nZ229X3eHTv8lqUEu0bbr8rOz/UScK8V+J8c7YrKGkV81xK7J2lbvhO -3dPoYuxLwPgzgM0uFeUBHiZwxg4+YA8tLtveDHz9fvolyVPF/j2DF6ZBAoGBAO+s -c2jMRxLlX3Xc0QDixqBbPk+gDlkPU3TJt4apJ1PkDR3HD3erwypBjSAgpAJ/5Jf6 -Jfe/Wz8x7EdVSiilt4S9cJJL5UVxIdUoMPAvOLSglDP4kQn3lBjGjG6v2O0pgXZ/ -Dl30JlajPp7WcgBpIupwmHi2aQ81aFV0gwVx3XqvAoGACu0OFIPsjNvptlLV3TzH -6E2A5iEt7yapJ3WJi/QBRA9fYkRyrqYhLhoJ5YgrGic8uN/lCVu+B1Ofhgc1cmD+ -yF9A8P6E9CejCwvlRNM3m23CM1K7KWxhiqNlzjeY841cu9rWIPNr504pl3o11nix -Ii9XYEYC7jnEUX8TbK/24AECgYAvkFu++ntIZrjRHSdlM5wTisgM6Uivp/j5/mYr -lTo2zdVEiZKqPy4WHrgxHgkubc8h0gTi69jh67hmV6jF9E09TJMglWtEorUCJl2/ -7L8mKY//2F6ASd/cItsPxFoahtgoegKR5rgNDYyJ3Sj2p+bD++BmZFzpJcI041B1 -Lim0BQKBgHjwFeeUqxCwIN9o+vau5LF8BsAzbf7eEnUX2qAKTvVUYt4oRdhAtDBp -4WU7wFhO8+q66Ltxthzivhk6Ts93rVRC7QqNSRPDiRPmyRJDegWclFKzkms4+iTf -CLoby0RRwVbA0miAVC8FTKc5iIpS+vd6pTG8O0PMY91SoF2y61Ya ------END RSA PRIVATE KEY-----