Skip to content

Commit 16619ad

Browse files
committed
0.3.0 and async pool
1 parent 2cf3cab commit 16619ad

17 files changed

+227
-222
lines changed

gradle.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ pullInDeps=true
2020
produceJar=false
2121

2222
# The version of the Scala module
23-
scalaLangModVersion=0.2.0
23+
scalaLangModVersion=0.3.0
2424

2525
# The version of Scala to use
2626
scalaVersion=2.10.2

gradle/vertx.gradle

Lines changed: 63 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,4 @@
1-
import org.vertx.java.core.AsyncResult
2-
import org.vertx.java.core.AsyncResultHandler
3-
import org.vertx.java.platform.PlatformLocator
4-
import org.vertx.java.platform.impl.ModuleClassLoader
5-
6-
import java.util.concurrent.CountDownLatch
7-
import java.util.concurrent.TimeUnit
1+
import org.vertx.java.platform.impl.cli.Starter
82

93
/*
104
* Copyright 2012 the original author or authors.
@@ -27,6 +21,8 @@ apply plugin: 'scala'
2721
apply plugin: 'idea'
2822
apply plugin: 'eclipse'
2923

24+
def cpSeparator = System.getProperty("path.separator")
25+
3026
// We have to explicitly load props from the user home dir - on CI we set
3127
// GRADLE_USER_HOME to a different dir to avoid problems with concurrent builds corrupting
3228
// a shared Maven local and using Gradle wrapper concurrently
@@ -44,13 +40,6 @@ targetCompatibility = '1.7'
4440

4541
project.ext.moduleName = "$modowner~$modname~$version"
4642

47-
if (produceJar == 'false') {
48-
jar.enabled = false
49-
assert configurations.archives.artifacts.removeAll { it.file == jar.archivePath }
50-
} else {
51-
52-
}
53-
5443
configurations {
5544
provided
5645
testCompile.extendsFrom provided
@@ -91,6 +80,8 @@ buildscript {
9180
dependencies {
9281
classpath "io.vertx:vertx-core:$vertxVersion"
9382
classpath "io.vertx:vertx-platform:$vertxVersion"
83+
classpath "io.vertx:vertx-hazelcast:$vertxVersion"
84+
classpath files(['src/main/resources'])
9485
}
9586
}
9687

@@ -119,10 +110,26 @@ task modZip( type: Zip, dependsOn: 'pullInDeps', description: 'Package the modul
119110
from copyMod
120111
}
121112

113+
task sourceJar(type: Jar) {
114+
description = 'Builds a source jar artifact suitable for maven deployment.'
115+
classifier = 'sources'
116+
from sourceSets.main.java
117+
}
118+
119+
task javadocJar(type: Jar) {
120+
description = 'Builds a javadoc jar artifact suitable for maven deployment.'
121+
classifier = 'javadoc'
122+
from javadoc.destinationDir
123+
}
124+
javadocJar.dependsOn javadoc
125+
126+
build.dependsOn sourceJar, javadocJar
127+
122128
artifacts {
123-
archives modZip
129+
archives sourceJar, javadocJar, modZip
124130
}
125131

132+
126133
test {
127134
dependsOn copyMod
128135

@@ -137,82 +144,61 @@ test {
137144
systemProperty 'vertx.mods', "build/mods"
138145
}
139146

140-
task runModIDEA(dependsOn: copyMod, description: 'Run the module from the resources in IntelliJ') << {
141-
def classpath = [ new URL('file:src/main/resources/'), new URL('file:src/test/resources/'),
142-
new URL("file:out/production/${project.name}/"), new URL("file:out/test/${project.name}/")] as URL[]
143-
144-
println "file:out/production/${project.name}"
145-
runModWithClasspath(classpath)
146-
}
147-
148-
task runModEclipse(dependsOn: copyMod, description: 'Run the module from the resources in Eclipse') << {
149-
def classpath = [ new URL('file:src/main/resources/'), new URL('file:src/test/resources/'), new URL('file:bin/')] as URL[]
150-
runModWithClasspath(classpath)
151-
}
152-
153-
def runModWithClasspath(URL[] classpath) {
147+
task init(description: 'Create module link and CP file') << {
154148
setSysProps()
155-
def pm = PlatformLocator.factory.createPlatformManager()
156-
def latch = new CountDownLatch(1)
157-
pm.deployModuleFromClasspath(moduleName, null, 1, classpath, new
158-
AsyncResultHandler<String>() {
159-
public void handle(AsyncResult<String> asyncResult) {
160-
if (asyncResult.succeeded()) {
161-
println "CTRL-C to stop server"
162-
} else {
163-
println "Failed to deploy module"
164-
asyncResult.cause().printStackTrace()
165-
latch.countDown()
166-
}
167-
}
168-
});
169-
latch.await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
149+
doInit()
170150
}
171151

172-
task runMod(dependsOn: copyMod, description: 'Run the module using all the build dependencies (not using installed vertx') << {
152+
task runMod(description: 'Run the module') << {
173153
setSysProps()
174154
System.setProperty("vertx.langs.scala", "io.vertx~lang-scala~${scalaLangModVersion}:org.vertx.scala.platform.impl.ScalaVerticleFactory")
175-
def pm = PlatformLocator.factory.createPlatformManager()
176-
def latch = new CountDownLatch(1)
177-
178-
pm.deployModule(moduleName, null, 1, new AsyncResultHandler<String>() {
179-
public void handle(AsyncResult<String> asyncResult) {
180-
if (asyncResult.succeeded()) {
181-
println "CTRL-C to stop server"
182-
} else {
183-
println "Failed to deploy module"
184-
asyncResult.cause().printStackTrace()
185-
latch.countDown()
186-
}
187-
}
188-
});
189-
latch.await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
155+
// We also init here - this means for single module builds the user doesn't have to explicitly init -
156+
// they can just do runMod
157+
doInit()
158+
args = ['runmod', moduleName]
159+
def args2 = runModArgs.split("\\s+")
160+
args.addAll(args2)
161+
Starter.main(args as String[])
162+
}
163+
164+
def doInit() {
165+
File cpFile = new File("vertx_classpath.txt")
166+
if (!cpFile.exists()) {
167+
cpFile.createNewFile();
168+
String defaultCp =
169+
"src/main/resources\r\n" +
170+
"bin\r\n" +
171+
"out/production/${project.name}\r\n" +
172+
"out/test/${project.name}";
173+
cpFile << defaultCp;
174+
}
175+
def args = ['create-module-link', moduleName]
176+
Starter.main(args as String[])
190177
}
191178

192179
task pullInDeps(dependsOn: copyMod, description: 'Pull in all the module dependencies for the module into the nested mods directory') << {
193180
if (pullInDeps == 'true') {
194181
setSysProps()
195-
def pm = PlatformLocator.factory.createPlatformManager()
196-
def latch = new CountDownLatch(1)
197-
println "Pulling in dependencies for module $moduleName. Please wait"
198-
pm.pullInDependencies(moduleName, new AsyncResultHandler<Void>() {
199-
public void handle(AsyncResult<Void> asyncResult) {
200-
if (asyncResult.succeeded()) {
201-
println "Dependencies pulled in successfully"
202-
latch.countDown()
203-
} else {
204-
println "Failed to pull in dependencies"
205-
asyncResult.cause().printStackTrace()
206-
latch.countDown()
207-
}
208-
}
209-
})
210-
latch.await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
182+
def args = ['pulldeps', moduleName]
183+
Starter.main(args as String[])
184+
}
185+
}
186+
187+
task fatJar(dependsOn: modZip, description: 'Creates a fat executable jar which contains everything needed to run the module') << {
188+
if (createFatJar == 'true') {
189+
setSysProps()
190+
def args = ['fatjar', moduleName, '-d', 'build/libs']
191+
Starter.main(args as String[])
211192
}
212193
}
213194

214195
def setSysProps() {
215-
System.setProperty("vertx.mods", "build/mods")
196+
System.setProperty("vertx.clusterManagerFactory", "org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory")
197+
String modsDir = System.getenv("VERTX_MODS")
198+
if (modsDir == null) {
199+
modsDir = "build/mods";
200+
}
201+
System.setProperty("vertx.mods", modsDir)
216202
}
217203

218204
def loadProperties(String sourceFileName) {

src/main/resources/langs.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
scala=io.vertx~lang-scala~0.2.0:org.vertx.scala.platform.impl.ScalaVerticleFactory
1+
scala=io.vertx~lang-scala~0.3.0:org.vertx.scala.platform.impl.ScalaVerticleFactory
22
.scala=scala

src/main/scala/io/vertx/asyncsql/Starter.scala

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.vertx.asyncsql
22

3-
import scala.concurrent.Promise
3+
import scala.annotation.implicitNotFound
4+
import scala.concurrent.{ ExecutionContext, Promise }
45

56
import org.vertx.scala.core.json.{ Json, JsonObject }
67
import org.vertx.scala.platform.Verticle
@@ -15,22 +16,23 @@ class Starter extends Verticle {
1516

1617
override def start(startedResult: Promise[Unit]) = {
1718

18-
logger.error("Starting async database module for MySQL and PostgreSQL.")
19+
logger.info("Starting async database module for MySQL and PostgreSQL.")
1920

2021
try {
2122
val config = Option(container.config()).getOrElse(Json.emptyObj())
2223

2324
val address = config.getString("address", "campudus.asyncdb")
2425
val dbType = getDatabaseType(config)
2526
val configuration = getConfiguration(config, dbType)
27+
val maxPoolSize = config.getInteger("maxPoolSize", 10)
2628

2729
handler = dbType match {
28-
case "postgresql" => new PostgreSqlConnectionHandler(this, configuration)
29-
case "mysql" => new MySqlConnectionHandler(this, configuration)
30+
case "postgresql" => new PostgreSqlConnectionHandler(this, configuration, maxPoolSize)
31+
case "mysql" => new MySqlConnectionHandler(this, configuration, maxPoolSize)
3032
}
3133
vertx.eventBus.registerHandler(address, handler)
3234

33-
logger.error("Async database module for MySQL and PostgreSQL started with config " + configuration)
35+
logger.info("Async database module for MySQL and PostgreSQL started with config " + configuration)
3436

3537
startedResult.success()
3638
} catch {

src/main/scala/io/vertx/asyncsql/database/ConnectionHandler.scala

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,28 +9,36 @@ import org.vertx.scala.platform.Verticle
99
import com.github.mauricio.async.db.{ Configuration, Connection, QueryResult, RowData }
1010
import com.github.mauricio.async.db.postgresql.exceptions.GenericDatabaseException
1111
import io.vertx.asyncsql.database.pool.AsyncConnectionPool
12-
import io.vertx.busmod.ScalaBusMod
1312
import io.vertx.helpers.VertxScalaHelpers
1413
import org.vertx.scala.core.json.Json
14+
import org.vertx.scala.mods.ScalaBusMod
15+
import org.vertx.scala.mods.replies._
16+
import org.vertx.scala.core.Vertx
17+
import org.vertx.scala.platform.Container
18+
import io.vertx.asyncsql.Starter
1519

1620
trait ConnectionHandler extends ScalaBusMod with VertxScalaHelpers {
17-
val verticle: Verticle
21+
val verticle: Starter
1822
def dbType: String
1923
val config: Configuration
24+
val maxPoolSize: Int
25+
26+
lazy val vertx: Vertx = verticle.vertx
27+
lazy val container: Container = verticle.container
2028
lazy val logger: Logger = verticle.logger
21-
val pool = AsyncConnectionPool(verticle.vertx, dbType, config)
29+
lazy val pool = AsyncConnectionPool(verticle, dbType, maxPoolSize, config)
2230

2331
def transactionStart: String = "START TRANSACTION;"
2432
def transactionEnd: String = "COMMIT;"
2533
def statementDelimiter: String = ";"
2634

2735
import org.vertx.scala.core.eventbus._
28-
override def asyncReceive(msg: Message[JsonObject]) = {
36+
override def receive(msg: Message[JsonObject]) = {
2937
case "select" => select(msg.body)
3038
case "insert" => insert(msg.body)
31-
case "prepared" => sendWithPool(prepared(msg.body))
39+
case "prepared" => AsyncReply(sendWithPool(prepared(msg.body)))
3240
case "transaction" => transaction(msg.body)
33-
case "raw" => sendWithPool(rawCommand(msg.body.getString("command")))
41+
case "raw" => AsyncReply(sendWithPool(rawCommand(msg.body.getString("command"))))
3442
}
3543

3644
def close() = pool.close
@@ -52,9 +60,9 @@ trait ConnectionHandler extends ScalaBusMod with VertxScalaHelpers {
5260
}
5361
}
5462

55-
protected def select(json: JsonObject): Future[Reply] = pool.withConnection({ c: Connection =>
63+
protected def select(json: JsonObject): AsyncReply = AsyncReply(pool.withConnection({ c: Connection =>
5664
sendWithPool(rawCommand(selectCommand(json)))
57-
})
65+
}))
5866

5967
protected def insertCommand(json: JsonObject): String = {
6068
val table = json.getString("table")
@@ -73,15 +81,15 @@ trait ConnectionHandler extends ScalaBusMod with VertxScalaHelpers {
7381
.append(listOfLines.mkString(",")).toString
7482
}
7583

76-
protected def insert(json: JsonObject): Future[Reply] = {
84+
protected def insert(json: JsonObject): AsyncReply = AsyncReply {
7785
sendWithPool(rawCommand(insertCommand(json)))
7886
}
7987

8088
sealed trait CommandType { val query: Connection => Future[QueryResult] }
8189
case class Raw(stmt: String) extends CommandType { val query = rawCommand(stmt) }
8290
case class Prepared(json: JsonObject) extends CommandType { val query = prepared(json) }
8391

84-
protected def transaction(json: JsonObject): Future[Reply] = pool.withConnection({ c: Connection =>
92+
protected def transaction(json: JsonObject): AsyncReply = AsyncReply(pool.withConnection({ c: Connection =>
8593
logger.info("TRANSACTION-JSON: " + json.encodePrettily())
8694

8795
Option(json.getArray("statements")) match {
@@ -101,9 +109,10 @@ trait ConnectionHandler extends ScalaBusMod with VertxScalaHelpers {
101109
}
102110
case None => throw new IllegalArgumentException("No 'statements' field in request!")
103111
}
104-
})
112+
}))
105113

106-
protected def sendWithPool(fn: Connection => Future[QueryResult]): Future[Reply] = pool.withConnection({ c: Connection =>
114+
115+
protected def sendWithPool(fn: Connection => Future[QueryResult]): Future[SyncReply] = pool.withConnection({ c: Connection =>
107116
fn(c) map buildResults recover {
108117
case x: GenericDatabaseException =>
109118
Error(x.errorMessage.message)
@@ -118,7 +127,7 @@ trait ConnectionHandler extends ScalaBusMod with VertxScalaHelpers {
118127

119128
protected def rawCommand(command: String): Connection => Future[QueryResult] = { c: Connection => c.sendQuery(command) }
120129

121-
private def buildResults(qr: QueryResult): Reply = {
130+
private def buildResults(qr: QueryResult): SyncReply = {
122131
val result = new JsonObject()
123132
result.putString("message", qr.statusMessage)
124133
result.putNumber("rows", qr.rowsAffected)

src/main/scala/io/vertx/asyncsql/database/MySqlConnectionHandler.scala

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package io.vertx.asyncsql.database
22

33
import org.vertx.scala.platform.Verticle
4-
54
import com.github.mauricio.async.db.Configuration
5+
import io.vertx.asyncsql.Starter
6+
7+
class MySqlConnectionHandler(val verticle: Starter, val config: Configuration, val maxPoolSize: Int) extends ConnectionHandler {
8+
override val dbType: String = "mysql"
69

7-
class MySqlConnectionHandler(val verticle: Verticle, val config: Configuration, val dbType: String = "mysql") extends ConnectionHandler {
810
override protected def escapeField(str: String): String = "`" + str.replace("`", "\\`") + "`"
911
override protected def escapeString(str: String): String = "'" + str.replace("'", "''") + "'"
1012

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package io.vertx.asyncsql.database
22

33
import org.vertx.scala.platform.Verticle
4-
54
import com.github.mauricio.async.db.Configuration
5+
import io.vertx.asyncsql.Starter
66

7-
class PostgreSqlConnectionHandler(val verticle: Verticle, val config: Configuration, val dbType: String = "postgresql") extends ConnectionHandler {
7+
class PostgreSqlConnectionHandler(val verticle: Starter, val config: Configuration, val maxPoolSize: Int) extends ConnectionHandler {
8+
override val dbType: String = "postgresql"
89
}

0 commit comments

Comments
 (0)