Reputation: 75
I'm a noob with vertx, but I have already created the JDBC connection manager using a java class where I can print data from the result set:
ConnectionManager cm=ConnectionManager.getInstance();
Connection conn = cm.getConnection();
try {
Statement stmt=conn.createStatement();
try {
ResultSet rs =
stmt.executeQuery("select username, password from users");
try {
if (rs.next()){
System.out.println(rs.getString(1));
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
conn.close();
}
Now I want to connect my vertx javascript app to this java class. I can't seem to get an idea where to start. I found a few sources from Google Groups, but none of them seem to shed some light:
Loading JDBC Drivers from JavaScript https://groups.google.com/forum/?fromgroups#!topic/vertx/_oJQaeH07Sg
Executing Java from Javascript https://groups.google.com/forum/#!msg/vertx/VyZj2yqqGTM/tvnTg4T55kMJ
I've also found a jdbc-persistor for Vert.x:
JDBC-persistor https://github.com/timyates/mod-jdbc-persistor/
I'm still trying to understand how to use it with my app. I will post whatever information I can share after, but for now, can anyone help me with this (persistor or direct java communication)? Thanks.
Upvotes: 1
Views: 3909
Reputation: 20021
AFAIK the only way to do it is using the event bus. You put your Java code in a Verticle class (or in alternative create a module just for the goal). Something like this
public class JavaFromEverywhere extends Verticle {
@Override
public void start() throws Exception {
vertx.eventBus().registerHandler("invokeFromAnyLanguage", new Handler<Message<String>>(){
public void handle(Message<String> e) {
doSomething();
}
});
}
private void doSomething() {
// your database code here
}
}
Then in your javascript you should just write
vertx.eventBus.send("invokeFromAnyLanguage", "");
This is a simple scenario. If you want do more complex things like sending to your JS the String received from the DB you can extend BusModBase
and send back data. Meanwhile in your JS you should register an handler to handle the reply
public class JavaReply extends BusModBase {
@Override
public void start() {
eb.registerHandler("invokeFromAnyLanguage", new Handler<Message<String>>(){
public void handle(Message<String> e) {
String something = doSomething();
e.reply(something);
}
});
}
private String doSomething() {
// your database code here
return "databaseResult";
}
}
and your JS code would be something like
eb.send("invokeFromAnyLanguage", "", function(javareply) {
// your answer in javareply
});
HTH, Regards
Carlo
Upvotes: 2