├── vertx-lang-js └── src │ ├── main │ ├── docoverride │ │ └── vertx-core │ │ │ └── js │ │ │ └── override │ │ │ ├── dns.adoc │ │ │ ├── json.adoc │ │ │ ├── buffer_from_bytes.adoc │ │ │ ├── eventbus.adoc │ │ │ ├── configuring-native.adoc │ │ │ ├── eventbus_headers.adoc │ │ │ ├── dependencies.adoc │ │ │ ├── verticle-configuration.adoc │ │ │ ├── configuring-eventbus.adoc │ │ │ ├── in-the-beginning.adoc │ │ │ ├── hostname-resolution.adoc │ │ │ └── verticles.adoc │ └── assembly │ │ └── docs.xml │ └── test │ ├── npm │ ├── testmod1 │ │ ├── testmod1_main.js │ │ └── package.json │ └── zip │ │ └── my_npm_module.zip │ ├── resources │ ├── test_verticle_no_vertxstop.js │ ├── somedir │ │ ├── test_mod2.js │ │ └── test_mod3.js │ ├── test_verticle_error.js │ ├── test_verticle_fail.js │ ├── test_mod.js │ ├── test_set_timeout.js │ ├── brokenmodule_typeerror.js │ ├── brokenmodule_syntaxerror.js │ ├── brokenmodule_typeerror2.js │ ├── test_verticle_global.js │ ├── test_verticle_multiple.js │ ├── test_clear_interval.js │ ├── test_clear_timeout.js │ ├── examples │ │ ├── echo_server.js │ │ └── http_server.js │ ├── test_set_interval.js │ ├── test_multiple_concurrent_requires_required.js │ ├── it │ │ ├── web │ │ │ ├── altlang.ftl │ │ │ └── freemarker_javascript_template_test.js │ │ ├── unit │ │ │ ├── coordinated │ │ │ │ ├── server.js │ │ │ │ └── test.js │ │ │ ├── timer.js │ │ │ └── failing.js │ │ ├── healthcheck │ │ │ └── verticle.js │ │ └── discovery │ │ │ └── HelloServiceConsumer.js │ ├── test_multiple_concurrent_requires_verticle.js │ ├── async_test_verticle.js │ ├── test_method_dispatch.js │ ├── test_mod_cached_require.js │ ├── test_verticle_vertxstart.js │ ├── event_bus_test.js │ ├── async_start_test.js │ ├── js_web_test.js │ ├── js_timeout_test.js │ ├── test_verticle.js │ ├── js_verticle_test.js │ └── require_test.js │ ├── asciidoc │ ├── enums.adoc │ └── dataobjects.adoc │ └── java │ └── io │ └── vertx │ └── test │ ├── lang │ └── js │ │ ├── WebTest.java │ │ ├── AsyncStartTest.java │ │ ├── MethodDispatchTest.java │ │ ├── TimeoutTest.java │ │ ├── EventBusTest.java │ │ ├── DeployTest.java │ │ └── RequireTest.java │ └── it │ ├── discovery │ └── service │ │ ├── package-info.java │ │ ├── HelloService.java │ │ ├── HelloServiceImpl.java │ │ ├── HelloServiceVertxEBProxy.java │ │ └── HelloServiceVertxProxyHandler.java │ ├── web │ └── FreeMarkerJavascriptTemplateTest.java │ ├── unit │ └── VertxUnitTest.java │ └── healthcheck │ └── HealthCheckTest.java ├── vertx-lang-js-gen ├── src │ ├── main │ │ ├── resources │ │ │ ├── META-INF │ │ │ │ └── services │ │ │ │ │ ├── io.vertx.docgen.DocGenerator │ │ │ │ │ ├── io.vertx.core.spi.VerticleFactory │ │ │ │ │ └── io.vertx.codegen.GeneratorLoader │ │ │ └── vertx-js │ │ │ │ └── util │ │ │ │ └── console.js │ │ └── java │ │ │ └── io │ │ │ └── vertx │ │ │ └── lang │ │ │ └── js │ │ │ ├── ThrowableConverter.java │ │ │ ├── generator │ │ │ └── JSGeneratorLoader.java │ │ │ ├── SucceededResult.java │ │ │ ├── FailedResult.java │ │ │ ├── JavaArraySetWrapper.java │ │ │ ├── ListConverterSet.java │ │ │ ├── ByteConverterMap.java │ │ │ ├── LongConverterMap.java │ │ │ ├── ShortConverterMap.java │ │ │ ├── VertxGenConverterSet.java │ │ │ ├── VertxGenConverterList.java │ │ │ ├── VertxGenConverterMap.java │ │ │ ├── ClasspathFileResolver.java │ │ │ └── JSDocGenerator.java │ └── test │ │ ├── java │ │ └── io │ │ │ └── vertx │ │ │ └── test │ │ │ ├── codegen │ │ │ ├── package-info.java │ │ │ ├── GenericHolder.java │ │ │ ├── InterfaceWithMethod.java │ │ │ ├── ClassParamOverload.java │ │ │ ├── InterfaceExtendingInterfaceWithMethod.java │ │ │ └── impl │ │ │ │ └── ClassParamOverloadImpl.java │ │ │ ├── lang │ │ │ └── js │ │ │ │ ├── DataObjectTCKTest.java │ │ │ │ ├── JSTestBase.java │ │ │ │ ├── InheritedMethodsTest.java │ │ │ │ ├── ExtraTest.java │ │ │ │ ├── ConstantTCKTest.java │ │ │ │ ├── JSRunner.java~HEAD │ │ │ │ ├── JSRunner.java~HEAD_0 │ │ │ │ ├── JSRunner.java │ │ │ │ ├── FunctionParamTCKTest.java │ │ │ │ └── GenericsTCKTest.java │ │ │ └── ExampleRunner.java │ │ └── resources │ │ ├── test_utils.js │ │ ├── data_object_tck_test.js │ │ ├── extra_test.js │ │ ├── acme-js │ │ ├── sub_interface.js │ │ └── my_interface.js │ │ ├── extra-js │ │ ├── generic_holder.js │ │ └── class_param_overload.js │ │ ├── inherited_methods_test.js │ │ └── constant_tck_test.js └── pom.xml ├── vertx-rx-js ├── src │ ├── test │ │ ├── resources │ │ │ ├── test.js │ │ │ ├── test_observer_to_handler.js │ │ │ ├── test_observable_handler.js │ │ │ ├── test_completed.js │ │ │ ├── test_concat.js │ │ │ ├── test_scheduled_timer.js │ │ │ ├── test_scheduled_buffer.js │ │ │ ├── test_adapt_item.js │ │ │ ├── test_observer_to_future.js │ │ │ ├── test_observable_future.js │ │ │ ├── test_consumer_registration.js │ │ │ ├── test_subscribe_twice.js │ │ │ ├── test_consume_body_stream.js │ │ │ ├── test_http_client.js │ │ │ ├── test_websocket_client.js │ │ │ ├── test_time_map.js │ │ │ ├── test_websocket_client_flatmap.js │ │ │ └── test_http_client_flatmap.js │ │ └── java │ │ │ └── io │ │ │ └── vertx │ │ │ └── rx │ │ │ └── js │ │ │ └── test │ │ │ ├── VertxAssert.java │ │ │ └── JsIntegrationTest.java │ └── main │ │ ├── asciidoc │ │ └── js │ │ │ ├── timer.js │ │ │ ├── periodic.js │ │ │ ├── handler.js │ │ │ ├── websocket_server.js │ │ │ ├── http_server_request.js │ │ │ ├── observer_to_future.js │ │ │ ├── event_bus_bodies.js │ │ │ ├── websocket_server_buffer.js │ │ │ ├── read_stream.js │ │ │ ├── websocket_client_buffer.js │ │ │ ├── observer_to_handler.js │ │ │ ├── http_client_request.js │ │ │ ├── http_server_request_buffer.js │ │ │ ├── http_client_response.js │ │ │ ├── websocket_client.js │ │ │ ├── event_bus_map_reduce.js │ │ │ ├── future.js │ │ │ ├── event_bus_messages.js │ │ │ └── index.adoc │ │ ├── assembly │ │ └── docs.xml │ │ └── resources │ │ └── rx.vertx.js └── pom.xml ├── .editorconfig ├── .gitignore ├── .travis.maven.settings.xml ├── README.adoc └── pom.xml /vertx-lang-js/src/main/docoverride/vertx-core/js/override/dns.adoc: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/json.adoc: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/buffer_from_bytes.adoc: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/npm/testmod1/testmod1_main.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = "hello from testmod1"; -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_no_vertxstop.js: -------------------------------------------------------------------------------- 1 | console.log("in verticle"); 2 | 3 | 4 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/resources/META-INF/services/io.vertx.docgen.DocGenerator: -------------------------------------------------------------------------------- 1 | io.vertx.lang.js.JSDocGenerator -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/somedir/test_mod2.js: -------------------------------------------------------------------------------- 1 | // CommonJS module for testing 2 | 3 | module.exports = "socks"; -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test.js: -------------------------------------------------------------------------------- 1 | module.exports = Java.type("io.vertx.rx.js.test.JsIntegrationTest").current; -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/resources/META-INF/services/io.vertx.core.spi.VerticleFactory: -------------------------------------------------------------------------------- 1 | io.vertx.lang.js.JSVerticleFactory -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_error.js: -------------------------------------------------------------------------------- 1 | 2 | exports.vertxStop = function() { 3 | throw "oops!" 4 | } 5 | 6 | 7 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_fail.js: -------------------------------------------------------------------------------- 1 | 2 | exports.vertxStop = function() { 3 | throw "oops!" 4 | } 5 | 6 | 7 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/resources/META-INF/services/io.vertx.codegen.GeneratorLoader: -------------------------------------------------------------------------------- 1 | io.vertx.lang.js.generator.JSGeneratorLoader 2 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_mod.js: -------------------------------------------------------------------------------- 1 | // CommonJS module for testing 2 | 3 | var someGlobal = "foo"; 4 | 5 | module.exports = "hello" -------------------------------------------------------------------------------- /vertx-lang-js/src/test/npm/zip/my_npm_module.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vert-x3/vertx-lang-js/HEAD/vertx-lang-js/src/test/npm/zip/my_npm_module.zip -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_set_timeout.js: -------------------------------------------------------------------------------- 1 | var eb = vertx.eventBus(); 2 | setTimeout(function() { 3 | eb.send("done", true); 4 | }, 2000); -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/brokenmodule_typeerror.js: -------------------------------------------------------------------------------- 1 | // A broken module 2 | 3 | // Deliberate type error: 4 | 5 | var num = 234; 6 | num.substr(1, 1); -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/eventbus.adoc: -------------------------------------------------------------------------------- 1 | ==== Message Codecs 2 | 3 | Message codecs are available exclusively with the Java api. 4 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/somedir/test_mod3.js: -------------------------------------------------------------------------------- 1 | // CommonJS module for testing 2 | 3 | var mod2 = require("./test_mod2"); 4 | 5 | module.exports = mod2; 6 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/brokenmodule_syntaxerror.js: -------------------------------------------------------------------------------- 1 | // A broken module 2 | 3 | // Deliberate syntax error: 4 | 5 | v ar x = "oops"; 6 | 7 | module.exports = x; -------------------------------------------------------------------------------- /vertx-lang-js/src/test/npm/testmod1/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "testmod1", 3 | "version": "1.0", 4 | "description": "My test mod 1", 5 | "main": "testmod1_main.js" 6 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | trim_trailing_whitespace = true 8 | end_of_line = lf 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/brokenmodule_typeerror2.js: -------------------------------------------------------------------------------- 1 | // A broken module 2 | 3 | // Deliberate type error: 4 | 5 | 6 | 7 | module.exports = function() { 8 | var num = 234; 9 | num.substr(1, 1); 10 | } -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_global.js: -------------------------------------------------------------------------------- 1 | console.log("in test verticle global"); 2 | 3 | // try and access a global variable - this should fail as we run verticles in use_strict mode which 4 | // prohibits this 5 | 6 | x = 1; -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_multiple.js: -------------------------------------------------------------------------------- 1 | //We want to make sure the body is executed every time the verticle is deployed 2 | 3 | vertx.eventBus().send("fooaddress", "blah"); 4 | 5 | exports.__vertxRunModule = null; 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_clear_interval.js: -------------------------------------------------------------------------------- 1 | var eb = vertx.eventBus(); 2 | var id = setInterval(function() { 3 | eb.send("done", "foo"); 4 | }, 100); 5 | clearInterval(id); 6 | setInterval(function() { 7 | eb.send("done", "bar"); 8 | }, 2000); -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_clear_timeout.js: -------------------------------------------------------------------------------- 1 | var eb = vertx.eventBus(); 2 | var id = setTimeout(function() { 3 | eb.send("done", "foo"); 4 | }, 100); 5 | clearTimeout(id); 6 | setTimeout(function() { 7 | eb.send("done", "bar"); 8 | }, 2000); -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/examples/echo_server.js: -------------------------------------------------------------------------------- 1 | var options = { 2 | host: "localhost", 3 | port: 1234 4 | }; 5 | 6 | vertx.createNetServer(options).connectHandler(function(conn) { 7 | conn.dataHandler(function(buff) { 8 | conn.writeBuffer(buff); 9 | }) 10 | }).listen(); -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Julien Viet 3 | */ 4 | @ModuleGen(name = "extra", groupPackage = "io.vertx") 5 | package io.vertx.test.codegen; 6 | 7 | import io.vertx.codegen.annotations.ModuleGen; 8 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_set_interval.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | var eb = vertx.eventBus(); 3 | var count = 0; 4 | var id = setInterval(function() { 5 | if (count++ == 2) { 6 | clearInterval(id); 7 | eb.send("done", true); 8 | } 9 | }, 2000); 10 | Assert.assertNotNull(id); 11 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_multiple_concurrent_requires_required.js: -------------------------------------------------------------------------------- 1 | function ConcurrencyTest() {} 2 | 3 | // Just a test property, this will sometimes be undefined if the require failed 4 | ConcurrencyTest.testProperty = function() { 5 | return true; 6 | }; 7 | 8 | module.exports = ConcurrencyTest; 9 | 10 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/asciidoc/enums.adoc: -------------------------------------------------------------------------------- 1 | = Enums 2 | 3 | [[TestGenEnum]] 4 | == TestGenEnum 5 | 6 | ++++ 7 | ++++ 8 | ''' 9 | 10 | [cols=">25%,75%"] 11 | [frame="topbot"] 12 | |=== 13 | ^|Name | Description 14 | |[[LAURA]]`LAURA`|- 15 | |[[BOB]]`BOB`|- 16 | |[[MIKE]]`MIKE`|- 17 | |[[LELAND]]`LELAND`|- 18 | |=== 19 | 20 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/GenericHolder.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.codegen; 2 | 3 | import io.vertx.codegen.annotations.VertxGen; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | @VertxGen 9 | public interface GenericHolder { 10 | 11 | T get(); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/web/altlang.ftl: -------------------------------------------------------------------------------- 1 | Hello ${context.foo} 2 | <#list context.bar as thing> 3 | There is a ${thing} 4 | 5 | <#list context.baz?keys as k> 6 | ${k} 7 | 8 | <#list context.baz?values as v> 9 | ${v} 10 | 11 | <#list context.team.marseille as peep> 12 | ${peep} loves Olympique de Marseille 13 | 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/timer.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var timer = Rx.Observable.fromReadStream(vertx.timerStream(1000)); 7 | timer.subscribe(function(id) { 8 | console.log("Callback after 1 second"); 9 | }); 10 | // end::example[] 11 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/periodic.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var timer = Rx.Observable.fromReadStream(vertx.periodicStream(1000)); 7 | timer.subscribe(function(id) { 8 | console.log("Callback every second"); 9 | }); 10 | // end::example[] 11 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/unit/coordinated/server.js: -------------------------------------------------------------------------------- 1 | exports.vertxStartAsync = function(startFuture) { 2 | var server = vertx.createHttpServer({"port":8080,"host":"localhost"}); 3 | server.requestStream().handler(function(req) { 4 | req.response().setChunked(true).write("Hello World").end(); 5 | }); 6 | server.listen(function(ar) { 7 | startFuture.complete(); 8 | }); 9 | }; -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/handler.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var observable = Rx.observableHandler(); 7 | observable.subscribe( 8 | function(evt) { 9 | // Got event 10 | } 11 | ); 12 | vertx.setTimer(1000, observable.toHandler()); 13 | // end::example[] 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_observer_to_handler.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var observer = Rx.Observer.create( 4 | function(evt) { 5 | test.testComplete(); 6 | }, function(err) { 7 | test.fail(); 8 | }, function() { 9 | test.fail(); 10 | } 11 | ); 12 | var handler = observer.toHandler(); 13 | vertx.setTimer(1, handler); 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_observable_handler.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var observable = Rx.observableHandler(); 4 | observable.subscribe( 5 | function(evt) { 6 | test.testComplete(); 7 | }, function(err) { 8 | test.fail(); 9 | }, function() { 10 | test.fail(); 11 | } 12 | ); 13 | vertx.setTimer(1, observable.toHandler()); 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/websocket_server.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var server = vertx.createHttpServer(); 7 | var sockets = Rx.Observable.fromReadStream(server.websocketStream()); 8 | sockets.subscribe(function(ws) { 9 | // Process the web socket 10 | }); 11 | // end::example[] 12 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/configuring-native.adoc: -------------------------------------------------------------------------------- 1 | [source,json] 2 | ---- 3 | { 4 | "preferNativeTransport": true 5 | } 6 | ---- 7 | 8 | NOTE: preferring native transport will not prevent the application to execute (for example if a JAR is missing). 9 | If your application requires native transport, you need to check {@link io.vertx.core.Vertx#isNativeTransportEnabled()}. 10 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/http_server_request.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var server = vertx.createHttpServer(); 7 | var requests = Rx.Observable.fromReadStream(server.requestStream()); 8 | requests.subscribe(function(request) { 9 | // Process the request 10 | }); 11 | // end::example[] 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .gradle 3 | .idea 4 | .classpath 5 | .project 6 | .settings 7 | .yardoc 8 | .yardopts 9 | bin 10 | build 11 | target 12 | out 13 | *.iml 14 | *.ipr 15 | *.iws 16 | test-output 17 | Scratch.java 18 | ScratchTest.java 19 | test-results 20 | test-tmp 21 | *.class 22 | src/gen 23 | src/main/resources/vertx-js/*.js 24 | src/test/resources/testmodel-js/*.js 25 | src/scratchpad 26 | .vertx/ 27 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/unit/timer.js: -------------------------------------------------------------------------------- 1 | exports.vertxStartAsync = function(future) { 2 | var TestSuite = require('vertx-unit-js/test_suite'); 3 | var suite = TestSuite.create("time_suite").test("timer_test", function(context) { 4 | var async = context.async(); 5 | vertx.setTimer(50, function() { 6 | async.complete(); 7 | }); 8 | }); 9 | suite.run().resolve(future); 10 | }; -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_completed.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var consumer = vertx.timerStream(100); 4 | var observer = Rx.Observer.create( 5 | function (evt) { 6 | }, 7 | function (err) { 8 | test.fail(err); 9 | }, 10 | function () { 11 | test.testComplete(); 12 | } 13 | ); 14 | var observable = Rx.Observable.fromReadStream(consumer); 15 | observable.subscribe(observer); 16 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/WebTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class WebTest extends JSTestBase { 9 | @Override 10 | protected String getTestFile() { 11 | return "js_web_test.js"; 12 | } 13 | 14 | @Test 15 | public void testCookies() throws Exception { 16 | runTest(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/unit/failing.js: -------------------------------------------------------------------------------- 1 | exports.vertxStartAsync = function(future) { 2 | var TestSuite = require('vertx-unit-js/test_suite'); 3 | var suite = TestSuite.create("time_suite").test("timer_test", function(context) { 4 | var async = context.async(); 5 | vertx.setTimer(50, function() { 6 | context.fail(new Error("the_failure")); 7 | }); 8 | }); 9 | suite.run().resolve(future); 10 | }; -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/observer_to_future.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | 3 | // tag::example[] 4 | var Rx = require("rx.vertx"); 5 | 6 | // Create an observer via the Rx api 7 | var observer = Rx.Observer.create( 8 | function(evt) { 9 | // Got event 10 | } 11 | ); 12 | 13 | // The rx.vertx extension augmented the observer with the toHandler method 14 | var future = observer.toFuture(); 15 | // end::example[] 16 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/examples/http_server.js: -------------------------------------------------------------------------------- 1 | console.log("in example server, vertx is " + vertx); 2 | 3 | var options = { 4 | host: "localhost", 5 | port: 8080 6 | }; 7 | 8 | vertx.createHttpServer(options).requestHandler(function(req) { 9 | req.response().writeStringAndEnd("hello world"); 10 | }).listen(); 11 | 12 | 13 | module.exports = {}; 14 | 15 | module.exports.vertxStop = function() { 16 | console.log("in vertxStop!"); 17 | } -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/event_bus_bodies.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | 7 | var eb = vertx.eventBus(); 8 | var messageConsumer = eb.consumer("the-address"); 9 | var bodyConsumer = messageConsumer.bodyStream(); 10 | 11 | // Create an observable from the body consumer 12 | var observable = Rx.Observable.fromReadStream(bodyConsumer); 13 | // end::example[] 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/java/io/vertx/rx/js/test/VertxAssert.java: -------------------------------------------------------------------------------- 1 | package io.vertx.rx.js.test; 2 | 3 | /** 4 | * @author Julien Viet 5 | */ 6 | public interface VertxAssert { 7 | 8 | void testComplete(); 9 | void assertEquals(Object expected, Object actual); 10 | void assertEquals(long expected, long actual); 11 | void assertTrue(boolean b); 12 | void assertFalse(boolean b); 13 | void fail(String msg); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/AsyncStartTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class AsyncStartTest extends JSTestBase { 9 | @Override 10 | protected String getTestFile() { 11 | return "async_start_test.js"; 12 | } 13 | 14 | @Test 15 | public void testAsyncStartStop() throws Exception { 16 | runTest(); 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/websocket_server_buffer.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var server = vertx.createHttpServer(); 7 | Rx.Observable.fromReadStream(server.websocketStream()).subscribe(function(ws) { 8 | var observable = Rx.Observable.fromReadStream(ws); 9 | observable.forEach(function(buffer) { 10 | // Process message 11 | }); 12 | }); 13 | // end::example[] 14 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_concat.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var o1 = Rx.Observable.fromReadStream(vertx.timerStream(100)); 4 | var o2 = Rx.Observable.fromReadStream(vertx.timerStream(100)); 5 | var obs = Rx.Observable.concat(o1, o2); 6 | var count = 0; 7 | obs.subscribe( 8 | function(evt) { count++; }, 9 | function(err) { test.fail(err); }, 10 | function() { 11 | test.assertEquals(2, count); 12 | test.testComplete(); 13 | } 14 | ); 15 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/read_stream.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var fs = vertx.fileSystem(); 7 | fs.open("/data.txt", {}, function(result, err) { 8 | var file = result.result(); 9 | var observable = Rx.Observable.fromReadStream(file); 10 | observable.forEach(function(data) { 11 | console.log("Read data: " + data.toString("UTF-8")); 12 | }); 13 | }); 14 | // end::example[] 15 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/websocket_client_buffer.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var client = vertx.createHttpClient(); 7 | var stream = client.websocketStream(8080, "localhost", "/the_uri"); 8 | var observable = Rx.Observable.fromReadStream(stream); 9 | observable.subscribe(function(ws) { 10 | // Use the websocket 11 | }, function(err) { 12 | // Could not connect 13 | }); 14 | // end::example[] 15 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/MethodDispatchTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class MethodDispatchTest extends JSTestBase { 9 | @Override 10 | protected String getTestFile() { 11 | return "test_method_dispatch.js"; 12 | } 13 | 14 | @Test 15 | public void testObjectArgumentShouldIncreaseTheArgumentCount() throws Exception { 16 | runTest(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/observer_to_handler.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | 7 | // Create an observer via the Rx api 8 | var observer = Rx.Observer.create( 9 | function(evt) { 10 | // Got event 11 | } 12 | ); 13 | 14 | // The rx.vertx extension augmented the observer with the toHandler method 15 | var handler = observer.toHandler(); 16 | vertx.setTimer(1000, handler); 17 | // end::example[] 18 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_scheduled_timer.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var Rx = require("rx.time"); 4 | var Vertx = require("vertx-js/vertx"); 5 | var initContext = Vertx.currentContext(); 6 | Rx.Observable.timer(100, 100).take(10).subscribe( 7 | function(event) { 8 | test.assertEquals(initContext._jdel, Vertx.currentContext()._jdel); 9 | }, 10 | function(err) { 11 | test.fail(err.message); 12 | }, function() { 13 | test.testComplete(); 14 | } 15 | ); 16 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/ThrowableConverter.java: -------------------------------------------------------------------------------- 1 | package io.vertx.lang.js; 2 | 3 | import java.util.concurrent.Callable; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | public class ThrowableConverter { 9 | 10 | public static Throwable catchAndReturnThrowable(Callable c) { 11 | try { 12 | c.call(); 13 | } catch (Throwable t) { 14 | return t; 15 | } 16 | throw new AssertionError("Should not happen"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/http_client_request.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var client = vertx.createHttpClient(); 7 | var req = client.request("GET", 8080, "localhost", "/the_uri"); 8 | var observable = Rx.Observable.fromReadStream(req); 9 | observable.subscribe(function(resp) { 10 | // Process the response 11 | }, function(err) { 12 | // Could not connect 13 | }); 14 | req.end(); 15 | // end::example[] 16 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/http_server_request_buffer.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var server = vertx.createHttpServer(); 7 | var requests = Rx.Observable.fromReadStream(server.requestStream()); 8 | requests.subscribe(function(request) { 9 | var buffers = Rx.Observable.fromReadStream(request); 10 | buffers.forEach(function(buffer) { 11 | // Handle buffer 12 | }); 13 | }); 14 | // end::example[] 15 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_multiple_concurrent_requires_verticle.js: -------------------------------------------------------------------------------- 1 | var RequiredResource = require("test_multiple_concurrent_requires_required.js"); 2 | 3 | if (RequiredResource == null) { 4 | vertx.eventBus().send("test_multiple_concurrent_requires", "failed: Resource is null"); 5 | } else if (RequiredResource.testProperty == null) { 6 | vertx.eventBus().send("test_multiple_concurrent_requires", "failed: Property is null"); 7 | } else { 8 | vertx.eventBus().send("test_multiple_concurrent_requires", "ok"); 9 | } 10 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/generator/JSGeneratorLoader.java: -------------------------------------------------------------------------------- 1 | package io.vertx.lang.js.generator; 2 | 3 | import io.vertx.codegen.Generator; 4 | import io.vertx.codegen.GeneratorLoader; 5 | 6 | import javax.annotation.processing.ProcessingEnvironment; 7 | import java.util.stream.Stream; 8 | 9 | public class JSGeneratorLoader implements GeneratorLoader { 10 | @Override 11 | public Stream> loadGenerators(ProcessingEnvironment processingEnv) { 12 | return Stream.of(new JSClassGenerator()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/http_client_response.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var client = vertx.createHttpClient(); 7 | var req = client.request("GET", 8080, "localhost", "/the_uri"); 8 | Rx.Observable.fromReadStream(req).subscribe(function(resp) { 9 | var observable = Rx.Observable.fromReadStream(resp); 10 | observable.forEach(function(buffer) { 11 | // Process buffer 12 | }); 13 | }); 14 | req.end(); 15 | // end::example[] 16 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/websocket_client.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | var client = vertx.createHttpClient(); 7 | var stream = client.websocketStream(8080, "localhost", "/the_uri"); 8 | Rx.Observable.fromReadStream(stream). 9 | subscribe(function (ws) { 10 | var observable = Rx.Observable.fromReadStream(ws); 11 | observable.forEach(function(buffer) { 12 | // Process message 13 | }); 14 | 15 | }); 16 | // end::example[] 17 | -------------------------------------------------------------------------------- /.travis.maven.settings.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | false 7 | 8 | 9 | 10 | vertx-snapshots-repository 11 | ${env.VERTX_NEXUS_USERNAME} 12 | ${env.VERTX_NEXUS_PASSWORD} 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/event_bus_map_reduce.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | 7 | var eb = vertx.eventBus(); 8 | var consumer = eb.consumer("heat-sensor").bodyStream(); 9 | var observable = Rx.Observable.fromReadStream(consumer); 10 | 11 | observable. 12 | bufferWithTime(500). 13 | map(function (arr) { return arr.reduce(function (acc, x) { return acc + x; }, "") }). 14 | subscribe( 15 | function(heat) { 16 | console.log("Current heat is " + heat); 17 | }); 18 | // end::example[] 19 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/future.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | 7 | // Create an observable that is also an handler of async result 8 | var observable = Rx.observableFuture(); 9 | observable.subscribe( 10 | function(server) { 11 | // Server is listening 12 | }, 13 | function(err) { 14 | // Server could not start 15 | } 16 | ); 17 | 18 | var server = vertx.createHttpServer({ "port":1234, "host":"localhost" }); 19 | server.listen(observable.toHandler()); 20 | // end::example[] 21 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_scheduled_buffer.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var Rx = require("rx.time"); 4 | var Vertx = require("vertx-js/vertx"); 5 | var initContext = Vertx.currentContext(); 6 | var eventCount = 0; 7 | Rx.Observable.timer(10, 10).bufferWithTime(100).take(10).subscribe( 8 | function(event) { 9 | eventCount++; 10 | test.assertEquals(initContext._jdel, Vertx.currentContext()._jdel); 11 | }, 12 | function(err) { 13 | test.fail(err.message); 14 | }, function() { 15 | test.assertEquals(10, eventCount); 16 | test.testComplete(); 17 | } 18 | ); 19 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_adapt_item.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | var consumer = eb.localConsumer("the-address"); 5 | var observer = Rx.Observer.create( 6 | function (evt) { 7 | test.assertEquals("object", typeof evt._jdel); 8 | this.dispose(); 9 | test.testComplete(); 10 | }, 11 | function (err) { 12 | test.fail(err); 13 | }, 14 | function () { 15 | test.fail("unexpected"); 16 | } 17 | ); 18 | var observable = Rx.Observable.fromReadStream(consumer); 19 | observable.subscribe(observer); 20 | eb.send("the-address", "msg1"); 21 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_observer_to_future.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | eb.consumer("the_address").handler(function(msg) { 5 | msg.reply("pong"); 6 | }); 7 | var events = []; 8 | var observer = Rx.Observer.create( 9 | function(evt) { 10 | events.push(evt.body()); 11 | }, function(err) { 12 | test.fail(); 13 | }, function() { 14 | test.assertEquals(1, events.length); 15 | test.assertEquals("pong", events[0]); 16 | test.testComplete(); 17 | } 18 | ); 19 | var future = observer.toFuture(); 20 | eb.send("the_address", {}, {}, future); 21 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/test_utils.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | assertEquals: function(arg0, arg1, arg2) { 3 | if (typeof arg2 !== 'undefined') { 4 | arg0 = arg1; 5 | arg1 = arg2; 6 | } 7 | if (!isNaN(arg0) && !isNaN(arg1)) { 8 | if (arg0 % 1 === 0 && arg1 % 1 === 0) { 9 | // (integer, integer) 10 | Assert["assertEquals(double, double, double)"](arg0, arg1, 0); 11 | } else { 12 | // (double, double) 13 | Assert["assertEquals(double, double, double)"](arg0, arg1, 0.0001); 14 | } 15 | } else { 16 | Assert.assertEquals(arg0, arg1); 17 | } 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_observable_future.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | eb.consumer("the_address").handler(function(msg) { 5 | msg.reply("pong"); 6 | }); 7 | var observable = Rx.observableFuture(); 8 | var events = []; 9 | observable.subscribe( 10 | function(evt) { 11 | events.push(evt.body()); 12 | }, function(err) { 13 | test.fail(); 14 | }, function() { 15 | test.assertEquals(1, events.length); 16 | test.assertEquals("pong", events[0]); 17 | test.testComplete(); 18 | } 19 | ); 20 | eb.send("the_address", {}, {}, observable.toHandler()); 21 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/DataObjectTCKTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * 7 | * This test tests all the different types of methods, return values and parameters that can be used in generated 8 | * APIs. 9 | * 10 | * @author Tim Fox 11 | */ 12 | public class DataObjectTCKTest extends JSTestBase { 13 | 14 | @Override 15 | protected String getTestFile() { 16 | return "data_object_tck_test.js"; 17 | } 18 | 19 | @Test 20 | public void testJsonOnlyConstructorDataObject() throws Exception { 21 | runTest(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/async_test_verticle.js: -------------------------------------------------------------------------------- 1 | 2 | exports.vertxStartAsync = function(startFuture) { 3 | if (startFuture._jdel === undefined) { 4 | startFuture.fail("Was expecting a proxy and not a native object"); 5 | } else { 6 | vertx.setTimer(1100, function() { 7 | startFuture.complete(); 8 | }); 9 | } 10 | }; 11 | 12 | exports.vertxStopAsync = function(stopFuture) { 13 | if (stopFuture._jdel === undefined) { 14 | stopFuture.fail("Was expecting a proxy and not a native object"); 15 | } else { 16 | vertx.setTimer(1100, function() { 17 | stopFuture.complete(); 18 | }); 19 | } 20 | }; 21 | 22 | 23 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/JSTestBase.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | /** 4 | * @author Tim Fox 5 | */ 6 | public abstract class JSTestBase { 7 | 8 | protected String getMethodName() { 9 | return Thread.currentThread().getStackTrace()[3].getMethodName(); 10 | } 11 | 12 | protected abstract String getTestFile(); 13 | 14 | protected void runTest() throws Exception { 15 | new JSRunner().run(getTestFile(), getMethodName()); 16 | } 17 | 18 | protected void runTest(String testName) throws Exception { 19 | new JSRunner().run(getTestFile(), testName); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/InheritedMethodsTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | public class InheritedMethodsTest extends JSTestBase { 6 | 7 | @Override 8 | protected String getTestFile() { 9 | return "inherited_methods_test.js"; 10 | } 11 | 12 | @Test 13 | public void testCallInheritedMethods() throws Exception { 14 | runTest(); 15 | } 16 | 17 | @Test 18 | public void testCallMethodOverloadingInheritedMethods() throws Exception { 19 | runTest(); 20 | } 21 | 22 | @Test 23 | public void testCallStaticMethods() throws Exception { 24 | runTest(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_consumer_registration.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | var consumer = eb.localConsumer("the-address"); 5 | var observer = Rx.Observer.create( 6 | function (evt) { 7 | test.fail(err); 8 | }, 9 | function (err) { 10 | test.fail(err); 11 | }, 12 | function () { 13 | test.fail(err); 14 | } 15 | ); 16 | 17 | var observable = Rx.Observable.fromReadStream(consumer); 18 | var subscription = observable.subscribe(observer); 19 | test.assertTrue(consumer.isRegistered()); 20 | subscription.dispose(); 21 | test.assertFalse(consumer.isRegistered()); 22 | test.testComplete(); -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | # Nashorn JavaScript implementation for Vert.x 2 | 3 | image:https://travis-ci.org/vert-x3/vertx-lang-js.svg?branch=master["Build Status",link="https://travis-ci.org/vert-x3/vertx-lang-js"] 4 | 5 | This project provides the JavaScript API implementation for Vert.x using the Nashorn JavaScript engine built into Java 8. 6 | 7 | As with all Vert.x 3 language implementations they are generated from a Java API using templates - this allows us to 8 | maintain just the canonical Java APIs which is a lot less work than maintaining them manually. 9 | 10 | This project provides a verticle factory implementation which knows how to deploy verticles with the prefix, or file 11 | extension `js`. 12 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_method_dispatch.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var Assert = org.junit.Assert; 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var TimeUnit = java.util.concurrent.TimeUnit; 5 | 6 | function testObjectArgumentShouldIncreaseTheArgumentCount() { 7 | var vertx = Vertx.vertx(); 8 | var latch = new CountDownLatch(1); 9 | var eb = vertx.eventBus(); 10 | eb.consumer("the-address").handler(function (msg) { 11 | msg.reply(null); 12 | }); 13 | eb.send("the-address", "foo", function(msg, failure) { 14 | latch.countDown(); 15 | }); 16 | Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); 17 | } 18 | 19 | this[testName](); -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/event_bus_messages.js: -------------------------------------------------------------------------------- 1 | var Vertx = require("vertx-js/vertx"); 2 | var vertx = Vertx.vertx(); 3 | 4 | // tag::example[] 5 | var Rx = require("rx.vertx"); 6 | 7 | var eb = vertx.eventBus(); 8 | var messageConsumer = eb.consumer("the-address"); 9 | 10 | // Create an observable from the message consumer 11 | var observable = Rx.Observable.fromReadStream(messageConsumer); 12 | 13 | // Subscribe to the observable 14 | var subscription = observable.subscribe( 15 | function(msg) { 16 | // Got message 17 | }); 18 | 19 | // Unregisters the stream after 10 seconds 20 | vertx.setTimer(10000, function() { 21 | subscription.dispose(); 22 | }); 23 | // end::example[] 24 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/InterfaceWithMethod.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.codegen; 2 | 3 | import io.vertx.codegen.annotations.VertxGen; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | @VertxGen 9 | public interface InterfaceWithMethod { 10 | 11 | String meth1(); 12 | String meth1(String arg); 13 | 14 | String meth2(); 15 | String meth2(String arg); 16 | 17 | static String static_meth1() { return "static_meth1()"; } 18 | static String static_meth1(String arg) { return "static_meth1(" + arg + ")"; } 19 | static String static_meth2() { return "static_meth2()"; } 20 | static String static_meth2(String arg) { return "static_meth2(" + arg + ")"; } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_mod_cached_require.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | // CommonJS module for testing 18 | 19 | var someGlobal = "foo"; 20 | 21 | module.exports = {foo: "bar"} -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/SucceededResult.java: -------------------------------------------------------------------------------- 1 | package io.vertx.lang.js; 2 | 3 | import io.vertx.core.AsyncResult; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | public class SucceededResult implements AsyncResult { 9 | 10 | final T result; 11 | 12 | public SucceededResult(T result) { 13 | this.result = result; 14 | } 15 | 16 | @Override 17 | public T result() { 18 | return result; 19 | } 20 | 21 | @Override 22 | public Throwable cause() { 23 | return null; 24 | } 25 | 26 | @Override 27 | public boolean succeeded() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public boolean failed() { 33 | return false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/ExampleRunner.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test; 2 | 3 | import io.vertx.core.Vertx; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class ExampleRunner { 9 | 10 | public static void main(String[] args) { 11 | Vertx vertx = Vertx.vertx(); 12 | vertx.deployVerticle("js:examples/http_server", ar -> { 13 | if (ar.succeeded()) { 14 | System.out.println("Succeeded in deploying"); 15 | } else { 16 | System.out.println("Failed: " + ar.cause()); 17 | ar.cause().printStackTrace(); 18 | } 19 | }); 20 | try { 21 | Thread.sleep(100000); 22 | } catch (Exception e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_subscribe_twice.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | var consumer = eb.localConsumer("the-address"); 5 | var observer1 = Rx.Observer.create( 6 | function (evt) { 7 | test.fail("onNext called"); 8 | }, 9 | function (err) { 10 | test.fail(err); 11 | }, 12 | function () { 13 | } 14 | ); 15 | var observer2 = Rx.Observer.create( 16 | function (evt) { 17 | test.fail(); 18 | }, 19 | function (err) { 20 | test.testComplete(); 21 | }, 22 | function () { 23 | test.testComplete(); 24 | } 25 | ); 26 | var observable = Rx.Observable.fromReadStream(consumer); 27 | observable.subscribe(observer1); 28 | observable.subscribe(observer2); 29 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/data_object_tck_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var TestInterface = require('testmodel-js/test_interface'); 4 | var RefedInterface1 = require('testmodel-js/refed_interface1'); 5 | 6 | var DataObjectTCK = require('testmodel-js/data_object_tck'); 7 | var dataObjectTCK = new DataObjectTCK(new Packages.io.vertx.codegen.testmodel.DataObjectTCKImpl()); 8 | 9 | var that = this; 10 | 11 | function testJsonOnlyConstructorDataObject() { 12 | var dataObject = { "foo" : "bar" }; 13 | dataObjectTCK.methodWithOnlyJsonObjectConstructorDataObject(dataObject); 14 | } 15 | 16 | if (typeof this[testName] === 'undefined') { 17 | throw "No such test: " + testName; 18 | } 19 | 20 | this[testName](); 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/TimeoutTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class TimeoutTest extends JSTestBase { 9 | @Override 10 | protected String getTestFile() { 11 | return "js_timeout_test.js"; 12 | } 13 | 14 | @Test 15 | public void testSetTimeout() throws Exception { 16 | runTest(); 17 | } 18 | 19 | @Test 20 | public void testClearTimeout() throws Exception { 21 | runTest(); 22 | } 23 | 24 | @Test 25 | public void testSetInterval() throws Exception { 26 | runTest(); 27 | } 28 | 29 | @Test 30 | public void testClearInterval() throws Exception { 31 | runTest(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/assembly/docs.xml: -------------------------------------------------------------------------------- 1 | 4 | docs 5 | false 6 | 7 | 8 | ${project.build.directory}/asciidoc 9 | ./ 10 | 11 | 12 | ${project.build.directory}/jsdoc 13 | ./jsdoc/ 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/ClassParamOverload.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.codegen; 2 | 3 | import io.vertx.codegen.annotations.VertxGen; 4 | import io.vertx.test.codegen.impl.ClassParamOverloadImpl; 5 | 6 | /** 7 | * @author Julien Viet 8 | */ 9 | @VertxGen 10 | public interface ClassParamOverload { 11 | 12 | static ClassParamOverload create() { 13 | return new ClassParamOverloadImpl(); 14 | } 15 | 16 | T typeVarReturn(); 17 | 18 | T typeVarReturn(Class type); 19 | 20 | GenericHolder parameterizedReturn(); 21 | 22 | GenericHolder parameterizedReturn(Class type); 23 | 24 | boolean typeVarParam(T t); 25 | 26 | boolean typeVarParam(Class type, T t); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/eventbus_headers.adoc: -------------------------------------------------------------------------------- 1 | ==== Setting headers on messages 2 | 3 | Messages sent over the event bus can also contain headers. This can be specified by providing a `headers` object 4 | inside the {@link io.vertx.core.eventbus.DeliveryOptions} object when sending or publishing: 5 | 6 | [source,javascript] 7 | ---- 8 | var options = { 9 | headers: { 10 | "some-header" : "some-value" 11 | } 12 | } 13 | vertx.eventBus().send("news.uk.sport", "Yay! Someone kicked a ball", options); 14 | ---- 15 | 16 | On the other side, the consumer can retrieve the message header as follows: 17 | 18 | [source, javascript] 19 | ---- 20 | vertx.eventBus().consumer("news.uk.sport", function(e) { 21 | console.log(e.headers().get("some-header")); 22 | }); 23 | ---- 24 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/FailedResult.java: -------------------------------------------------------------------------------- 1 | package io.vertx.lang.js; 2 | 3 | import io.vertx.core.AsyncResult; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | public class FailedResult implements AsyncResult { 9 | 10 | final Throwable cause; 11 | 12 | public FailedResult(Object cause) { 13 | this.cause = cause instanceof Throwable ? (Throwable) cause : new Exception(cause.toString()); 14 | } 15 | 16 | @Override 17 | public T result() { 18 | return null; 19 | } 20 | 21 | @Override 22 | public Throwable cause() { 23 | return cause; 24 | } 25 | 26 | @Override 27 | public boolean succeeded() { 28 | return false; 29 | } 30 | 31 | @Override 32 | public boolean failed() { 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/unit/coordinated/test.js: -------------------------------------------------------------------------------- 1 | var TestSuite = require('vertx-unit-js/test_suite'); 2 | 3 | var suite = TestSuite.create("my_suite"). 4 | before(function(context) { 5 | var async = context.async(); 6 | vertx.deployVerticle("js:it/unit/coordinated/server", function(id, err) { 7 | context.assertTrue(err === null); 8 | async.complete(); 9 | }); 10 | }).test("server_get", function(context) { 11 | var async = context.async(); 12 | var client = vertx.createHttpClient({}); 13 | client.request("GET", 8080, "localhost", "/path", function(resp) { 14 | context.assertTrue(resp.statusCode() == 200); 15 | async.complete(); 16 | }).end(); 17 | }); 18 | 19 | suite.run(vertx, { reporters : [{ to: "bus:test"}] }); 20 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle_vertxstart.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | // Verticle with an explicit vertxStart method 18 | 19 | vertx.eventBus().send("fooaddressinit", "blah"); 20 | 21 | function vertxStart() { 22 | vertx.eventBus().send("fooaddress", "blah") 23 | } 24 | 25 | exports.vertxStart = vertxStart; 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/assembly/docs.xml: -------------------------------------------------------------------------------- 1 | 4 | docs 5 | 6 | zip 7 | 8 | false 9 | 10 | 11 | ${asciidoc.dir} 12 | / 13 | 14 | 15 | ${project.build.directory}/docs/vertx-rx/ 16 | / 17 | 18 | js/jsdoc/** 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/discovery/service/package-info.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011-2016 The original author or authors 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | /** 18 | * @author Clement Escoffier 19 | */ 20 | @ModuleGen(name = "test-services", groupPackage = "io.vertx") 21 | package io.vertx.test.it.discovery.service; 22 | 23 | import io.vertx.codegen.annotations.ModuleGen; 24 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_consume_body_stream.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var eb = vertx.eventBus(); 4 | var consumer = eb.localConsumer("the-address"); 5 | var events = []; 6 | var observer = Rx.Observer.create( 7 | function (evt) { 8 | var body = evt.body(); 9 | events.push(body); 10 | if (body == "msg3") { 11 | test.assertEquals(3, events.length); 12 | test.assertEquals("msg1", events[0]); 13 | test.assertEquals("msg2", events[1]); 14 | test.assertEquals("msg3", events[2]); 15 | this.dispose(); 16 | test.testComplete(); 17 | } 18 | }, 19 | function (err) { 20 | test.fail(err); 21 | }, 22 | function () { 23 | test.fail("unexpected"); 24 | } 25 | ); 26 | 27 | var observable = Rx.Observable.fromReadStream(consumer); 28 | observable.subscribe(observer); 29 | eb.send("the-address", "msg1"); 30 | eb.send("the-address", "msg2"); 31 | eb.send("the-address", "msg3"); 32 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_http_client.js: -------------------------------------------------------------------------------- 1 | var Buffer = require('vertx-js/buffer'); 2 | var test = require("test"); 3 | var Rx = require("rx.vertx"); 4 | 5 | var server = vertx.createHttpServer({port: 8080}); 6 | server.requestStream().handler(function(req) { 7 | req.response().setChunked(true).end("some_content"); 8 | }); 9 | 10 | server.listen(function(server, cause) { 11 | var client = vertx.createHttpClient({}); 12 | client.request("GET", 8080, "localhost", "/the_uri", function(resp) { 13 | var content = Buffer.buffer(); 14 | var observable = Rx.Observable.fromReadStream(resp); 15 | observable.forEach( 16 | function(buffer) { 17 | content.appendBuffer(buffer); 18 | }, function(err) { 19 | test.fail(); 20 | } , function() { 21 | server.close(); 22 | test.assertEquals("some_content", content.toString("UTF-8")); 23 | test.testComplete(); 24 | }); 25 | }).end(); 26 | }); 27 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_websocket_client.js: -------------------------------------------------------------------------------- 1 | var Buffer = require('vertx-js/buffer'); 2 | var test = require("test"); 3 | var Rx = require("rx.vertx"); 4 | 5 | var server = vertx.createHttpServer({port: 8080}); 6 | server.websocketStream().handler(function(ws) { 7 | ws.write(Buffer.buffer("some_content")); 8 | ws.close(); 9 | }); 10 | 11 | server.listen(function(server, cause) { 12 | var client = vertx.createHttpClient({}); 13 | client.websocket(8080, "localhost", "/the_uri", function(ws) { 14 | var content = Buffer.buffer(); 15 | var observable = Rx.Observable.fromReadStream(ws); 16 | observable.forEach( 17 | function(buffer) { 18 | content.appendBuffer(buffer); 19 | }, function(err) { 20 | test.fail(); 21 | } , function() { 22 | server.close(); 23 | test.assertEquals("some_content", content.toString("UTF-8")); 24 | test.testComplete(); 25 | }); 26 | }); 27 | }); 28 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/event_bus_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var TimeUnit = java.util.concurrent.TimeUnit; 5 | 6 | var Vertx = require("vertx-js/vertx"); 7 | var Buffer = require('vertx-js/buffer'); 8 | 9 | function testSendBuffer() { 10 | var vertx = Vertx.vertx(); 11 | var latch = new CountDownLatch(1); 12 | 13 | var eventBus = vertx.eventBus(); 14 | eventBus.consumer("foo", function (msg) { 15 | Assert.assertEquals("The quick brown fox jumps over the lazy dog", msg.body().toString()); 16 | latch.countDown(); 17 | }).completionHandler(function (v, err) { 18 | Assert.assertNull(err); 19 | eventBus.send("foo", Buffer.buffer("The quick brown fox jumps over the lazy dog")); 20 | }); 21 | 22 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 23 | } 24 | 25 | if (typeof this[testName] === 'undefined') { 26 | throw "No such test: " + testName; 27 | } 28 | 29 | this[testName](); 30 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/JavaArraySetWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import java.util.HashSet; 20 | 21 | /** 22 | * @author Tim Fox 23 | */ 24 | public class JavaArraySetWrapper extends HashSet { 25 | 26 | public JavaArraySetWrapper(Object[] array) { 27 | for (Object obj: array) { 28 | add(obj); 29 | } 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/extra_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var ClassParamOverload = require('extra-js/class_param_overload'); 4 | var overload = ClassParamOverload.create(); 5 | 6 | var that = this; 7 | 8 | var testUtils = require("test_utils"); 9 | var assertEquals = testUtils.assertEquals; 10 | 11 | function testTypeVarReturn() { 12 | Assert.assertEquals("wibble", overload.typeVarReturn()); 13 | assertEquals(5, overload.typeVarReturn(Number)); 14 | } 15 | 16 | function testParameterizedReturn() { 17 | assertEquals("cheese", overload.parameterizedReturn().get()); 18 | assertEquals(10, overload.parameterizedReturn(Number).get()); 19 | } 20 | 21 | function testTypeVarParam() { 22 | assertEquals(true, overload.typeVarParam("wibble")); 23 | assertEquals(true, overload.typeVarParam(Number, 20)); 24 | } 25 | 26 | if (typeof this[testName] === 'undefined') { 27 | throw "No such test: " + testName; 28 | } 29 | 30 | this[testName](); 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/ListConverterSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import java.util.HashSet; 20 | import java.util.List; 21 | 22 | /** 23 | * @author Tim Fox 24 | */ 25 | public class ListConverterSet extends HashSet { 26 | 27 | public ListConverterSet(List list) { 28 | for (Object obj: list) { 29 | add(obj); 30 | } 31 | } 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_time_map.js: -------------------------------------------------------------------------------- 1 | var test = require("test"); 2 | var Rx = require("rx.vertx"); 3 | var Rx = require("rx.time"); 4 | var Vertx = require("vertx-js/vertx"); 5 | var initContext = Vertx.currentContext(); 6 | var eb = vertx.eventBus(); 7 | var consumer = eb.localConsumer("the-address").bodyStream(); 8 | var observer = Rx.Observer.create( 9 | function (evt) { 10 | test.assertEquals(initContext._jdel, Vertx.currentContext()._jdel); 11 | test.assertEquals("msg1msg2msg3", evt); 12 | this.dispose(); 13 | test.testComplete(); 14 | }, 15 | function (err) { 16 | test.fail(err); 17 | }, 18 | function () { 19 | test.fail(err); 20 | } 21 | ); 22 | var observable = Rx.Observable.fromReadStream(consumer); 23 | observable. 24 | bufferWithTime(500). 25 | map(function (arr) { return arr.reduce(function (acc, x) { return acc + x; }, "") }). 26 | subscribe(observer); 27 | eb.send("the-address", "msg1"); 28 | eb.send("the-address", "msg2"); 29 | eb.send("the-address", "msg3"); 30 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_websocket_client_flatmap.js: -------------------------------------------------------------------------------- 1 | var Buffer = require('vertx-js/buffer'); 2 | var test = require("test"); 3 | var Rx = require("rx.vertx"); 4 | 5 | var server = vertx.createHttpServer({port: 8080}); 6 | server.websocketStream().handler(function(ws) { 7 | ws.write(Buffer.buffer("some_content")); 8 | ws.close(); 9 | }); 10 | 11 | server.listen(function(server, cause) { 12 | var client = vertx.createHttpClient({}); 13 | var content = Buffer.buffer(); 14 | var stream = client.websocketStream(8080, "localhost", "/the_uri"); 15 | var observable = Rx.Observable.fromReadStream(stream); 16 | observable.flatMap(function(ws) { 17 | return Rx.Observable.fromReadStream(ws); 18 | }). 19 | forEach( 20 | function(buffer) { 21 | content.appendBuffer(buffer); 22 | }, function(err) { 23 | test.fail(); 24 | } , function() { 25 | server.close(); 26 | test.assertEquals("some_content", content.toString("UTF-8")); 27 | test.testComplete(); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/async_start_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var TimeUnit = java.util.concurrent.TimeUnit; 5 | 6 | // Use an embedded Vert.x 7 | var Vertx = require("vertx-js/vertx"); 8 | 9 | function testAsyncStartStop() { 10 | var vertx = Vertx.vertx(); 11 | var latch = new CountDownLatch(1); 12 | var start = Date.now(); 13 | vertx.deployVerticle("js:async_test_verticle", function(deploymentID, err) { 14 | 15 | Assert.assertNotNull(deploymentID); 16 | Assert.assertNull(err); 17 | Assert.assertTrue(Date.now() - start > 1000); 18 | 19 | var start2 = Date.now(); 20 | 21 | vertx.undeploy(deploymentID, function (v, err) { 22 | Assert.assertNull(err); 23 | Assert.assertTrue(Date.now() - start2 > 1000); 24 | latch.countDown(); 25 | }); 26 | }); 27 | 28 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 29 | } 30 | 31 | if (typeof this[testName] === 'undefined') { 32 | throw "No such test: " + testName; 33 | } 34 | 35 | this[testName](); -------------------------------------------------------------------------------- /vertx-rx-js/src/test/resources/test_http_client_flatmap.js: -------------------------------------------------------------------------------- 1 | var Buffer = require('vertx-js/buffer'); 2 | var test = require("test"); 3 | var Rx = require("rx.vertx"); 4 | 5 | var server = vertx.createHttpServer({port: 8080}); 6 | server.requestStream().handler(function(req) { 7 | req.response().setChunked(true).end("some_content"); 8 | }); 9 | 10 | server.listen(function(server, cause) { 11 | var client = vertx.createHttpClient({}); 12 | var req = client.request("GET", 8080, "localhost", "/the_uri"); 13 | var content = Buffer.buffer(); 14 | var observable = Rx.Observable.fromReadStream(req); 15 | observable. 16 | flatMap(function(resp) { 17 | return Rx.Observable.fromReadStream(resp); 18 | }). 19 | forEach( 20 | function(buffer) { 21 | content.appendBuffer(buffer); 22 | }, 23 | function(err) { 24 | test.fail(); 25 | }, 26 | function() { 27 | server.close(); 28 | test.assertEquals("some_content", content.toString("UTF-8")); 29 | test.testComplete(); 30 | }); 31 | req.end(); 32 | }); 33 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/ExtraTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * 7 | * This test tests all the different types of methods, return values and parameters that can be used in generated 8 | * APIs. 9 | * 10 | * @author Tim Fox 11 | */ 12 | public class ExtraTest extends JSTestBase { 13 | 14 | @Override 15 | protected String getTestFile() { 16 | return "extra_test.js"; 17 | } 18 | 19 | // Test params 20 | 21 | @Test 22 | public void testTypeVarReturn() throws Exception { 23 | runTest(); 24 | } 25 | 26 | @Test 27 | public void testParameterizedReturn() throws Exception { 28 | runTest(); 29 | } 30 | 31 | @Test 32 | public void testTypeVarParam() throws Exception { 33 | // With Java 9 : Long -> Integer in function returns which leads to CCE 34 | if (!System.getProperty("java.version").equals("9")) { 35 | runTest(); 36 | } else { 37 | System.out.println("Skipping testTypeVarParam test on Java 9"); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/EventBusTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package io.vertx.test.lang.js; 18 | 19 | import org.junit.Test; 20 | 21 | /** 22 | * @author Thomas Segismont 23 | */ 24 | public class EventBusTest extends JSTestBase { 25 | 26 | @Override 27 | protected String getTestFile() { 28 | return "event_bus_test.js"; 29 | } 30 | 31 | @Test 32 | public void testSendBuffer() throws Exception { 33 | runTest(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/discovery/service/HelloService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011-2016 The original author or authors 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.test.it.discovery.service; 18 | 19 | import io.vertx.codegen.annotations.ProxyGen; 20 | import io.vertx.codegen.annotations.VertxGen; 21 | import io.vertx.core.AsyncResult; 22 | import io.vertx.core.Handler; 23 | import io.vertx.core.json.JsonObject; 24 | 25 | /** 26 | * @author Clement Escoffier 27 | */ 28 | @ProxyGen 29 | @VertxGen 30 | public interface HelloService { 31 | 32 | void hello(JsonObject name, Handler> resultHandler); 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/InterfaceExtendingInterfaceWithMethod.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.codegen; 2 | 3 | import io.vertx.codegen.annotations.VertxGen; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | @VertxGen 9 | public interface InterfaceExtendingInterfaceWithMethod extends InterfaceWithMethod { 10 | 11 | public static InterfaceExtendingInterfaceWithMethod create() { 12 | return new InterfaceExtendingInterfaceWithMethod() { 13 | @Override 14 | public String meth2(Integer arg) { 15 | return "meth2(" + arg + ")"; 16 | } 17 | @Override 18 | public String meth1() { 19 | return "meth1()"; 20 | } 21 | @Override 22 | public String meth1(String arg) { 23 | return "meth1(" + arg + ")"; 24 | } 25 | @Override 26 | public String meth2() { 27 | return "meth2()"; 28 | } 29 | @Override 30 | public String meth2(String arg) { 31 | return "meth2(" + arg + ")"; 32 | } 33 | }; 34 | } 35 | 36 | // Don't provide meth1 37 | 38 | // Overload meth2 39 | String meth2(Integer arg); 40 | static String static_meth2(Integer arg) { return "static_meth2(" + arg + ")"; } 41 | } 42 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/ConstantTCKTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * 7 | * This test tests all the different types of methods, return values and parameters that can be used in generated 8 | * APIs. 9 | * 10 | * @author Tim Fox 11 | */ 12 | public class ConstantTCKTest extends JSTestBase { 13 | 14 | @Override 15 | protected String getTestFile() { 16 | return "constant_tck_test.js"; 17 | } 18 | 19 | @Test public void testBasic() throws Exception { runTest(); } 20 | @Test public void testVertxGen() throws Exception { runTest(); } 21 | @Test public void testDataObject() throws Exception { runTest(); } 22 | @Test public void testJson() throws Exception { runTest(); } 23 | @Test public void testEnum() throws Exception { runTest(); } 24 | @Test public void testThrowable() throws Exception { runTest(); } 25 | @Test public void testObject() throws Exception { runTest(); } 26 | @Test public void testNullable() throws Exception { runTest(); } 27 | @Test public void testList() throws Exception { runTest(); } 28 | @Test public void testSet() throws Exception { runTest(); } 29 | @Test public void testMap() throws Exception { runTest(); } 30 | } 31 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/dependencies.adoc: -------------------------------------------------------------------------------- 1 | If you are using Maven or Gradle, add the following dependency to the _dependencies_ section of your 2 | project descriptor to access the Vert.x Core API and enable the JavaScript support: 3 | 4 | * Maven (in your `pom.xml`): 5 | 6 | [source,xml,subs="+attributes"] 7 | ---- 8 | 9 | io.vertx 10 | vertx-core 11 | ${maven.version} 12 | 13 | 14 | io.vertx 15 | vertx-lang-js 16 | ${maven.version} 17 | 18 | ---- 19 | 20 | * Gradle (in your `build.gradle` file): 21 | 22 | [source,groovy,subs="+attributes"] 23 | ---- 24 | compile "io.vertx:vertx-core:${maven.version}" 25 | compile "io.vertx:vertx-lang-js:${maven.version}" 26 | ---- 27 | 28 | [IMPORTANT] 29 | ==== 30 | The JavaScript support is based on http://openjdk.java.net/projects/nashorn/[Nashorn], and so is 31 | constrained by Nashorn feature set and limits. It does not support EcmaScript 6, because Nashorn does not support it. 32 | 33 | In addition, _native_ NPM modules cannot be used as they are _compiled_ for Node.JS. NPMs developed in EcmaScript 6 34 | are also not usable. 35 | ==== 36 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/DeployTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class DeployTest extends JSTestBase { 9 | @Override 10 | protected String getTestFile() { 11 | return "js_verticle_test.js"; 12 | } 13 | 14 | @Test 15 | public void testStopCalled() throws Exception { 16 | runTest(); 17 | } 18 | 19 | @Test 20 | public void testFailureInStop() throws Exception { 21 | runTest(); 22 | } 23 | 24 | @Test 25 | public void testStoppedOKIfNoVertxStop() throws Exception { 26 | runTest(); 27 | } 28 | 29 | @Test 30 | public void testDeployMultipleInstances() throws Exception { 31 | runTest(); 32 | } 33 | 34 | @Test 35 | public void testDeployMultipleInstancesWithVertxStart() throws Exception { 36 | runTest(); 37 | } 38 | 39 | @Test 40 | public void testErrorInVerticle() throws Exception { 41 | runTest(); 42 | } 43 | 44 | @Test 45 | public void testSyntaxErrorInVerticle() throws Exception { 46 | runTest(); 47 | } 48 | 49 | @Test 50 | public void testGlobals() throws Exception { 51 | runTest(); 52 | } 53 | 54 | @Test 55 | public void testVerticleGlobal() throws Exception { 56 | runTest(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/ByteConverterMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * @author Tim Fox 24 | */ 25 | public class ByteConverterMap extends HashMap { 26 | 27 | public ByteConverterMap(Map other) { 28 | for (Entry entry: other.entrySet()) { 29 | Object val = entry.getValue(); 30 | if (val == null) { 31 | put(entry.getKey(), null); 32 | } else if (!(val instanceof Byte) && val instanceof Number) { 33 | Number number = (Number)val; 34 | Byte b = number.byteValue(); 35 | put(entry.getKey(), b); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/LongConverterMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * @author Tim Fox 24 | */ 25 | public class LongConverterMap extends HashMap { 26 | 27 | 28 | public LongConverterMap(Map other) { 29 | for (Entry entry: other.entrySet()) { 30 | Object val = entry.getValue(); 31 | if (val == null) { 32 | put(entry.getKey(), null); 33 | } else if (!(val instanceof Long) && val instanceof Number) { 34 | Number number = (Number)val; 35 | Long l = number.longValue(); 36 | put(entry.getKey(), l); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/ShortConverterMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * @author Tim Fox 24 | */ 25 | public class ShortConverterMap extends HashMap { 26 | 27 | public ShortConverterMap(Map other) { 28 | for (Entry entry: other.entrySet()) { 29 | Object val = entry.getValue(); 30 | if (val == null) { 31 | put(entry.getKey(), null); 32 | } else if (!(val instanceof Short) && val instanceof Number) { 33 | Number number = (Number)val; 34 | Short s = number.shortValue(); 35 | put(entry.getKey(), s); 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/codegen/impl/ClassParamOverloadImpl.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.codegen.impl; 2 | 3 | import io.vertx.test.codegen.ClassParamOverload; 4 | import io.vertx.test.codegen.GenericHolder; 5 | 6 | /** 7 | * @author Julien Viet 8 | */ 9 | @SuppressWarnings("unchecked") 10 | public class ClassParamOverloadImpl implements ClassParamOverload { 11 | 12 | @Override 13 | public T typeVarReturn() { 14 | return (T) "wibble"; 15 | } 16 | 17 | @Override 18 | public T typeVarReturn(Class type) { 19 | if (type != Long.class) { 20 | throw new AssertionError("Unexpected type " + type); 21 | } 22 | return type.cast(5L); 23 | } 24 | 25 | @Override 26 | public GenericHolder parameterizedReturn() { 27 | return () -> (T) "cheese"; 28 | } 29 | 30 | @Override 31 | public GenericHolder parameterizedReturn(Class type) { 32 | if (type != Long.class) { 33 | throw new AssertionError("Unexpected type"); 34 | } 35 | return () -> type.cast(10L); 36 | } 37 | 38 | @Override 39 | public boolean typeVarParam(T t) { 40 | return "wibble".equals(t); 41 | } 42 | 43 | @Override 44 | public boolean typeVarParam(Class type, T t) { 45 | return type == Long.class && (Long)t == 20L; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/verticle-configuration.adoc: -------------------------------------------------------------------------------- 1 | === Passing configuration to a verticle 2 | 3 | Configuration in the form of JSON can be passed to a verticle at deployment time: 4 | 5 | [source,javascript] 6 | ---- 7 | var config = { 8 | "name" : "tim", 9 | "directory" : "/blah" 10 | }; 11 | var options = { 12 | "config" : config 13 | }; 14 | vertx.deployVerticle("MyOrderProcessorVerticle.js", options); 15 | ---- 16 | 17 | This configuration is then available via the {@link io.vertx.core.Context} object. The configuration is returned as a 18 | JavaScript object so you can retrieve data as follows: 19 | 20 | [source,javascript] 21 | ---- 22 | // The context object can be retrieve either using: 23 | console.log("Configuration: " + Vertx.currentContext().config().name); 24 | // or: 25 | console.log("Configuration: " + vertx.getOrCreateContext().config().name); 26 | ---- 27 | 28 | NOTE: The access to the `context` object is made either using {@link io.vertx.core.Vertx#currentContext()} or using 29 | {@link io.vertx.core.Vertx#getOrCreateContext()}. 30 | 31 | === Accessing environment variables in a Verticle 32 | 33 | Environment variables and system properties are accessible from a verticle using the Java API: 34 | 35 | [source,javascript] 36 | ---- 37 | console.log(java.lang.System.getProperty("foo")); 38 | console.log(java.lang.System.getenv("HOME")); 39 | ---- 40 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/web/FreeMarkerJavascriptTemplateTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package io.vertx.test.it.web; 18 | 19 | import io.vertx.lang.js.ClasspathFileResolver; 20 | import io.vertx.test.lang.js.JSTestBase; 21 | import org.junit.Ignore; 22 | import org.junit.Test; 23 | 24 | /** 25 | * @author Thomas Segismont 26 | */ 27 | public class FreeMarkerJavascriptTemplateTest extends JSTestBase { 28 | 29 | static { 30 | ClasspathFileResolver.init(); 31 | } 32 | 33 | @Override 34 | protected String getTestFile() { 35 | return "it/web/freemarker_javascript_template_test.js"; 36 | } 37 | 38 | @Ignore // For now it does not pass ! 39 | @Test 40 | public void testTemplate() throws Exception { 41 | runTest(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/healthcheck/verticle.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | vertxStartAsync: function (startFuture) { 3 | vertx.executeBlocking(function (blockingFuture) { 4 | try { 5 | var Router = require("vertx-web-js/router"); 6 | var router = Router.router(vertx); 7 | 8 | var handler = require("vertx-health-checks-js/health_check_handler").create(vertx); 9 | 10 | handler.register("complete-with-ok", function (future) { 11 | future.complete({ok: true}); 12 | }); 13 | 14 | handler.register("complete-with-ko", function (future) { 15 | future.complete({ok: false}); 16 | }); 17 | 18 | handler.register("complete-with-data", function (future) { 19 | future.complete({ok: true, data: { foo: 'bar'}}); 20 | }); 21 | 22 | handler.register("complete-with-nothing", function (future) { 23 | future.complete(); 24 | }); 25 | 26 | router.get("/health/*").handler(handler.handle); 27 | 28 | var server = vertx.createHttpServer(); 29 | server.requestHandler(router.accept).listen(5050); 30 | console.log('>>> verticle: now listening on port 5050') 31 | 32 | blockingFuture.complete() 33 | } catch(error) { 34 | blockingFuture.fail(error) 35 | } 36 | 37 | }, function(result, error) { 38 | error ? startFuture.fail(error) : startFuture.complete(); 39 | }) 40 | }, 41 | 42 | vertxStop: function () { 43 | console.log('verticle stopped') 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/VertxGenConverterSet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import jdk.nashorn.api.scripting.ScriptObjectMirror; 20 | 21 | import java.util.HashSet; 22 | import java.util.List; 23 | 24 | /** 25 | * @author Tim Fox 26 | */ 27 | public class VertxGenConverterSet extends HashSet { 28 | 29 | public VertxGenConverterSet(List other) { 30 | for (Object entry: other) { 31 | if (entry == null) { 32 | add(null); 33 | } else { 34 | if (!(entry instanceof ScriptObjectMirror)) { 35 | throw new IllegalArgumentException("Array does not contain objects"); 36 | } 37 | ScriptObjectMirror mirror = (ScriptObjectMirror)entry; 38 | if (mirror.hasMember("_jdel")) { 39 | add(mirror.getMember("_jdel")); 40 | } else { 41 | throw new IllegalArgumentException("Object in array is not @VertxGen object"); 42 | } 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/VertxGenConverterList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import jdk.nashorn.api.scripting.ScriptObjectMirror; 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | /** 25 | * @author Tim Fox 26 | */ 27 | public class VertxGenConverterList extends ArrayList { 28 | 29 | public VertxGenConverterList(List other) { 30 | for (Object entry: other) { 31 | if (entry == null) { 32 | add(null); 33 | } else { 34 | if (!(entry instanceof ScriptObjectMirror)) { 35 | throw new IllegalArgumentException("Array does not contain objects"); 36 | } 37 | ScriptObjectMirror mirror = (ScriptObjectMirror)entry; 38 | if (mirror.hasMember("_jdel")) { 39 | add(mirror.getMember("_jdel")); 40 | } else { 41 | throw new IllegalArgumentException("Object in array is not @VertxGen object"); 42 | } 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/js_web_test.js: -------------------------------------------------------------------------------- 1 | var TimeUnit = java.util.concurrent.TimeUnit; 2 | var Assert = org.junit.Assert; 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var Vertx = require("vertx-js/vertx"); 5 | var Router = require("vertx-web-js/router"); 6 | var Cookie = require("vertx-js/cookie"); 7 | 8 | function testCookies() { 9 | 10 | var latch = new CountDownLatch(1); 11 | var vertx = Vertx.vertx(); 12 | 13 | var cookie1 = null; 14 | var router = Router.router(vertx); 15 | router.route().handler(function (routingContext) { 16 | var response = routingContext.response(); 17 | cookie1 = routingContext.getCookie("cookie1"); 18 | routingContext.addCookie(Cookie.cookie("cookie2", "apple")); 19 | response.end("Hello World from Vert.x-Web!"); 20 | }); 21 | var server = vertx.createHttpServer(); 22 | server.requestHandler(router.handle).listen(8080); 23 | 24 | var client = vertx.createHttpClient(); 25 | var cookie2 = null; 26 | var req = client.get(8080, "localhost", "/some-uri", function (response) { 27 | console.log("Received response with status code " + response.statusCode()); 28 | cookie2 = response.getHeader("set-cookie"); 29 | latch.countDown(); 30 | }); 31 | req.putHeader("cookie", "cookie1=banana"); 32 | req.end(); 33 | 34 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 35 | vertx.close(); 36 | Assert.assertNotNull(cookie1); 37 | Assert.assertEquals("cookie1", cookie1.getName()); 38 | Assert.assertEquals("banana", cookie1.getValue()); 39 | Assert.assertEquals("cookie2=apple", cookie2); 40 | } 41 | 42 | this[testName](); 43 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/configuring-eventbus.adoc: -------------------------------------------------------------------------------- 1 | The event bus can be configured. It is particularly useful when the event bus is clustered. 2 | Under the hood the event bus uses TCP connections to send and receive messages, so the {@link io.vertx.core.eventbus.EventBusOptions} let you configure all aspects of these TCP connections. 3 | As the event bus acts as a server and client, the configuration is close to {@link io.vertx.core.net.NetClientOptions} and {@link io.vertx.core.net.NetServerOptions}. 4 | 5 | [source,json] 6 | ---- 7 | { 8 | "eventBusOptions": { 9 | "ssl": true, 10 | "keyStoreOptions": { 11 | "path": "keystore.jks", 12 | "password": "wibble" 13 | }, 14 | "trustStoreOptions:" { 15 | "path": "keystore.jks", 16 | "password": "wibble" 17 | }, 18 | clientAuth: "REQUIRED" 19 | } 20 | } 21 | ---- 22 | 23 | The previous snippet depicts how you can use SSL connections for the event bus, instead of plain TCP connections. 24 | 25 | **WARNING**: to enforce the security in clustered mode, you **must** configure the cluster manager to use encryption or enforce security. 26 | Refer to the documentation of the cluster manager for further details. 27 | 28 | The event bus configuration needs to be consistent in all the cluster nodes. 29 | 30 | The {@link io.vertx.core.eventbus.EventBusOptions} also lets you specify whether or not the event bus is clustered, the port and host. 31 | 32 | When used in containers, you can also configure the public host and port: 33 | 34 | [source,json] 35 | ---- 36 | { 37 | "eventBusOptions": { 38 | "clusterPublicHost": "whatever", 39 | "clusterPublicPort": 1234 40 | } 41 | } 42 | ---- 43 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/VertxGenConverterMap.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import jdk.nashorn.api.scripting.ScriptObjectMirror; 20 | 21 | import java.util.HashMap; 22 | import java.util.Map; 23 | 24 | /** 25 | * @author Tim Fox 26 | */ 27 | public class VertxGenConverterMap extends HashMap { 28 | 29 | 30 | public VertxGenConverterMap(Map other) { 31 | for (Map.Entry entry: other.entrySet()) { 32 | if (entry.getValue() == null) { 33 | put(entry.getKey(), null); 34 | } else { 35 | if (!(entry.getValue() instanceof ScriptObjectMirror)) { 36 | throw new IllegalArgumentException("Array does not contain objects"); 37 | } 38 | ScriptObjectMirror mirror = (ScriptObjectMirror)entry.getValue(); 39 | if (mirror.hasMember("_jdel")) { 40 | put(entry.getKey(), mirror.getMember("_jdel")); 41 | } else { 42 | throw new IllegalArgumentException("Object in array is not @VertxGen object"); 43 | } 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/js_timeout_test.js: -------------------------------------------------------------------------------- 1 | var TimeUnit = java.util.concurrent.TimeUnit; 2 | var Assert = org.junit.Assert; 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var Vertx = require("vertx-js/vertx"); 5 | 6 | function testSetTimeout() { 7 | 8 | var latch = new CountDownLatch(1); 9 | var vertx = Vertx.vertx(); 10 | vertx.eventBus().consumer("done").handler(function() { 11 | latch.countDown(); 12 | }); 13 | vertx.deployVerticle("js:test_set_timeout"); 14 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 15 | 16 | } 17 | 18 | function testClearTimeout() { 19 | 20 | var latch = new CountDownLatch(1); 21 | var vertx = Vertx.vertx(); 22 | vertx.eventBus().consumer("done").handler(function(msg) { 23 | Assert.assertEquals("bar", msg.body()); 24 | latch.countDown(); 25 | }); 26 | vertx.deployVerticle("js:test_clear_timeout"); 27 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 28 | 29 | } 30 | 31 | function testSetInterval() { 32 | 33 | var latch = new CountDownLatch(1); 34 | var vertx = Vertx.vertx(); 35 | vertx.eventBus().consumer("done").handler(function() { 36 | latch.countDown(); 37 | }); 38 | vertx.deployVerticle("js:test_set_interval"); 39 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 40 | 41 | } 42 | 43 | function testClearInterval() { 44 | 45 | var latch = new CountDownLatch(1); 46 | var vertx = Vertx.vertx(); 47 | vertx.eventBus().consumer("done").handler(function(msg) { 48 | Assert.assertEquals("bar", msg.body()); 49 | latch.countDown(); 50 | }); 51 | vertx.deployVerticle("js:test_clear_interval"); 52 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 53 | 54 | } 55 | 56 | this[testName](); -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/test_verticle.js: -------------------------------------------------------------------------------- 1 | 2 | // Make sure console globals are in scope 3 | 4 | if (typeof console !== 'object') { 5 | throw "No console global"; 6 | } 7 | 8 | if (typeof console.log !== 'function') { 9 | throw "No console.log"; 10 | } 11 | 12 | if (typeof console.info !== 'function') { 13 | throw "No console.info"; 14 | } 15 | 16 | if (typeof console.warn !== 'function') { 17 | throw "No console.warn"; 18 | } 19 | 20 | if (typeof console.error !== 'function') { 21 | throw "No console.error"; 22 | } 23 | 24 | if (typeof require !== 'function') { 25 | throw "No require global"; 26 | } 27 | 28 | if (typeof vertx !== 'object') { 29 | throw "No vertx global"; 30 | } 31 | 32 | if (typeof setTimeout !== 'function') { 33 | throw "No setTimeout global"; 34 | } 35 | 36 | if (typeof clearTimeout !== 'function') { 37 | throw "No clearTimeout global"; 38 | } 39 | 40 | if (typeof setInterval !== 'function') { 41 | throw "No setInterval global"; 42 | } 43 | 44 | if (typeof clearInterval !== 'function') { 45 | throw "No clearInterval global"; 46 | } 47 | 48 | if (typeof parent !== 'object') { 49 | throw "No parent global"; 50 | } 51 | 52 | if (typeof global !== 'object') { 53 | throw "No global"; 54 | } 55 | 56 | var proc = process; 57 | if (java.lang.System.getProperty('vertx.disableNodeJSProcessENV') == null) { 58 | if (typeof proc !== 'object') { 59 | throw "No process object"; 60 | } 61 | var env = proc.env; 62 | if (typeof env !== 'object') { 63 | throw "No env object"; 64 | } 65 | } else { 66 | if (typeof proc !== 'undefined') { 67 | throw "proc shouldn't be there!"; 68 | } 69 | } 70 | 71 | exports.vertxStop = function() { 72 | vertx.eventBus().send("testComplete", "foo"); 73 | } 74 | 75 | 76 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/discovery/service/HelloServiceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011-2016 The original author or authors 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.test.it.discovery.service; 18 | 19 | import io.vertx.core.AsyncResult; 20 | import io.vertx.core.Future; 21 | import io.vertx.core.Handler; 22 | import io.vertx.core.Vertx; 23 | import io.vertx.core.eventbus.MessageConsumer; 24 | import io.vertx.core.json.JsonObject; 25 | import io.vertx.serviceproxy.ProxyHelper; 26 | 27 | /** 28 | * @author Clement Escoffier 29 | */ 30 | public class HelloServiceImpl implements HelloService { 31 | 32 | private final String msg; 33 | private MessageConsumer service; 34 | 35 | public HelloServiceImpl() { 36 | this("Hello"); 37 | } 38 | 39 | public HelloServiceImpl(String message) { 40 | this.msg = message; 41 | } 42 | 43 | public void start(Vertx vertx, String address) { 44 | service = ProxyHelper.registerService(HelloService.class, vertx, this, address); 45 | } 46 | 47 | public void stop() { 48 | ProxyHelper.unregisterService(service); 49 | } 50 | 51 | @Override 52 | public void hello(JsonObject name, Handler> resultHandler) { 53 | resultHandler.handle(Future.succeededFuture(msg + " " + name.getString("name"))); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | io.vertx 7 | 8 | vertx-parent 9 | 10 | 19 11 | 12 | 13 | 14 | 4.0.0 15 | 16 | pom 17 | 18 | vertx-lang-js-parent 19 | 20 | 3.9.17-SNAPSHOT 21 | 22 | 23 | 24 | 3.9.17-SNAPSHOT 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | io.vertx 35 | 36 | vertx-dependencies 37 | 38 | ${stack.version} 39 | 40 | pom 41 | 42 | import 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | vertx-lang-js-gen 53 | 54 | vertx-lang-js 55 | 56 | vertx-rx-js 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/discovery/HelloServiceConsumer.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2011-2016 The original author or authors 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | var ServiceDiscovery = require("vertx-service-discovery-js/service_discovery"); 18 | var HelloService = require("test-services-js/hello_service.js"); 19 | var EventBusService = require("vertx-service-discovery-js/event_bus_service.js"); 20 | 21 | var discovery = ServiceDiscovery.create(vertx, { 22 | "backendConfiguration": 23 | { 24 | "backend-name": "io.vertx.servicediscovery.impl.DefaultServiceDiscoveryBackend" 25 | } 26 | }); 27 | 28 | 29 | EventBusService.getServiceProxyWithJsonFilter(discovery, 30 | { "service.interface" : "io.vertx.test.it.discovery.service.HelloService"}, 31 | HelloService, 32 | function(ar, ar_err) { 33 | if (ar_err) { 34 | ar_err.printStackTrace(); 35 | vertx.eventBus().send("result", { 36 | "status" : "ko" 37 | }); 38 | } else { 39 | var proxy = ar; 40 | proxy.hello({"name" : "vert.x"}, function(r, err) { 41 | if (err) { 42 | vertx.eventBus().send("result", { 43 | "status" : "ko" 44 | }); 45 | } else { 46 | vertx.eventBus().send("result", { 47 | "status": "ok", 48 | "message": r 49 | }); 50 | ServiceDiscovery.releaseServiceObject(discovery, proxy); 51 | } 52 | }); 53 | } 54 | }); 55 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/in-the-beginning.adoc: -------------------------------------------------------------------------------- 1 | == In the beginning there was Vert.x 2 | 3 | You can't do much in Vert.x-land unless you can communicate with a {@link io.vertx.core.Vertx} object! 4 | 5 | It's the control centre of Vert.x and is how you do pretty much everything, including creating clients and servers, 6 | getting a reference to the event bus, setting timers, as well as many other things. 7 | 8 | So how do you get an instance? 9 | 10 | When you start your application with the CLI, a `vertx` variable will be made available to your code. 11 | 12 | [source,js] 13 | ---- 14 | var server = vertx.createHttpServer(); // <1> 15 | server.requestHandler(function (request) { 16 | request.response().end("Hello world"); 17 | }); 18 | server.listen(8080); 19 | ---- 20 | <1> At runtime, `vertx` variable is available 21 | 22 | Then run the applicaton with the CLI: 23 | 24 | [source,bash] 25 | ---- 26 | vertx run my-verticle.js 27 | ---- 28 | 29 | NOTE: Most applications will only need a single Vert.x instance, but it's possible to create multiple Vert.x instances if you 30 | require, for example, isolation between the event bus or different groups of servers and clients. 31 | 32 | === Specifying options when creating a Vertx object 33 | 34 | When creating a Vert.x object you can also specify options if the defaults aren't right for you. 35 | 36 | [source,bash] 37 | ---- 38 | vertx run my-verticle.js -options my-options.json 39 | ---- 40 | 41 | If you want to increase the worker pool size, your `my-options.json` file may look like: 42 | 43 | [source,json] 44 | ---- 45 | { 46 | "workerPoolSize": 40 47 | } 48 | ---- 49 | 50 | The {@link io.vertx.core.VertxOptions} object has many settings and allows you to configure things like clustering, high availability, pool sizes and various other settings. 51 | 52 | === Creating a clustered Vert.x object 53 | 54 | If you're creating a *clustered Vert.x* (See the section on the <> for more information on clustering the event bus), add the `-cluster` option: 55 | 56 | [source,bash] 57 | ---- 58 | vertx run my-verticle.js -cluster 59 | ---- 60 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/JSRunner.java~HEAD: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import io.vertx.lang.js.ClasspathFileResolver; 4 | 5 | import javax.script.ScriptEngine; 6 | import javax.script.ScriptEngineManager; 7 | import javax.script.ScriptException; 8 | 9 | import java.io.File; 10 | import java.net.URL; 11 | 12 | /** 13 | * @author Tim Fox 14 | */ 15 | public class JSRunner { 16 | 17 | public static void main(String[] args) { 18 | try { 19 | new JSRunner().run("eval_filename.js", "testBrokenModuleSyntaxError", true, true); 20 | } catch (ScriptException e) { 21 | System.out.println("message:" + e.getMessage()); 22 | System.out.println("fileName:" + e.getFileName()); 23 | System.out.println("lineNumber:" + e.getLineNumber()); 24 | } 25 | } 26 | 27 | public void run(String scriptName, String testName) throws Exception { 28 | run(scriptName, testName, true, true); 29 | } 30 | 31 | public void run(String scriptName, String testName, boolean provideRequire, boolean provideConsole) throws ScriptException { 32 | ScriptEngineManager mgr = new ScriptEngineManager(); 33 | ScriptEngine engine = mgr.getEngineByName("nashorn"); 34 | if (provideRequire) { 35 | load("vertx-js/util/jvm-npm.js", engine); 36 | if (provideConsole) { 37 | engine.eval("var console = require('vertx-js/util/console'); var testName = '" + testName + "';"); 38 | } 39 | } 40 | load(scriptName, engine); 41 | } 42 | 43 | private void load(String scriptName, ScriptEngine engine) throws ScriptException { 44 | 45 | String file = ClasspathFileResolver.resolveFilename(scriptName); 46 | if (file == null) { 47 | URL url = getClass().getClassLoader().getResource(scriptName); 48 | if (url == null) { 49 | throw new IllegalStateException("Cannot find " + scriptName + " on classpath"); 50 | } 51 | file = url.getFile(); 52 | } 53 | if (File.separatorChar != '/') { 54 | file = file.replace(File.separatorChar, '/'); 55 | } 56 | engine.eval("load('" + file + "');"); 57 | 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/JSRunner.java~HEAD_0: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import io.vertx.lang.js.ClasspathFileResolver; 4 | 5 | import javax.script.ScriptEngine; 6 | import javax.script.ScriptEngineManager; 7 | import javax.script.ScriptException; 8 | 9 | import java.io.File; 10 | import java.net.URL; 11 | 12 | /** 13 | * @author Tim Fox 14 | */ 15 | public class JSRunner { 16 | 17 | public static void main(String[] args) { 18 | try { 19 | new JSRunner().run("eval_filename.js", "testBrokenModuleSyntaxError", true, true); 20 | } catch (ScriptException e) { 21 | System.out.println("message:" + e.getMessage()); 22 | System.out.println("fileName:" + e.getFileName()); 23 | System.out.println("lineNumber:" + e.getLineNumber()); 24 | } 25 | } 26 | 27 | public void run(String scriptName, String testName) throws Exception { 28 | run(scriptName, testName, true, true); 29 | } 30 | 31 | public void run(String scriptName, String testName, boolean provideRequire, boolean provideConsole) throws ScriptException { 32 | ScriptEngineManager mgr = new ScriptEngineManager(); 33 | ScriptEngine engine = mgr.getEngineByName("nashorn"); 34 | if (provideRequire) { 35 | load("vertx-js/util/jvm-npm.js", engine); 36 | if (provideConsole) { 37 | engine.eval("var console = require('vertx-js/util/console'); var testName = '" + testName + "';"); 38 | } 39 | } 40 | load(scriptName, engine); 41 | } 42 | 43 | private void load(String scriptName, ScriptEngine engine) throws ScriptException { 44 | 45 | String file = ClasspathFileResolver.resolveFilename(scriptName); 46 | if (file == null) { 47 | URL url = getClass().getClassLoader().getResource(scriptName); 48 | if (url == null) { 49 | throw new IllegalStateException("Cannot find " + scriptName + " on classpath"); 50 | } 51 | file = url.getFile(); 52 | } 53 | if (File.separatorChar != '/') { 54 | file = file.replace(File.separatorChar, '/'); 55 | } 56 | engine.eval("load('" + file + "');"); 57 | 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/acme-js/sub_interface.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | /** @module acme-js/sub_interface */ 18 | var utils = require('vertx-js/util/utils'); 19 | 20 | var io = Packages.io; 21 | var JsonObject = io.vertx.core.json.JsonObject; 22 | var JSubInterface = Java.type('com.acme.pkg.sub.SubInterface'); 23 | 24 | /** 25 | 26 | @class 27 | */ 28 | var SubInterface = function(j_val) { 29 | 30 | var j_subInterface = j_val; 31 | var that = this; 32 | 33 | /** 34 | 35 | @public 36 | @param s {string} 37 | @return {string} 38 | */ 39 | this.reverse = function(s) { 40 | var __args = arguments; 41 | if (__args.length === 1 && typeof __args[0] === 'string') { 42 | return j_subInterface["reverse(java.lang.String)"](s); 43 | } else throw new TypeError('function invoked with invalid arguments'); 44 | }; 45 | 46 | // A reference to the underlying Java delegate 47 | // NOTE! This is an internal API and must not be used in user code. 48 | // If you rely on this property your code is likely to break if we change it / remove it without warning. 49 | this._jdel = j_subInterface; 50 | }; 51 | 52 | SubInterface._jclass = utils.getJavaClass("com.acme.pkg.sub.SubInterface"); 53 | SubInterface._jtype = { 54 | accept: function(obj) { 55 | return SubInterface._jclass.isInstance(obj._jdel); 56 | }, 57 | wrap: function(jdel) { 58 | var obj = Object.create(SubInterface.prototype, {}); 59 | SubInterface.apply(obj, arguments); 60 | return obj; 61 | }, 62 | unwrap: function(obj) { 63 | return obj._jdel; 64 | } 65 | }; 66 | SubInterface._create = function(jdel) { 67 | var obj = Object.create(SubInterface.prototype, {}); 68 | SubInterface.apply(obj, arguments); 69 | return obj; 70 | } 71 | module.exports = SubInterface; -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/extra-js/generic_holder.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | /** @module extra-js/generic_holder */ 18 | var utils = require('vertx-js/util/utils'); 19 | 20 | var io = Packages.io; 21 | var JsonObject = io.vertx.core.json.JsonObject; 22 | var JGenericHolder = Java.type('io.vertx.test.codegen.GenericHolder'); 23 | 24 | /** 25 | 26 | @class 27 | */ 28 | var GenericHolder = function(j_val, j_arg_0) { 29 | 30 | var j_genericHolder = j_val; 31 | var that = this; 32 | var j_T = typeof j_arg_0 !== 'undefined' ? j_arg_0 : utils.unknown_jtype; 33 | 34 | /** 35 | 36 | @public 37 | 38 | @return {Object} 39 | */ 40 | this.get = function() { 41 | var __args = arguments; 42 | if (__args.length === 0) { 43 | return j_T.wrap(j_genericHolder["get()"]()); 44 | } else throw new TypeError('function invoked with invalid arguments'); 45 | }; 46 | 47 | // A reference to the underlying Java delegate 48 | // NOTE! This is an internal API and must not be used in user code. 49 | // If you rely on this property your code is likely to break if we change it / remove it without warning. 50 | this._jdel = j_genericHolder; 51 | }; 52 | 53 | GenericHolder._jclass = utils.getJavaClass("io.vertx.test.codegen.GenericHolder"); 54 | GenericHolder._jtype = { 55 | accept: function(obj) { 56 | return GenericHolder._jclass.isInstance(obj._jdel); 57 | }, 58 | wrap: function(jdel) { 59 | var obj = Object.create(GenericHolder.prototype, {}); 60 | GenericHolder.apply(obj, arguments); 61 | return obj; 62 | }, 63 | unwrap: function(obj) { 64 | return obj._jdel; 65 | } 66 | }; 67 | GenericHolder._create = function(jdel) { 68 | var obj = Object.create(GenericHolder.prototype, {}); 69 | GenericHolder.apply(obj, arguments); 70 | return obj; 71 | } 72 | module.exports = GenericHolder; -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/unit/VertxUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.it.unit; 2 | 3 | import io.vertx.core.json.JsonObject; 4 | import io.vertx.ext.unit.collect.EventBusCollector; 5 | import io.vertx.test.core.VertxTestBase; 6 | import org.junit.Test; 7 | 8 | /** 9 | * @author Julien Viet 10 | */ 11 | public class VertxUnitTest extends VertxTestBase { 12 | 13 | @Test 14 | public void testAssertionsJs() throws Exception { 15 | testAssertions("js:it/unit/assertions"); 16 | } 17 | 18 | private void testAssertions(String verticle) throws Exception { 19 | vertx.eventBus().consumer("assert_tests").bodyStream().handler(msg -> { 20 | String type = msg.getString("type"); 21 | switch (type) { 22 | case EventBusCollector.EVENT_TEST_CASE_END: 23 | String name = msg.getString("name"); 24 | if (name.startsWith("fail_")) { 25 | assertNotNull(msg.getValue("failure")); 26 | } else { 27 | assertEquals(null, msg.getValue("failure")); 28 | } 29 | break; 30 | case EventBusCollector.EVENT_TEST_SUITE_END: 31 | testComplete(); 32 | break; 33 | } 34 | }); 35 | vertx.deployVerticle(verticle, ar -> { 36 | assertTrue(ar.succeeded()); 37 | }); 38 | await(); 39 | } 40 | 41 | @Test 42 | public void testJavaScriptTimer() { 43 | vertx.deployVerticle("js:it/unit/timer", ar -> { 44 | assertTrue(ar.succeeded()); 45 | testComplete(); 46 | }); 47 | await(); 48 | } 49 | 50 | @Test 51 | public void testJavaScriptFailure() { 52 | vertx.deployVerticle("js:it/unit/failing", ar -> { 53 | assertTrue(ar.failed()); 54 | assertEquals("Error: the_failure", ar.cause().getMessage()); 55 | testComplete(); 56 | }); 57 | await(); 58 | } 59 | 60 | @org.junit.Test 61 | public void testCoordinated() { 62 | vertx.eventBus().consumer("test").handler(msg -> { 63 | switch (msg.body().getString("type")) { 64 | case EventBusCollector.EVENT_TEST_SUITE_ERROR: 65 | // Replace with data object when done 66 | fail("Unexpected failure " + msg.body().getJsonObject("failure")); 67 | break; 68 | case EventBusCollector.EVENT_TEST_SUITE_END: 69 | testComplete(); 70 | break; 71 | } 72 | }); 73 | vertx.deployVerticle("js:it/unit/coordinated/test", ar -> { 74 | assertTrue(ar.succeeded()); 75 | }); 76 | await(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/lang/js/RequireTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Tim Fox 7 | */ 8 | public class RequireTest extends JSTestBase { 9 | 10 | @Override 11 | protected String getTestFile() { 12 | return "require_test.js"; 13 | } 14 | 15 | @Test 16 | public void testRequireNoExtension() throws Exception { 17 | runTest(); 18 | } 19 | 20 | @Test 21 | public void testRequireWithExtension() throws Exception { 22 | runTest(); 23 | } 24 | 25 | @Test 26 | public void testRequireInDirectoryNoExtension() throws Exception { 27 | runTest(); 28 | } 29 | 30 | @Test 31 | public void testRequireInDirectoryWithExtension() throws Exception { 32 | runTest(); 33 | } 34 | 35 | @Test 36 | public void testRequireRelative() throws Exception { 37 | runTest(); 38 | } 39 | 40 | @Test 41 | public void testRequireNotFound() throws Exception { 42 | runTest(); 43 | } 44 | 45 | @Test 46 | public void testBrokenModuleSyntaxError() throws Exception { 47 | runTest(); 48 | } 49 | 50 | @Test 51 | public void testBrokenModuleTypeErrorInMainBody() throws Exception { 52 | runTest(); 53 | } 54 | 55 | @Test 56 | public void testBrokenModuleTypeErrorInFunction() throws Exception { 57 | runTest(); 58 | } 59 | 60 | @Test 61 | public void testTopLevelIsolated() throws Exception { 62 | runTest(); 63 | } 64 | 65 | @Test 66 | public void testCachedRequires() throws Exception { 67 | runTest(); 68 | } 69 | 70 | @Test 71 | public void testRequireNPMModule() throws Exception { 72 | runTest(); 73 | } 74 | 75 | @Test 76 | public void testRequireNPMModuleUsingNodePath() throws Exception { 77 | runTest(); 78 | } 79 | 80 | @Test 81 | public void testRequireNPMModuleUsingClassPath() throws Exception { 82 | class TestThread extends Thread { 83 | public String result; 84 | public void run() { 85 | try { 86 | runTest("testRequireNPMModuleUsingClassPath"); 87 | result = "PASS"; 88 | } catch (Throwable t) { result = t.getMessage(); } 89 | } 90 | } 91 | TestThread test = new TestThread(); 92 | test.setContextClassLoader(new java.net.URLClassLoader(new java.net.URL[] { new java.io.File("src/test/npm/zip/my_npm_module.zip").toURI().toURL() })); 93 | test.start(); 94 | test.join(); 95 | org.junit.Assert.assertEquals("PASS", test.result); 96 | } 97 | 98 | @Test 99 | public void testMultipleConcurrentRequires() throws Exception { 100 | runTest(); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/inherited_methods_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | var InterfaceWithMethod = require("extra-js/interface_with_method") 3 | var InterfaceExtendingInterfaceWithMethod = require("extra-js/interface_extending_interface_with_method") 4 | var o = InterfaceExtendingInterfaceWithMethod.create() 5 | var testUtils = require("test_utils"); 6 | var assertEquals = testUtils.assertEquals; 7 | 8 | function testCallInheritedMethods() { 9 | // Call meth2() defined by InterfaceWithMethod 10 | assertEquals("meth2()", o.meth2()); 11 | // Call meth2(String) defined by InterfaceWithMethod 12 | assertEquals("meth2(the-string)", o.meth2("the-string")); 13 | // Call meth1() defined by InterfaceWithMethod 14 | assertEquals("meth1()", o.meth1()); 15 | // Call meth1(String) defined by InterfaceWithMethod 16 | assertEquals("meth1(the-string)", o.meth1("the-string")); 17 | } 18 | 19 | function testCallMethodOverloadingInheritedMethods() { 20 | // Call meth2(Integer) defined by InterfaceExtendingInterfaceWithMethod 21 | assertEquals("meth2(4)", o.meth2(4)); 22 | } 23 | 24 | function assertThrowError(fn) { 25 | var called = false; 26 | try { 27 | fn() 28 | called = true; 29 | } catch(expected) { 30 | } 31 | assertEquals(false, called); 32 | } 33 | 34 | function testCallStaticMethods() { 35 | // Call meth2() defined by InterfaceWithMethod 36 | assertEquals("static_meth2()", InterfaceWithMethod.static_meth2()); 37 | assertThrowError(function() { InterfaceExtendingInterfaceWithMethod.static_meth2(); }); 38 | assertEquals("static_meth2(the-string)", InterfaceWithMethod.static_meth2("the-string")); 39 | assertThrowError(function() { InterfaceExtendingInterfaceWithMethod.static_meth2("the-string"); }); 40 | // Call meth2(String) defined by InterfaceWithMethod 41 | assertEquals("static_meth2(the-string)", InterfaceWithMethod.static_meth2("the-string")); 42 | assertThrowError(function() { InterfaceExtendingInterfaceWithMethod.static_meth2("the-string"); }); 43 | // Call meth1() defined by InterfaceWithMethod 44 | assertEquals("static_meth1()", InterfaceWithMethod.static_meth1()); 45 | assertThrowError(function() { InterfaceExtendingInterfaceWithMethod.static_meth1(); }); 46 | // Call meth1(String) defined by InterfaceWithMethod 47 | assertEquals("static_meth1(the-string)", InterfaceWithMethod.static_meth1("the-string")); 48 | assertThrowError(function() { InterfaceExtendingInterfaceWithMethod.static_meth1("the-string"); }); 49 | // Call meth2(Integer) defined by InterfaceExtendingInterfaceWithMethod 50 | assertEquals("static_meth2(4)", InterfaceExtendingInterfaceWithMethod.static_meth2(4)); 51 | } 52 | 53 | if (typeof this[testName] === 'undefined') { 54 | throw "No such test: " + testName; 55 | } 56 | 57 | this[testName](); 58 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/resources/vertx-js/util/console.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var formatRegExp = /%[sdj%]/g; 4 | 5 | function format(f) { 6 | if (typeof f !== 'string') { 7 | var objects = []; 8 | for (var index = 0; index < arguments.length; index++) { 9 | objects.push(JSON.stringify(arguments[index])); 10 | } 11 | return objects.join(' '); 12 | } 13 | 14 | if (arguments.length === 1) return f; 15 | 16 | var i = 1; 17 | var args = arguments; 18 | var len = args.length; 19 | var str = String(f).replace(formatRegExp, function(x) { 20 | if (x === '%%') return '%'; 21 | if (i >= len) return x; 22 | switch (x) { 23 | case '%s': return String(args[i++]); 24 | case '%d': return Number(args[i++]); 25 | case '%j': 26 | try { 27 | return JSON.stringify(args[i++]); 28 | } catch (_) { 29 | return '[Circular]'; 30 | } 31 | // falls through 32 | default: 33 | return x; 34 | } 35 | }); 36 | for (var x = args[i]; i < len; x = args[++i]) { 37 | if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) { 38 | str += ' ' + x; 39 | } else { 40 | str += ' ' + JSON.stringify(x); 41 | } 42 | } 43 | return str; 44 | } 45 | 46 | function Console(stdout, stderr) { 47 | if (!(this instanceof Console)) { 48 | return new Console(stdout, stderr); 49 | } 50 | if (!stdout || !(stdout instanceof java.io.PrintStream)) { 51 | throw new TypeError('Console expects a java.io.PrintStream instance'); 52 | } 53 | if (!stderr) { 54 | stderr = stdout; 55 | } else if (!(stderr instanceof java.io.PrintStream)) { 56 | throw new TypeError('Console expects java.io.PrintStream instances'); 57 | } 58 | 59 | var prop = { 60 | writable: true, 61 | enumerable: false, 62 | configurable: true 63 | }; 64 | prop.value = stdout; 65 | Object.defineProperty(this, '_stdout', prop); 66 | prop.value = stderr; 67 | Object.defineProperty(this, '_stderr', prop); 68 | prop.value = {}; 69 | Object.defineProperty(this, '_times', prop); 70 | 71 | // bind the prototype functions to this Console instance 72 | var keys = Object.keys(Console.prototype); 73 | for (var v = 0; v < keys.length; v++) { 74 | var k = keys[v]; 75 | this[k] = this[k].bind(this); 76 | } 77 | } 78 | 79 | Console.prototype.log = function() { 80 | this._stdout.println(format.apply(null, arguments)); 81 | }; 82 | 83 | 84 | Console.prototype.info = Console.prototype.log; 85 | 86 | 87 | Console.prototype.warn = function() { 88 | this._stderr.println(format.apply(null, arguments)); 89 | }; 90 | 91 | 92 | Console.prototype.error = Console.prototype.warn; 93 | 94 | 95 | module.exports = new Console(java.lang.System.out, java.lang.System.err); 96 | module.exports.Console = Console; -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/JSRunner.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import io.vertx.lang.js.ClasspathFileResolver; 4 | 5 | import javax.script.ScriptEngine; 6 | import javax.script.ScriptEngineManager; 7 | import javax.script.ScriptException; 8 | 9 | import java.io.File; 10 | import java.io.InputStream; 11 | import java.net.JarURLConnection; 12 | import java.net.URL; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | import java.nio.file.StandardCopyOption; 16 | import java.util.jar.JarFile; 17 | 18 | /** 19 | * @author Tim Fox 20 | */ 21 | public class JSRunner { 22 | 23 | public static void main(String[] args) { 24 | try { 25 | new JSRunner().run("eval_filename.js", "testBrokenModuleSyntaxError", true, true); 26 | } catch (ScriptException e) { 27 | System.out.println("message:" + e.getMessage()); 28 | System.out.println("fileName:" + e.getFileName()); 29 | System.out.println("lineNumber:" + e.getLineNumber()); 30 | } 31 | } 32 | 33 | public void run(String scriptName, String testName) throws Exception { 34 | run(scriptName, testName, true, true); 35 | } 36 | 37 | public void run(String scriptName, String testName, boolean provideRequire, boolean provideConsole) throws ScriptException { 38 | ScriptEngineManager mgr = new ScriptEngineManager(); 39 | ScriptEngine engine = mgr.getEngineByName("nashorn"); 40 | if (provideRequire) { 41 | load("vertx-js/util/jvm-npm.js", engine); 42 | if (provideConsole) { 43 | engine.eval("var console = require('vertx-js/util/console'); var testName = '" + testName + "';"); 44 | } 45 | } 46 | load(scriptName, engine); 47 | } 48 | 49 | private void load(String scriptName, ScriptEngine engine) throws ScriptException { 50 | String file = ClasspathFileResolver.resolveFilename(scriptName); 51 | if (file == null) { 52 | URL url = getClass().getClassLoader().getResource(scriptName); 53 | if (url == null) { 54 | throw new IllegalStateException("Cannot find " + scriptName + " on classpath"); 55 | } 56 | if (url.getProtocol().equals("jar")) { 57 | try { 58 | JarURLConnection connection = (JarURLConnection) url.openConnection(); 59 | JarFile f = connection.getJarFile(); 60 | Path path = Files.createTempFile("vertx", ".dat"); 61 | try (InputStream in = f.getInputStream(connection.getJarEntry())) { 62 | Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING); 63 | } 64 | file = path.toFile().getAbsolutePath(); 65 | } catch (Exception e) { 66 | throw new AssertionError(e); 67 | } 68 | } else { 69 | file = url.getFile(); 70 | } 71 | } 72 | if (File.separatorChar != '/') { 73 | file = file.replace(File.separatorChar, '/'); 74 | } 75 | engine.eval("load('" + file + "');"); 76 | } 77 | } 78 | 79 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/hostname-resolution.adoc: -------------------------------------------------------------------------------- 1 | == Host name resolution 2 | 3 | Vert.x uses an an address resolver for resolving host name into IP addresses instead of 4 | the JVM built-in blocking resolver. 5 | 6 | An host name resolves to an IP address using: 7 | 8 | - the _hosts_ file of the operating system 9 | - otherwise DNS queries against a list of servers 10 | 11 | By default it will use the list of the system DNS server addresses from the environment, if that list cannot be 12 | retrieved it will use Google's public DNS servers `"8.8.8.8"` and `"8.8.4.4"`. 13 | 14 | DNS servers can be also configured with {@link io.vertx.core.VertxOptions}: 15 | 16 | [source,json] 17 | ---- 18 | { 19 | "addressResolverOptions": { 20 | "servers": ["192.168.0.1", "192.168.0.2:40000"] 21 | } 22 | } 23 | ---- 24 | 25 | The default port of a DNS server is `53`, when a server uses a different port, this port can be set 26 | using a colon delimiter: `192.168.0.2:40000`. 27 | 28 | NOTE: sometimes it can be desirable to use the JVM built-in resolver, the JVM system property 29 | _-Dvertx.disableDnsResolver=true_ activates this behavior 30 | 31 | === Failover 32 | 33 | When a server does not reply in a timely manner, the resolver will try the next one from the list, the search 34 | is limited by {@link io.vertx.core.dns.AddressResolverOptions#setMaxQueries(int)} (the default value is `4` queries). 35 | 36 | A DNS query is considered as failed when the resolver has not received a correct answer within 37 | {@link io.vertx.core.dns.AddressResolverOptions#getQueryTimeout()} milliseconds (the default value is `5` seconds). 38 | 39 | === Server list rotation 40 | 41 | By default the dns server selection uses the first one, the remaining servers are used for failover. 42 | 43 | You can configure {@link io.vertx.core.dns.AddressResolverOptions#setRotateServers(boolean)} to `true` to let 44 | the resolver perform a round-robin selection instead. It spreads the query load among the servers and avoids 45 | all lookup to hit the first server of the list. 46 | 47 | Failover still applies and will use the next server in the list. 48 | 49 | === Hosts mapping 50 | 51 | The _hosts_ file of the operating system is used to perform an hostname lookup for an ipaddress. 52 | 53 | An alternative _hosts_ file can be used instead: 54 | 55 | [source,json] 56 | ---- 57 | { 58 | "addressResolverOptions": { 59 | "hostsPath": "/path/to/hosts" 60 | } 61 | } 62 | ---- 63 | 64 | === Search domains 65 | 66 | By default the resolver will use the system DNS search domains from the environment. Alternatively an explicit search domain 67 | list can be provided: 68 | 69 | [source,json] 70 | ---- 71 | { 72 | "addressResolverOptions": { 73 | "searchDomains": ["foo.com", "bar.com"] 74 | } 75 | } 76 | ---- 77 | 78 | When a search domain list is used, the threshold for the number of dots is `1` or loaded from `/etc/resolv.conf` 79 | on Linux, it can be configured to a specific value with {@link io.vertx.core.dns.AddressResolverOptions#setNdots(int)}. 80 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/discovery/service/HelloServiceVertxEBProxy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package io.vertx.test.it.discovery.service; 18 | 19 | import io.vertx.core.eventbus.DeliveryOptions; 20 | import io.vertx.core.Vertx; 21 | import io.vertx.core.Future; 22 | import io.vertx.core.json.JsonObject; 23 | import io.vertx.core.json.JsonArray; 24 | import java.util.ArrayList; 25 | import java.util.HashSet; 26 | import java.util.List; 27 | import java.util.Map; 28 | import java.util.Set; 29 | import java.util.stream.Collectors; 30 | import java.util.function.Function; 31 | import io.vertx.serviceproxy.ServiceProxyBuilder; 32 | import io.vertx.serviceproxy.ServiceException; 33 | import io.vertx.serviceproxy.ServiceExceptionMessageCodec; 34 | import io.vertx.serviceproxy.ProxyUtils; 35 | 36 | import io.vertx.core.json.JsonObject; 37 | import io.vertx.core.AsyncResult; 38 | import io.vertx.core.Handler; 39 | /* 40 | Generated Proxy code - DO NOT EDIT 41 | @author Roger the Robot 42 | */ 43 | 44 | @SuppressWarnings({"unchecked", "rawtypes"}) 45 | public class HelloServiceVertxEBProxy implements HelloService { 46 | private Vertx _vertx; 47 | private String _address; 48 | private DeliveryOptions _options; 49 | private boolean closed; 50 | 51 | public HelloServiceVertxEBProxy(Vertx vertx, String address) { 52 | this(vertx, address, null); 53 | } 54 | 55 | public HelloServiceVertxEBProxy(Vertx vertx, String address, DeliveryOptions options) { 56 | this._vertx = vertx; 57 | this._address = address; 58 | this._options = options; 59 | try{ 60 | this._vertx.eventBus().registerDefaultCodec(ServiceException.class, new ServiceExceptionMessageCodec()); 61 | } catch (IllegalStateException ex) {} 62 | } 63 | 64 | @Override 65 | public void hello(JsonObject name, Handler> resultHandler){ 66 | if (closed) { 67 | resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); 68 | return; 69 | } 70 | JsonObject _json = new JsonObject(); 71 | _json.put("name", name); 72 | 73 | DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); 74 | _deliveryOptions.addHeader("action", "hello"); 75 | _vertx.eventBus().request(_address, _json, _deliveryOptions, res -> { 76 | if (res.failed()) { 77 | resultHandler.handle(Future.failedFuture(res.cause())); 78 | } else { 79 | resultHandler.handle(Future.succeededFuture(res.result().body())); 80 | } 81 | }); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/acme-js/my_interface.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | /** @module acme-js/my_interface */ 18 | var utils = require('vertx-js/util/utils'); 19 | var SubInterface = require('acme-js/sub_interface'); 20 | var TestInterface = require('testmodel-js/test_interface'); 21 | 22 | var io = Packages.io; 23 | var JsonObject = io.vertx.core.json.JsonObject; 24 | var JMyInterface = Java.type('com.acme.pkg.MyInterface'); 25 | 26 | /** 27 | 28 | @class 29 | */ 30 | var MyInterface = function(j_val) { 31 | 32 | var j_myInterface = j_val; 33 | var that = this; 34 | 35 | /** 36 | 37 | @public 38 | 39 | @return {SubInterface} 40 | */ 41 | this.sub = function() { 42 | var __args = arguments; 43 | if (__args.length === 0) { 44 | return utils.convReturnVertxGen(SubInterface, j_myInterface["sub()"]()); 45 | } else throw new TypeError('function invoked with invalid arguments'); 46 | }; 47 | 48 | /** 49 | 50 | @public 51 | 52 | @return {TestInterface} 53 | */ 54 | this.method = function() { 55 | var __args = arguments; 56 | if (__args.length === 0) { 57 | return utils.convReturnVertxGen(TestInterface, j_myInterface["method()"]()); 58 | } else throw new TypeError('function invoked with invalid arguments'); 59 | }; 60 | 61 | // A reference to the underlying Java delegate 62 | // NOTE! This is an internal API and must not be used in user code. 63 | // If you rely on this property your code is likely to break if we change it / remove it without warning. 64 | this._jdel = j_myInterface; 65 | }; 66 | 67 | MyInterface._jclass = utils.getJavaClass("com.acme.pkg.MyInterface"); 68 | MyInterface._jtype = { 69 | accept: function(obj) { 70 | return MyInterface._jclass.isInstance(obj._jdel); 71 | }, 72 | wrap: function(jdel) { 73 | var obj = Object.create(MyInterface.prototype, {}); 74 | MyInterface.apply(obj, arguments); 75 | return obj; 76 | }, 77 | unwrap: function(obj) { 78 | return obj._jdel; 79 | } 80 | }; 81 | MyInterface._create = function(jdel) { 82 | var obj = Object.create(MyInterface.prototype, {}); 83 | MyInterface.apply(obj, arguments); 84 | return obj; 85 | } 86 | /** 87 | 88 | @memberof module:acme-js/my_interface 89 | 90 | @return {MyInterface} 91 | */ 92 | MyInterface.create = function() { 93 | var __args = arguments; 94 | if (__args.length === 0) { 95 | return utils.convReturnVertxGen(MyInterface, JMyInterface["create()"]()); 96 | } else throw new TypeError('function invoked with invalid arguments'); 97 | }; 98 | 99 | module.exports = MyInterface; -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/FunctionParamTCKTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * @author Julien Viet 7 | */ 8 | public class FunctionParamTCKTest extends JSTestBase { 9 | 10 | @Override 11 | protected String getTestFile() { 12 | return "function_param_tck_test.js"; 13 | } 14 | 15 | @Test 16 | public void testBasicParam() throws Exception { 17 | runTest(); 18 | } 19 | 20 | @Test 21 | public void testJsonParam() throws Exception { 22 | runTest(); 23 | } 24 | 25 | @Test 26 | public void testVoidParam() throws Exception { 27 | runTest(); 28 | } 29 | 30 | @Test 31 | public void testUserTypeParam() throws Exception { 32 | runTest(); 33 | } 34 | 35 | @Test 36 | public void testObjectParam() throws Exception { 37 | runTest(); 38 | } 39 | 40 | @Test 41 | public void testDataObjectParam() throws Exception { 42 | runTest(); 43 | } 44 | 45 | @Test 46 | public void testEnumParam() throws Exception { 47 | runTest(); 48 | } 49 | 50 | @Test 51 | public void testListParam() throws Exception { 52 | runTest(); 53 | } 54 | 55 | @Test 56 | public void testSetParam() throws Exception { 57 | runTest(); 58 | } 59 | 60 | @Test 61 | public void testMapParam() throws Exception { 62 | runTest(); 63 | } 64 | 65 | @Test 66 | public void testGenericParam() throws Exception { 67 | runTest(); 68 | } 69 | 70 | @Test 71 | public void testGenericUserTypeParam() throws Exception { 72 | runTest(); 73 | } 74 | 75 | @Test 76 | public void testNullableListParam() throws Exception { 77 | runTest(); 78 | } 79 | 80 | @Test 81 | public void testBasicReturn() throws Exception { 82 | // With Java 9 : Byte -> Integer in function returns which leads to CCE 83 | if (!System.getProperty("java.version").equals("9")) { 84 | runTest(); 85 | } else { 86 | System.out.println("Skipping testBasicReturn test on Java 9"); 87 | } 88 | } 89 | 90 | @Test 91 | public void testJsonReturn() throws Exception { 92 | runTest(); 93 | } 94 | 95 | @Test 96 | public void testObjectReturn() throws Exception { 97 | runTest(); 98 | } 99 | 100 | @Test 101 | public void testDataObjectReturn() throws Exception { 102 | runTest(); 103 | } 104 | 105 | @Test 106 | public void testEnumReturn() throws Exception { 107 | runTest(); 108 | } 109 | 110 | @Test 111 | public void testListReturn() throws Exception { 112 | runTest(); 113 | } 114 | 115 | @Test 116 | public void testSetReturn() throws Exception { 117 | runTest(); 118 | } 119 | 120 | @Test 121 | public void testMapReturn() throws Exception { 122 | runTest(); 123 | } 124 | 125 | @Test 126 | public void testGenericReturn() throws Exception { 127 | runTest(); 128 | } 129 | 130 | @Test 131 | public void testGenericUserTypeReturn() throws Exception { 132 | runTest(); 133 | } 134 | 135 | @Test 136 | public void testNullableListReturn() throws Exception { 137 | runTest(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/healthcheck/HealthCheckTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.it.healthcheck; 2 | 3 | import io.vertx.core.Vertx; 4 | import io.vertx.core.json.JsonObject; 5 | import io.vertx.ext.unit.Async; 6 | import io.vertx.ext.unit.TestContext; 7 | import io.vertx.ext.unit.junit.VertxUnitRunner; 8 | import io.vertx.ext.web.client.WebClient; 9 | import org.junit.After; 10 | import org.junit.Assert; 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | import org.junit.runner.RunWith; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | 17 | /** 18 | * Tests the usage of Status in JavaScript, and other language that can pass JSON Object as result to the future. 19 | * 20 | * @author Clement Escoffier 21 | */ 22 | @RunWith(VertxUnitRunner.class) 23 | public class HealthCheckTest { 24 | 25 | private Vertx vertx; 26 | 27 | @Before 28 | public void setUp() { 29 | vertx = Vertx.vertx(); 30 | } 31 | 32 | @After 33 | public void tearDown() { 34 | vertx.close(); 35 | } 36 | 37 | @Test(timeout = 10000L) 38 | public void test(TestContext context) { 39 | Async deploy = context.async(); 40 | System.out.println(">>> test: starting health check verticle"); 41 | vertx.deployVerticle("it/healthcheck/verticle.js", context.asyncAssertSuccess(id -> deploy.complete())); 42 | 43 | deploy.await(); 44 | 45 | WebClient client = WebClient.create(vertx); 46 | 47 | Async nothing = context.async(); 48 | client.get(5050, "localhost", "/health/complete-with-nothing") 49 | .send(async -> { 50 | if (async.failed()) { 51 | context.fail(async.cause()); 52 | } 53 | assertStatus(async.result().bodyAsJsonObject(), "UP"); 54 | assertData(async.result().bodyAsJsonObject(), null); 55 | nothing.complete(); 56 | }); 57 | 58 | nothing.await(); 59 | 60 | Async ok = context.async(); 61 | client.get(5050, "localhost", "/health/complete-with-ok") 62 | .send(async -> { 63 | if (async.failed()) { 64 | context.fail(async.cause()); 65 | } 66 | assertStatus(async.result().bodyAsJsonObject(), "UP"); 67 | assertData(async.result().bodyAsJsonObject(), null); 68 | ok.complete(); 69 | }); 70 | 71 | Async ko = context.async(); 72 | client.get(5050, "localhost", "/health/complete-with-ko") 73 | .send(async -> { 74 | if (async.failed()) { 75 | context.fail(async.cause()); 76 | } 77 | assertStatus(async.result().bodyAsJsonObject(), "DOWN"); 78 | assertData(async.result().bodyAsJsonObject(), null); 79 | ko.complete(); 80 | }); 81 | 82 | 83 | Async extra = context.async(); 84 | client.get(5050, "localhost", "/health/complete-with-data") 85 | .send(async -> { 86 | if (async.failed()) { 87 | context.fail(async.cause()); 88 | } 89 | assertStatus(async.result().bodyAsJsonObject(), "UP"); 90 | assertData(async.result().bodyAsJsonObject(), new JsonObject().put("foo", "bar")); 91 | extra.complete(); 92 | }); 93 | } 94 | 95 | public void assertData(JsonObject obj, JsonObject expected) { 96 | Assert.assertEquals(obj.getJsonObject("data"), expected); 97 | } 98 | 99 | public void assertStatus(JsonObject obj, String expected) { 100 | String status = obj.getString("status", obj.getString("outcome")); 101 | assertThat(status).isEqualTo(expected); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /vertx-rx-js/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | 8 | vertx-lang-js-parent 9 | io.vertx 10 | 3.9.17-SNAPSHOT 11 | 12 | 13 | vertx-rx-js 14 | 3.9.17-SNAPSHOT 15 | 16 | Vert.x RxJs API 17 | 18 | 19 | ${project.basedir}/src/main/asciidoc 20 | js 21 | 22 | 23 | 24 | 25 | 26 | io.vertx 27 | vertx-core 28 | 29 | 30 | io.vertx 31 | vertx-lang-js 32 | 33 | 34 | io.vertx 35 | vertx-core 36 | test-jar 37 | test 38 | 39 | 40 | junit 41 | junit 42 | 4.13.1 43 | test 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | org.asciidoctor 52 | asciidoctor-maven-plugin 53 | 54 | 55 | ${project.groupId} 56 | ${project.artifactId} 57 | ${project.version} 58 | 59 | 60 | 61 | 62 | process-asciidoc 63 | 64 | 65 | 66 | 67 | com.phasebash.jsdoc 68 | jsdoc3-maven-plugin 69 | 1.2.0 70 | 71 | 72 | package 73 | 74 | jsdoc3 75 | 76 | 77 | true 78 | 79 | ${basedir}/src/main/resources 80 | 81 | ${project.build.directory}/docs/vertx-rx/js/jsdoc 82 | 83 | 84 | 85 | 86 | 87 | maven-assembly-plugin 88 | 89 | 90 | package-docs 91 | package 92 | 93 | single 94 | 95 | 96 | true 97 | 98 | ${basedir}/src/main/assembly/docs.xml 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/resources/rx.vertx.js: -------------------------------------------------------------------------------- 1 | ;(function (factory) { 2 | var objectTypes = { 3 | 'boolean': false, 4 | 'function': true, 5 | 'object': true, 6 | 'number': false, 7 | 'string': false, 8 | 'undefined': false 9 | }; 10 | 11 | var root = (objectTypes[typeof window] && window) || this, 12 | freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, 13 | freeModule = objectTypes[typeof module] && module && !module.nodeType && module, 14 | moduleExports = freeModule && freeModule.exports === freeExports && freeExports, 15 | freeGlobal = objectTypes[typeof global] && global; 16 | 17 | if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { 18 | root = freeGlobal; 19 | } 20 | 21 | // Because of build optimizers 22 | if (typeof define === 'function' && define.amd) { 23 | define(['rx.binding', 'exports'], function (Rx, exports) { 24 | root.Rx = factory(root, exports, Rx); 25 | return root.Rx; 26 | }); 27 | } else if (typeof module === 'object' && module && module.exports === freeExports) { 28 | module.exports = factory(root, module.exports, require('./rx')); 29 | } else { 30 | root.Rx = factory(root, {}, root.Rx); 31 | } 32 | }.call(this, function (root, exp, Rx, undefined) { 33 | 34 | // Aliases 35 | var Observable = Rx.Observable, 36 | Observer = Rx.Observer, 37 | observerProto = Observer.prototype; 38 | 39 | Observable.fromReadStream = function () { 40 | if (arguments.length === 1 && typeof arguments[0] === 'object') { 41 | var readStream = arguments[0]; 42 | var subscribed = false; 43 | return Rx.Observable.create(function(observer) { 44 | if (subscribed) { 45 | throw new Error('ReadStream observable support only a single subscription'); 46 | } 47 | subscribed = true; 48 | readStream.exceptionHandler(function(err) { observer.onError(err); }); 49 | readStream.endHandler(function() { observer.onCompleted(); }); 50 | readStream.handler(function(event) { observer.onNext(event); }); 51 | return function() { 52 | readStream._jdel.endHandler(null); 53 | readStream._jdel.exceptionHandler(null); 54 | readStream._jdel.handler(null); // This may call the endHandler 55 | } 56 | }) 57 | } else { 58 | throw new TypeError('function invoked with invalid arguments'); 59 | } 60 | }; 61 | 62 | function toFuture(observer) { 63 | return function(result, cause) { 64 | if (result != null) { 65 | observer.onNext(result); 66 | observer.onCompleted(); 67 | } else { 68 | observer.onError(cause); 69 | } 70 | }; 71 | } 72 | 73 | observerProto.toFuture = function() { 74 | return toFuture(this); 75 | }; 76 | 77 | Rx.observableFuture = function() { 78 | var subject = new Rx.Subject(); 79 | subject.toHandler = function() { 80 | return toFuture(subject); 81 | }; 82 | return subject; 83 | }; 84 | 85 | function toHandler(observer) { 86 | return function(result) { 87 | observer.onNext(result); 88 | }; 89 | } 90 | 91 | observerProto.toHandler = function() { 92 | return toHandler(this); 93 | }; 94 | 95 | Rx.observableHandler = function() { 96 | var subject = new Rx.Subject(); 97 | subject.toHandler = function() { 98 | return toHandler(subject); 99 | }; 100 | return subject; 101 | }; 102 | 103 | return Rx; 104 | })); 105 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/it/web/freemarker_javascript_template_test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | var Assert = org.junit.Assert; 18 | 19 | var CountDownLatch = java.util.concurrent.CountDownLatch; 20 | var TimeUnit = java.util.concurrent.TimeUnit; 21 | 22 | var Vertx = require("vertx-js/vertx"); 23 | 24 | var console = require("vertx-js/util/console"); 25 | 26 | var Router = require("vertx-web-js/router"); 27 | var FreeMarkerTemplateEngine = require("vertx-web-templ-freemarker-js/free_marker_template_engine"); 28 | var TemplateHandler = require("vertx-web-js/template_handler"); 29 | 30 | function testTemplate() { 31 | var vertx = Vertx.vertx(); 32 | var server = vertx.createHttpServer(); 33 | var router = Router.router(vertx); 34 | 35 | var engine = FreeMarkerTemplateEngine.create(vertx); 36 | var handler = TemplateHandler.create(engine, "it/web", "text/plain"); 37 | 38 | router.route().handler(function (context) { 39 | context.put("foo", "badger"); 40 | context.put("bar", ["pipo", "molo"]); 41 | context.put("baz", {"top": "pipo", "bottom": "molo"}); 42 | context.put("team", { 43 | "grenoble": ["Clément"], 44 | "lyon": ["Julien"], 45 | "amsterdam": ["Paulo"], 46 | "marseille": ["Julien", "Thomas"] 47 | }); 48 | context.next(); 49 | }); 50 | router.get().handler(handler.handle); 51 | 52 | var listenLatch = new CountDownLatch(1); 53 | server.requestHandler(router.accept).listen(8080, function (res, res_err) { 54 | if (res_err != null) { 55 | Assert.fail(res_err) 56 | } 57 | listenLatch.countDown(); 58 | }); 59 | Assert.assertTrue(listenLatch.await(5, TimeUnit.SECONDS)); 60 | 61 | var responseLatch = new CountDownLatch(1); 62 | var client = vertx.createHttpClient(); 63 | client.getNow(8080, "localhost", "/altlang", function (response) { 64 | Assert.assertTrue(200 == response.statusCode()); 65 | response.bodyHandler(function (buffer) { 66 | var lines = []; 67 | lines.push("Hello badger"); 68 | lines.push("There is a pipo"); 69 | lines.push("There is a molo"); 70 | lines.push("top"); 71 | lines.push("bottom"); 72 | lines.push("pipo"); 73 | lines.push("molo"); 74 | lines.push("Julien loves Olympique de Marseille"); 75 | lines.push("Thomas loves Olympique de Marseille"); 76 | lines.push(""); 77 | var actual = buffer.toString().replace(/\r\n/g , "\n"); 78 | Assert.assertEquals(lines.join("\n"), actual); 79 | responseLatch.countDown(); 80 | }); 81 | }); 82 | Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS)); 83 | 84 | var closeLatch = new CountDownLatch(2); 85 | client.close(); 86 | server.close(function (res, res_err) { 87 | if (res_err != null) { 88 | Assert.fail(res_err) 89 | } 90 | closeLatch.countDown(); 91 | }); 92 | vertx.close(function (res, res_err) { 93 | if (res_err != null) { 94 | Assert.fail(res_err) 95 | } 96 | closeLatch.countDown(); 97 | }); 98 | Assert.assertTrue(closeLatch.await(5, TimeUnit.SECONDS)); 99 | } 100 | 101 | if (typeof this[testName] === "undefined") { 102 | throw "No such test: " + testName; 103 | } 104 | 105 | this[testName](); 106 | -------------------------------------------------------------------------------- /vertx-rx-js/src/test/java/io/vertx/rx/js/test/JsIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.rx.js.test; 2 | 3 | import io.vertx.test.core.VertxTestBase; 4 | import org.junit.Test; 5 | 6 | /** 7 | * @author Julien Viet 8 | */ 9 | public class JsIntegrationTest extends VertxTestBase { 10 | 11 | public static VertxAssert current; 12 | 13 | @Override 14 | public void before() throws Exception { 15 | super.before(); 16 | current = new VertxAssert() { 17 | @Override 18 | public void testComplete() { 19 | JsIntegrationTest.this.testComplete(); 20 | } 21 | @Override 22 | public void assertEquals(Object expected, Object actual) { 23 | JsIntegrationTest.this.assertEquals(expected, actual); 24 | } 25 | @Override 26 | public void assertEquals(long expected, long actual) { 27 | JsIntegrationTest.this.assertEquals(expected, actual); 28 | } 29 | @Override 30 | public void assertTrue(boolean b) { 31 | JsIntegrationTest.this.assertTrue(b); 32 | } 33 | @Override 34 | public void assertFalse(boolean b) { 35 | JsIntegrationTest.this.assertFalse(b); 36 | } 37 | @Override 38 | public void fail(String msg) { 39 | JsIntegrationTest.this.fail(msg); 40 | } 41 | }; 42 | } 43 | 44 | @Test 45 | public void testConsumeBodyStream() throws Throwable { 46 | deployTest("test_consume_body_stream.js"); 47 | } 48 | 49 | @Test 50 | public void testAdaptItem() throws Throwable { 51 | deployTest("test_adapt_item.js"); 52 | } 53 | 54 | @Test 55 | public void testConsumerRegistration() throws Throwable { 56 | deployTest("test_consumer_registration.js"); 57 | } 58 | 59 | @Test 60 | public void testCompleted() throws Throwable { 61 | deployTest("test_completed.js"); 62 | } 63 | 64 | @Test 65 | public void testSubscribeTwice() throws Throwable { 66 | deployTest("test_subscribe_twice.js"); 67 | } 68 | 69 | @Test 70 | public void testObservableFuture() throws Throwable { 71 | deployTest("test_observable_future.js"); 72 | } 73 | 74 | @Test 75 | public void testObserverToFuture() throws Throwable { 76 | deployTest("test_observer_to_future.js"); 77 | } 78 | 79 | @Test 80 | public void testObservableHandler() throws Throwable { 81 | deployTest("test_observable_handler.js"); 82 | } 83 | 84 | @Test 85 | public void testObserverToHandler() throws Throwable { 86 | deployTest("test_observer_to_handler.js"); 87 | } 88 | 89 | @Test 90 | public void testScheduledTimer() throws Throwable { 91 | deployTest("test_scheduled_timer.js"); 92 | } 93 | 94 | @Test 95 | public void testScheduledBuffer() throws Throwable { 96 | deployTest("test_scheduled_buffer.js"); 97 | } 98 | 99 | @Test 100 | public void testConcat() throws Throwable { 101 | deployTest("test_concat.js"); 102 | } 103 | 104 | @Test 105 | public void testTimeMap() throws Throwable { 106 | deployTest("test_time_map.js"); 107 | } 108 | 109 | @Test 110 | public void testHttpClient() throws Throwable { 111 | deployTest("test_http_client.js"); 112 | } 113 | 114 | @Test 115 | public void testHttpClientFlatMap() throws Throwable { 116 | deployTest("test_http_client_flatmap.js"); 117 | } 118 | 119 | @Test 120 | public void testWebsocketClient() throws Throwable { 121 | deployTest("test_websocket_client.js"); 122 | } 123 | 124 | @Test 125 | public void testWebsocketClientFlatMap() throws Throwable { 126 | deployTest("test_websocket_client_flatmap.js"); 127 | } 128 | 129 | private void deployTest(String test) { 130 | vertx.deployVerticle(test, ar -> { 131 | if (!ar.succeeded()) { 132 | Throwable cause = ar.cause(); 133 | cause.printStackTrace(); 134 | fail(cause.getMessage()); 135 | } 136 | }); 137 | await(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /vertx-lang-js/src/main/docoverride/vertx-core/js/override/verticles.adoc: -------------------------------------------------------------------------------- 1 | === Writing Verticles 2 | 3 | JavaScript verticles are implemented either as http://wiki.commonjs.org/wiki/Modules/1.1[CommonJS modules] or 4 | https://www.npmjs.com/[NPM] modules. 5 | 6 | IMPORTANT: JavaScript support requires Java 1.8.0_45+. You can check your Java version with `java -version`. Please 7 | update if needed. 8 | 9 | Here's an example JavaScript verticle written as a CommonJS module. 10 | 11 | JavaScript verticles will have the following globals pre-set as a convenience: 12 | 13 | * +vertx+ - A reference to the Vertx object 14 | * +console+ A reference to the <> object 15 | 16 | [source, javascript] 17 | ---- 18 | // the vertx and console objects can be used directly as: 19 | vertx.setPeriodic(1000, function() { 20 | console.log('Timer has fired'); 21 | }); 22 | 23 | // Optional - called when verticle is undeployed 24 | exports.vertxStop = function() { 25 | console.log('stop called'); 26 | } 27 | ---- 28 | 29 | When the verticle is deployed the body of the script will be executed. 30 | 31 | Optionally a `vertxStop` callback can be defined to be notified when the verticle is undeployed. Notice that such 32 | a registration is made using `exports.vertxStop = function() { ... }`. 33 | 34 | === The console 35 | 36 | In addition to the `vertx` object, JavaScript verticles have access to a `console` object that let them print 37 | messages. The messages are printed on Java `System.out` and `System.err`: 38 | 39 | [source, javascript] 40 | ---- 41 | console.log("hello"); // Print on System.out 42 | console.warn("warning, something wrong is happening"); // Print on System.err 43 | console.error("something terrible happened"); // Print on System.err 44 | ---- 45 | 46 | === Defining a start method 47 | 48 | By default, when your verticle is deployed, vert.x execute the body of the javascript file. However, you can 49 | define a start method as follows: 50 | 51 | [source, javascript] 52 | ---- 53 | exports.vertxStart = function() { 54 | console.log("This is my verticle and it is starting..."); 55 | } 56 | ---- 57 | 58 | As for `vertStop` seen above, the method is defined on the `exports` object. 59 | 60 | IMPORTANT: Even with a `vertxStart` method defined, vert.x executes the body of the file. 61 | 62 | === Asynchronous Verticle start and stop 63 | 64 | Sometimes you want to do something in your verticle start-up which takes some time and you don't want the verticle to 65 | be considered deployed until that happens. For example you might want to deploy other verticles in the start method. 66 | 67 | You can't block waiting for the other verticles to deploy in your start method as that would break the Golden Rule. 68 | 69 | So how can you do this? 70 | 71 | The way to do it is to implement theasynchronous* start method. This version of the method takes a `Future` object 72 | as a parameter. When the method returns the verticle willnot* be considered deployed yet. Some time later, after 73 | you've done everything you need to do (e.g. start other verticles), you can call complete on the Future (or fail) to 74 | signal that you're done. 75 | 76 | Here's an example: 77 | 78 | [source, javascript] 79 | ---- 80 | exports.vertxStartAsync = function(startFuture) { 81 | vertx.deployVerticle("verticle.js", function(res, err) { 82 | if (err) { 83 | startFuture.fail(); 84 | } else { 85 | startFuture.complete(); 86 | } 87 | }); 88 | }; 89 | ---- 90 | 91 | Similarly, there is an asynchronous version of the `stop` method too. You use this if you want to do some verticle 92 | cleanup that takes some time. 93 | 94 | [source, javascript] 95 | ---- 96 | exports.vertxStopAsync = function(stopFuture) { 97 | obj.doSomethingThatTakesTimes(function(r, err) { 98 | if (err) { 99 | stopFuture.fail(); 100 | } else { 101 | stopFuture.complete(); 102 | } 103 | }); 104 | }; 105 | ---- 106 | 107 | INFO: You don't need to manually undeploy child verticles started by a verticle, in the verticle's stop method. 108 | Vert.x will automatically undeploy any child verticles when the parent is undeployed. 109 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/ClasspathFileResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * All rights reserved. This program and the accompanying materials 5 | * are made available under the terms of the Eclipse Public License v1.0 6 | * and Apache License v2.0 which accompanies this distribution. 7 | * 8 | * The Eclipse Public License is available at 9 | * http://www.eclipse.org/legal/epl-v10.html 10 | * 11 | * The Apache License v2.0 is available at 12 | * http://www.opensource.org/licenses/apache2.0.php 13 | * 14 | * You may elect to redistribute this code under either of these licenses. 15 | */ 16 | 17 | package io.vertx.lang.js; 18 | 19 | import io.vertx.core.Vertx; 20 | import io.vertx.core.VertxException; 21 | 22 | import java.io.File; 23 | import java.io.InputStream; 24 | import java.net.URI; 25 | import java.net.URL; 26 | import java.nio.file.Files; 27 | import java.nio.file.Path; 28 | import java.util.ArrayList; 29 | import java.util.Arrays; 30 | import java.util.List; 31 | import java.util.concurrent.CountDownLatch; 32 | import java.util.concurrent.TimeUnit; 33 | 34 | /** 35 | * @author Tim Fox 36 | */ 37 | public class ClasspathFileResolver { 38 | 39 | private static List sourceDirs = Arrays.asList("src/main/resources", "src/test/resources"); 40 | private static List sourceDirFiles; 41 | private static boolean enabled; 42 | private static File DEBUG_JS_SOURCE_DIR = new File(".vertx/debug-js"); 43 | 44 | public static void init() { 45 | sourceDirFiles = new ArrayList<>(sourceDirs.size()); 46 | for (String dir: sourceDirs) { 47 | File f = new File(dir); 48 | if (f.exists()) { 49 | enabled = true; 50 | sourceDirFiles.add(f); 51 | } 52 | } 53 | if (enabled) { 54 | if (DEBUG_JS_SOURCE_DIR.exists()) { 55 | Vertx vertx = Vertx.vertx(); 56 | CountDownLatch latch = new CountDownLatch(1); 57 | vertx.fileSystem().deleteRecursive(DEBUG_JS_SOURCE_DIR.getAbsolutePath(), true, res -> { 58 | if (res.failed()) { 59 | res.cause().printStackTrace(); 60 | } 61 | latch.countDown(); 62 | }); 63 | try { 64 | latch.await(30, TimeUnit.SECONDS); 65 | } catch (InterruptedException ignore) { 66 | } 67 | vertx.close(); 68 | } else { 69 | DEBUG_JS_SOURCE_DIR.mkdirs(); 70 | } 71 | } 72 | } 73 | 74 | public static String resolveFilename(String scriptName) { 75 | 76 | if (enabled) { 77 | // This is a hack to get Nashorn debugging working, as it doesn't work if the script is in the target directory 78 | // which it will be when running in the IDE as IntelliJ copies 79 | // src/main/resources and src/test/resources to target/classes during make!! 80 | 81 | // We assume that the JavaScript source is in one of the source dirs 82 | 83 | for (File sourceDir: sourceDirFiles) { 84 | File source = new File(sourceDir, scriptName); 85 | if (source.exists()) { 86 | return source.getPath(); 87 | } 88 | } 89 | 90 | // Maybe source file is in a jar? 91 | ClassLoader cl = Thread.currentThread().getContextClassLoader(); 92 | cl = cl == null ? ClasspathFileResolver.class.getClassLoader() : cl; 93 | 94 | URL url = cl.getResource(scriptName); 95 | if (url != null) { 96 | try { 97 | URI uri = url.toURI(); 98 | if (uri.getScheme().equals("jar")) { 99 | 100 | File target = new File(DEBUG_JS_SOURCE_DIR, scriptName); 101 | if (!target.exists()) { 102 | target.getParentFile().mkdirs(); 103 | Path path = target.toPath(); 104 | try (InputStream is = url.openStream()) { 105 | Files.copy(is, path); 106 | } 107 | } 108 | 109 | return target.getPath(); 110 | } 111 | } catch (Exception e) { 112 | throw new VertxException(e); 113 | } 114 | } 115 | 116 | return null; 117 | } else { 118 | return null; 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/asciidoc/dataobjects.adoc: -------------------------------------------------------------------------------- 1 | = Cheatsheets 2 | 3 | [[DataObjectWithBuffer]] 4 | == DataObjectWithBuffer 5 | 6 | ++++ 7 | ++++ 8 | ''' 9 | 10 | [cols=">25%,^25%,50%"] 11 | [frame="topbot"] 12 | |=== 13 | ^|Name | Type ^| Description 14 | |[[buffer]]`buffer`|`Buffer`|- 15 | |=== 16 | 17 | [[DataObjectWithLists]] 18 | == DataObjectWithLists 19 | 20 | ++++ 21 | ++++ 22 | ''' 23 | 24 | [cols=">25%,^25%,50%"] 25 | [frame="topbot"] 26 | |=== 27 | ^|Name | Type ^| Description 28 | |[[booleanValues]]`booleanValues`|`Array of Boolean`|- 29 | |[[dataObjectValues]]`dataObjectValues`|`Array of link:dataobjects.html#TestDataObject[TestDataObject]`|- 30 | |[[doubleValues]]`doubleValues`|`Array of Number (Double)`|- 31 | |[[enumValues]]`enumValues`|`Array of link:enums.html#TestEnum[TestEnum]`|- 32 | |[[floatValues]]`floatValues`|`Array of Number (Float)`|- 33 | |[[genEnumValues]]`genEnumValues`|`Array of link:enums.html#TestGenEnum[TestGenEnum]`|- 34 | |[[integerValues]]`integerValues`|`Array of Number (Integer)`|- 35 | |[[jsonArrayValues]]`jsonArrayValues`|`Array of Json array`|- 36 | |[[jsonObjectValues]]`jsonObjectValues`|`Array of Json object`|- 37 | |[[longValues]]`longValues`|`Array of Number (Long)`|- 38 | |[[shortValues]]`shortValues`|`Array of Number (Short)`|- 39 | |[[stringValues]]`stringValues`|`Array of String`|- 40 | |=== 41 | 42 | [[DataObjectWithMaps]] 43 | == DataObjectWithMaps 44 | 45 | ++++ 46 | ++++ 47 | ''' 48 | 49 | [cols=">25%,^25%,50%"] 50 | [frame="topbot"] 51 | |=== 52 | ^|Name | Type ^| Description 53 | |[[booleanValues]]`booleanValues`|`Boolean`|- 54 | |[[dataObjectValues]]`dataObjectValues`|`link:dataobjects.html#TestDataObject[TestDataObject]`|- 55 | |[[doubleValues]]`doubleValues`|`Number (Double)`|- 56 | |[[enumValues]]`enumValues`|`link:enums.html#TestEnum[TestEnum]`|- 57 | |[[floatValues]]`floatValues`|`Number (Float)`|- 58 | |[[genEnumValues]]`genEnumValues`|`link:enums.html#TestGenEnum[TestGenEnum]`|- 59 | |[[integerValues]]`integerValues`|`Number (Integer)`|- 60 | |[[jsonArrayValues]]`jsonArrayValues`|`Json array`|- 61 | |[[jsonObjectValues]]`jsonObjectValues`|`Json object`|- 62 | |[[longValues]]`longValues`|`Number (Long)`|- 63 | |[[shortValues]]`shortValues`|`Number (Short)`|- 64 | |[[stringValues]]`stringValues`|`String`|- 65 | |=== 66 | 67 | [[DataObjectWithNestedBuffer]] 68 | == DataObjectWithNestedBuffer 69 | 70 | ++++ 71 | ++++ 72 | ''' 73 | 74 | [cols=">25%,^25%,50%"] 75 | [frame="topbot"] 76 | |=== 77 | ^|Name | Type ^| Description 78 | |[[buffer]]`buffer`|`Buffer`|- 79 | |[[buffers]]`buffers`|`Array of Buffer`|- 80 | |[[nested]]`nested`|`link:dataobjects.html#DataObjectWithBuffer[DataObjectWithBuffer]`|- 81 | |=== 82 | 83 | [[DataObjectWithOnlyJsonObjectConstructor]] 84 | == DataObjectWithOnlyJsonObjectConstructor 85 | 86 | ++++ 87 | ++++ 88 | ''' 89 | 90 | [cols=">25%,^25%,50%"] 91 | [frame="topbot"] 92 | |=== 93 | ^|Name | Type ^| Description 94 | |[[foo]]`foo`|`String`|- 95 | |=== 96 | 97 | [[DataObjectWithValues]] 98 | == DataObjectWithValues 99 | 100 | ++++ 101 | ++++ 102 | ''' 103 | 104 | [cols=">25%,^25%,50%"] 105 | [frame="topbot"] 106 | |=== 107 | ^|Name | Type ^| Description 108 | |[[booleanValue]]`booleanValue`|`Boolean`|- 109 | |[[boxedBooleanValue]]`boxedBooleanValue`|`Boolean`|- 110 | |[[boxedDoubleValue]]`boxedDoubleValue`|`Number (Double)`|- 111 | |[[boxedFloatValue]]`boxedFloatValue`|`Number (Float)`|- 112 | |[[boxedIntValue]]`boxedIntValue`|`Number (Integer)`|- 113 | |[[boxedLongValue]]`boxedLongValue`|`Number (Long)`|- 114 | |[[boxedShortValue]]`boxedShortValue`|`Number (Short)`|- 115 | |[[dataObjectValue]]`dataObjectValue`|`link:dataobjects.html#TestDataObject[TestDataObject]`|- 116 | |[[doubleValue]]`doubleValue`|`Number (double)`|- 117 | |[[enumValue]]`enumValue`|`link:enums.html#TestEnum[TestEnum]`|- 118 | |[[floatValue]]`floatValue`|`Number (float)`|- 119 | |[[genEnumValue]]`genEnumValue`|`link:enums.html#TestGenEnum[TestGenEnum]`|- 120 | |[[intValue]]`intValue`|`Number (int)`|- 121 | |[[jsonArrayValue]]`jsonArrayValue`|`Json array`|- 122 | |[[jsonObjectValue]]`jsonObjectValue`|`Json object`|- 123 | |[[longValue]]`longValue`|`Number (long)`|- 124 | |[[shortValue]]`shortValue`|`Number (short)`|- 125 | |[[stringValue]]`stringValue`|`String`|- 126 | |=== 127 | 128 | [[TestDataObject]] 129 | == TestDataObject 130 | 131 | ++++ 132 | ++++ 133 | ''' 134 | 135 | [cols=">25%,^25%,50%"] 136 | [frame="topbot"] 137 | |=== 138 | ^|Name | Type ^| Description 139 | |[[bar]]`bar`|`Number (int)`|- 140 | |[[foo]]`foo`|`String`|- 141 | |[[wibble]]`wibble`|`Number (double)`|- 142 | |=== 143 | 144 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/extra-js/class_param_overload.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | /** @module extra-js/class_param_overload */ 18 | var utils = require('vertx-js/util/utils'); 19 | var GenericHolder = require('extra-js/generic_holder'); 20 | 21 | var io = Packages.io; 22 | var JsonObject = io.vertx.core.json.JsonObject; 23 | var JClassParamOverload = Java.type('io.vertx.test.codegen.ClassParamOverload'); 24 | 25 | /** 26 | 27 | @class 28 | */ 29 | var ClassParamOverload = function(j_val) { 30 | 31 | var j_classParamOverload = j_val; 32 | var that = this; 33 | 34 | /** 35 | 36 | @public 37 | @param type {todo} 38 | @return {Object} 39 | */ 40 | this.typeVarReturn = function() { 41 | var __args = arguments; 42 | if (__args.length === 0) { 43 | return utils.convReturnTypeUnknown(j_classParamOverload["typeVarReturn()"]()); 44 | } else if (__args.length === 1 && typeof __args[0] === 'function') { 45 | return utils.get_jtype(__args[0]).wrap(j_classParamOverload["typeVarReturn(java.lang.Class)"](utils.get_jclass(__args[0]))); 46 | } else throw new TypeError('function invoked with invalid arguments'); 47 | }; 48 | 49 | /** 50 | 51 | @public 52 | @param type {todo} 53 | @return {GenericHolder} 54 | */ 55 | this.parameterizedReturn = function() { 56 | var __args = arguments; 57 | if (__args.length === 0) { 58 | return utils.convReturnVertxGen(GenericHolder, j_classParamOverload["parameterizedReturn()"](), undefined); 59 | } else if (__args.length === 1 && typeof __args[0] === 'function') { 60 | return utils.convReturnVertxGen(GenericHolder, j_classParamOverload["parameterizedReturn(java.lang.Class)"](utils.get_jclass(__args[0])), utils.get_jtype(__args[0])); 61 | } else throw new TypeError('function invoked with invalid arguments'); 62 | }; 63 | 64 | /** 65 | 66 | @public 67 | @param type {todo} 68 | @param t {Object} 69 | @return {boolean} 70 | */ 71 | this.typeVarParam = function() { 72 | var __args = arguments; 73 | if (__args.length === 1 && typeof __args[0] !== 'function') { 74 | return j_classParamOverload["typeVarParam(java.lang.Object)"](utils.convParamTypeUnknown(__args[0])); 75 | } else if (__args.length === 2 && typeof __args[0] === 'function' && typeof __args[1] !== 'function') { 76 | return j_classParamOverload["typeVarParam(java.lang.Class,java.lang.Object)"](utils.get_jclass(__args[0]), utils.get_jtype(__args[0]).unwrap(__args[1])); 77 | } else throw new TypeError('function invoked with invalid arguments'); 78 | }; 79 | 80 | // A reference to the underlying Java delegate 81 | // NOTE! This is an internal API and must not be used in user code. 82 | // If you rely on this property your code is likely to break if we change it / remove it without warning. 83 | this._jdel = j_classParamOverload; 84 | }; 85 | 86 | ClassParamOverload._jclass = utils.getJavaClass("io.vertx.test.codegen.ClassParamOverload"); 87 | ClassParamOverload._jtype = { 88 | accept: function(obj) { 89 | return ClassParamOverload._jclass.isInstance(obj._jdel); 90 | }, 91 | wrap: function(jdel) { 92 | var obj = Object.create(ClassParamOverload.prototype, {}); 93 | ClassParamOverload.apply(obj, arguments); 94 | return obj; 95 | }, 96 | unwrap: function(obj) { 97 | return obj._jdel; 98 | } 99 | }; 100 | ClassParamOverload._create = function(jdel) { 101 | var obj = Object.create(ClassParamOverload.prototype, {}); 102 | ClassParamOverload.apply(obj, arguments); 103 | return obj; 104 | } 105 | /** 106 | 107 | @memberof module:extra-js/class_param_overload 108 | 109 | @return {ClassParamOverload} 110 | */ 111 | ClassParamOverload.create = function() { 112 | var __args = arguments; 113 | if (__args.length === 0) { 114 | return utils.convReturnVertxGen(ClassParamOverload, JClassParamOverload["create()"]()); 115 | } else throw new TypeError('function invoked with invalid arguments'); 116 | }; 117 | 118 | module.exports = ClassParamOverload; -------------------------------------------------------------------------------- /vertx-lang-js/src/test/java/io/vertx/test/it/discovery/service/HelloServiceVertxProxyHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package io.vertx.test.it.discovery.service; 18 | 19 | import io.vertx.test.it.discovery.service.HelloService; 20 | import io.vertx.core.Vertx; 21 | import io.vertx.core.Handler; 22 | import io.vertx.core.AsyncResult; 23 | import io.vertx.core.eventbus.EventBus; 24 | import io.vertx.core.eventbus.Message; 25 | import io.vertx.core.eventbus.MessageConsumer; 26 | import io.vertx.core.eventbus.DeliveryOptions; 27 | import io.vertx.core.eventbus.ReplyException; 28 | import io.vertx.core.json.JsonObject; 29 | import io.vertx.core.json.JsonArray; 30 | import java.util.Collection; 31 | import java.util.ArrayList; 32 | import java.util.HashSet; 33 | import java.util.List; 34 | import java.util.Map; 35 | import java.util.Set; 36 | import java.util.UUID; 37 | import java.util.stream.Collectors; 38 | import io.vertx.serviceproxy.ServiceBinder; 39 | import io.vertx.serviceproxy.ProxyHandler; 40 | import io.vertx.serviceproxy.ServiceException; 41 | import io.vertx.serviceproxy.ServiceExceptionMessageCodec; 42 | import io.vertx.serviceproxy.HelperUtils; 43 | 44 | import io.vertx.core.json.JsonObject; 45 | import io.vertx.core.AsyncResult; 46 | import io.vertx.core.Handler; 47 | /* 48 | Generated Proxy code - DO NOT EDIT 49 | @author Roger the Robot 50 | */ 51 | 52 | @SuppressWarnings({"unchecked", "rawtypes"}) 53 | public class HelloServiceVertxProxyHandler extends ProxyHandler { 54 | 55 | public static final long DEFAULT_CONNECTION_TIMEOUT = 5 * 60; // 5 minutes 56 | private final Vertx vertx; 57 | private final HelloService service; 58 | private final long timerID; 59 | private long lastAccessed; 60 | private final long timeoutSeconds; 61 | 62 | public HelloServiceVertxProxyHandler(Vertx vertx, HelloService service){ 63 | this(vertx, service, DEFAULT_CONNECTION_TIMEOUT); 64 | } 65 | 66 | public HelloServiceVertxProxyHandler(Vertx vertx, HelloService service, long timeoutInSecond){ 67 | this(vertx, service, true, timeoutInSecond); 68 | } 69 | 70 | public HelloServiceVertxProxyHandler(Vertx vertx, HelloService service, boolean topLevel, long timeoutSeconds) { 71 | this.vertx = vertx; 72 | this.service = service; 73 | this.timeoutSeconds = timeoutSeconds; 74 | try { 75 | this.vertx.eventBus().registerDefaultCodec(ServiceException.class, 76 | new ServiceExceptionMessageCodec()); 77 | } catch (IllegalStateException ex) {} 78 | if (timeoutSeconds != -1 && !topLevel) { 79 | long period = timeoutSeconds * 1000 / 2; 80 | if (period > 10000) { 81 | period = 10000; 82 | } 83 | this.timerID = vertx.setPeriodic(period, this::checkTimedOut); 84 | } else { 85 | this.timerID = -1; 86 | } 87 | accessed(); 88 | } 89 | 90 | 91 | private void checkTimedOut(long id) { 92 | long now = System.nanoTime(); 93 | if (now - lastAccessed > timeoutSeconds * 1000000000) { 94 | close(); 95 | } 96 | } 97 | 98 | @Override 99 | public void close() { 100 | if (timerID != -1) { 101 | vertx.cancelTimer(timerID); 102 | } 103 | super.close(); 104 | } 105 | 106 | private void accessed() { 107 | this.lastAccessed = System.nanoTime(); 108 | } 109 | 110 | public void handle(Message msg) { 111 | try{ 112 | JsonObject json = msg.body(); 113 | String action = msg.headers().get("action"); 114 | if (action == null) throw new IllegalStateException("action not specified"); 115 | accessed(); 116 | switch (action) { 117 | case "hello": { 118 | service.hello((io.vertx.core.json.JsonObject)json.getValue("name"), 119 | HelperUtils.createHandler(msg)); 120 | break; 121 | } 122 | default: throw new IllegalStateException("Invalid action: " + action); 123 | } 124 | } catch (Throwable t) { 125 | msg.reply(new ServiceException(500, t.getMessage())); 126 | throw t; 127 | } 128 | } 129 | } -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/main/java/io/vertx/lang/js/JSDocGenerator.java: -------------------------------------------------------------------------------- 1 | package io.vertx.lang.js; 2 | 3 | import io.vertx.codegen.Case; 4 | import io.vertx.codegen.type.ClassKind; 5 | import io.vertx.codegen.type.ClassTypeInfo; 6 | import io.vertx.codegen.type.EnumTypeInfo; 7 | import io.vertx.codegen.type.TypeInfo; 8 | import io.vertx.codegen.type.TypeMirrorFactory; 9 | import io.vertx.codetrans.CodeTranslator; 10 | import io.vertx.codetrans.lang.js.JavaScriptLang; 11 | import io.vertx.docgen.Coordinate; 12 | import io.vertx.docgen.DocGenerator; 13 | 14 | import javax.annotation.processing.ProcessingEnvironment; 15 | import javax.lang.model.element.Element; 16 | import javax.lang.model.element.ElementKind; 17 | import javax.lang.model.element.ExecutableElement; 18 | import javax.lang.model.element.TypeElement; 19 | import javax.lang.model.element.VariableElement; 20 | 21 | /** 22 | * @author Julien Viet 23 | */ 24 | public class JSDocGenerator implements DocGenerator { 25 | 26 | private TypeMirrorFactory factory; 27 | private CodeTranslator translator; 28 | private ProcessingEnvironment env; 29 | 30 | @Override 31 | public void init(ProcessingEnvironment processingEnv) { 32 | factory = new TypeMirrorFactory(processingEnv.getElementUtils(), processingEnv.getTypeUtils()); 33 | translator = new CodeTranslator(processingEnv); 34 | env = processingEnv; 35 | } 36 | 37 | @Override 38 | public String getName() { 39 | return "js"; 40 | } 41 | 42 | @Override 43 | public String renderSource(ExecutableElement elt, String source) { 44 | JavaScriptLang lang = new JavaScriptLang(); 45 | try { 46 | return translator.translate(elt, lang); 47 | } catch (Exception e) { 48 | System.out.println("Cannot generate " + elt.getEnclosingElement().getSimpleName() + "#" + elt.getSimpleName() + " : " + e.getMessage()); 49 | return "Code not translatable"; 50 | } 51 | } 52 | 53 | @Override 54 | public String resolveTypeLink(TypeElement elt, Coordinate coordinate) { 55 | TypeInfo type; 56 | try { 57 | type = factory.create(elt.asType()); 58 | } catch (Exception e) { 59 | System.out.println("Could not resolve doc link for type " + elt.getQualifiedName()); 60 | return null; 61 | } 62 | if (type.getKind() == ClassKind.ENUM && ((EnumTypeInfo) type).isGen()) { 63 | String baselink; 64 | if (coordinate == null) { 65 | baselink = "../"; 66 | } else { 67 | baselink = "../../" + coordinate.getArtifactId() + "/"; 68 | } 69 | return baselink + "enums.html#" + elt.getSimpleName().toString(); 70 | } 71 | if (type.getKind() == ClassKind.DATA_OBJECT) { 72 | String baselink; 73 | if (coordinate == null) { 74 | baselink = "../"; 75 | } else { 76 | baselink = "../../" + coordinate.getArtifactId() + "/"; 77 | } 78 | return baselink + "dataobjects.html#" + elt.getSimpleName().toString(); 79 | } 80 | if (type.getKind() == ClassKind.API) { 81 | ClassTypeInfo ct = type.getRaw(); 82 | 83 | return "../../jsdoc/module-" + ct.getModule().getName(Case.KEBAB) + "-js_" + Case.SNAKE.format(Case.CAMEL.parse(elt.getSimpleName().toString())) + "-" + elt.getSimpleName() + ".html"; 84 | } 85 | return null; 86 | } 87 | 88 | @Override 89 | public String resolveMethodLink(ExecutableElement elt, Coordinate coordinate) { 90 | TypeElement typeElt = (TypeElement) elt.getEnclosingElement(); 91 | String link = resolveTypeLink(typeElt, coordinate); 92 | if (link != null) { 93 | if (link.contains("cheatsheet")) { 94 | link = link + '#' + java.beans.Introspector.decapitalize(elt.getSimpleName().toString().substring(3)); 95 | } else { 96 | link = link + '#' + elt.getSimpleName(); 97 | } 98 | } 99 | return link; 100 | } 101 | 102 | @Override 103 | public String resolveLabel(Element elt, String defaultLabel) { 104 | if (elt.getKind() == ElementKind.METHOD) { 105 | TypeInfo type = factory.create(elt.getEnclosingElement().asType()); 106 | if (type.getKind() == ClassKind.DATA_OBJECT) { 107 | String name = elt.getSimpleName().toString(); 108 | if (name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3))) { 109 | name = java.beans.Introspector.decapitalize(name.substring(3)); 110 | } 111 | return name; 112 | } 113 | } 114 | return defaultLabel; 115 | } 116 | 117 | @Override 118 | public String resolveConstructorLink(ExecutableElement elt, Coordinate coordinate) { 119 | return "todo"; 120 | } 121 | 122 | @Override 123 | public String resolveFieldLink(VariableElement elt, Coordinate coordinate) { 124 | return "todo"; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/java/io/vertx/test/lang/js/GenericsTCKTest.java: -------------------------------------------------------------------------------- 1 | package io.vertx.test.lang.js; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * 7 | * This test tests all the different types of methods, return values and parameters that can be used in generated 8 | * APIs. 9 | * 10 | * @author Julien Viet 11 | */ 12 | public class GenericsTCKTest extends JSTestBase { 13 | 14 | @Override 15 | protected String getTestFile() { 16 | return "generics_tck_test.js"; 17 | } 18 | 19 | // Test params 20 | 21 | @Test 22 | public void testMethodWithBasicParameterizedReturn() throws Exception { 23 | runTest(); 24 | } 25 | 26 | @Test 27 | public void testMethodWithHandlerBasicParameterized() throws Exception { 28 | runTest(); 29 | } 30 | 31 | @Test 32 | public void testMethodWithHandlerAsyncResultBasicParameterized() throws Exception { 33 | runTest(); 34 | } 35 | 36 | @Test 37 | public void testMethodWithFunctionParamBasicParameterized() throws Exception { 38 | runTest(); 39 | } 40 | 41 | @Test 42 | public void testMethodWithJsonParameterizedReturn() throws Exception { 43 | runTest(); 44 | } 45 | 46 | @Test 47 | public void testMethodWithHandlerJsonParameterized() throws Exception { 48 | runTest(); 49 | } 50 | 51 | @Test 52 | public void testMethodWithHandlerAsyncResultJsonParameterized() throws Exception { 53 | runTest(); 54 | } 55 | 56 | @Test 57 | public void testMethodWithFunctionParamJsonParameterized() throws Exception { 58 | runTest(); 59 | } 60 | 61 | @Test 62 | public void testMethodWithDataObjectParameterizedReturn() throws Exception { 63 | runTest(); 64 | } 65 | 66 | @Test 67 | public void testMethodWithHandlerDataObjectParameterized() throws Exception { 68 | runTest(); 69 | } 70 | 71 | @Test 72 | public void testMethodWithHandlerAsyncResultDataObjectParameterized() throws Exception { 73 | runTest(); 74 | } 75 | 76 | @Test 77 | public void testMethodWithFunctionParamDataObjectParameterized() throws Exception { 78 | runTest(); 79 | } 80 | 81 | @Test 82 | public void testMethodWithEnumParameterizedReturn() throws Exception { 83 | runTest(); 84 | } 85 | 86 | @Test 87 | public void testMethodWithHandlerEnumParameterized() throws Exception { 88 | runTest(); 89 | } 90 | 91 | @Test 92 | public void testMethodWithHandlerAsyncResultEnumParameterized() throws Exception { 93 | runTest(); 94 | } 95 | 96 | @Test 97 | public void testMethodWithFunctionParamEnumParameterized() throws Exception { 98 | runTest(); 99 | } 100 | 101 | @Test 102 | public void testMethodWithUserTypeParameterizedReturn() throws Exception { 103 | runTest(); 104 | } 105 | 106 | @Test 107 | public void testMethodWithHandlerUserTypeParameterized() throws Exception { 108 | runTest(); 109 | } 110 | 111 | @Test 112 | public void testMethodWithHandlerAsyncResultUserTypeParameterized() throws Exception { 113 | runTest(); 114 | } 115 | 116 | @Test 117 | public void testMethodWithFunctionParamUserTypeParameterized() throws Exception { 118 | runTest(); 119 | } 120 | 121 | @Test 122 | public void testMethodWithClassTypeParameterizedReturn() throws Exception { 123 | runTest(); 124 | } 125 | 126 | @Test 127 | public void testMethodWithHandlerClassTypeParameterized() throws Exception { 128 | runTest(); 129 | } 130 | 131 | @Test 132 | public void testMethodWithHandlerAsyncResultClassTypeParameterized() throws Exception { 133 | runTest(); 134 | } 135 | 136 | @Test 137 | public void testMethodWithFunctionParamClassTypeParameterized() throws Exception { 138 | runTest(); 139 | } 140 | 141 | @Test 142 | public void testMethodWithClassTypeParam() throws Exception { 143 | runTest(); 144 | } 145 | 146 | @Test 147 | public void testMethodWithClassTypeReturn() throws Exception { 148 | runTest(); 149 | } 150 | 151 | @Test 152 | public void testMethodWithClassTypeHandler() throws Exception { 153 | runTest(); 154 | } 155 | 156 | @Test 157 | public void testMethodWithClassTypeHandlerAsyncResult() throws Exception { 158 | runTest(); 159 | } 160 | 161 | @Test 162 | public void testMethodWithClassTypeFunctionParam() throws Exception { 163 | runTest(); 164 | } 165 | 166 | @Test 167 | public void testMethodWithClassTypeFunctionReturn() throws Exception { 168 | runTest(); 169 | } 170 | 171 | @Test 172 | public void testInterfaceWithStringArg() throws Exception { 173 | runTest(); 174 | } 175 | 176 | @Test 177 | public void testInterfaceWithVariableArg() throws Exception { 178 | runTest(); 179 | } 180 | 181 | @Test 182 | public void testInterfaceWithApiArg() throws Exception { 183 | runTest(); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /vertx-rx-js/src/main/asciidoc/js/index.adoc: -------------------------------------------------------------------------------- 1 | = Vert.x for RxJS 2 | :toc: left 3 | 4 | https://github.com/Reactive-Extensions/RxJS[RxJS] is a popular library for composing asynchronous and event 5 | based programs using observable sequences for the JavaScript. 6 | 7 | Vert.x integrates naturally with RxJS, allowing to use observable wherever you can use streams or asynchronous results. 8 | 9 | Vert.x for RxJS comes as an extension for RxJS: 10 | 11 | [source,js] 12 | ---- 13 | var Rx = require("rx.vertx"); 14 | ---- 15 | 16 | It provides the `Rx` object we need for creating `Observable`, or other kind of Rx objects. 17 | 18 | If you are using Maven or Gradle, add the following dependency to the _dependencies_ section of your build descriptor: 19 | 20 | * Maven (in your `pom.xml`): 21 | 22 | [source,xml,subs="+attributes"] 23 | ---- 24 | 25 | {maven-groupId} 26 | {maven-artifactId} 27 | {maven-version} 28 | 29 | ---- 30 | 31 | * Gradle (in your `build.gradle` file): 32 | 33 | [source,groovy,subs="+attributes"] 34 | ---- 35 | compile {maven-groupId}:{maven-artifactId}:{maven-version} 36 | ---- 37 | 38 | == Read stream support 39 | 40 | RxJS observable is a perfect match for Vert.x read streams : both provide a flow of items. 41 | A read stream can be adapted to an observable with the `Rx.Observable.fromReadStream` function: 42 | 43 | [source,js] 44 | ---- 45 | include::read_stream.js[tags=example] 46 | ---- 47 | 48 | == Handler support 49 | 50 | The `rx.vertx` module provides an `observableHandler` function: 51 | 52 | [source,js] 53 | ---- 54 | include::handler.js[tags=example] 55 | ---- 56 | 57 | Rx can also turn an existing Observer into an handler: 58 | 59 | [source,js] 60 | ---- 61 | include::observer_to_handler.js[tags=example] 62 | ---- 63 | 64 | == Future support 65 | 66 | In Vert.x future objects are modelled as async result handlers and occur as last parameter of asynchronous methods. 67 | 68 | The `rx.vertx` module provides an `observableFuture` function: 69 | 70 | [source,js] 71 | ---- 72 | include::future.js[tags=example] 73 | ---- 74 | 75 | Rx can also turn an existing Observer into an future: 76 | 77 | [source,js] 78 | ---- 79 | include::observer_to_future.js[tags=example] 80 | ---- 81 | 82 | == Scheduler support 83 | 84 | RxJS relies on the default context method _timeout_ and _interval_ functions to schedule operations. The 85 | vertx-js integration implements such functions providing an out of the box scheduler support. 86 | 87 | == Examples 88 | 89 | Let's study now a few examples of using Vert.x with RxJava. 90 | 91 | === EventBus message stream 92 | 93 | The event bus message consumer provides naturally an stream of messages: 94 | 95 | [source,js] 96 | ---- 97 | include::event_bus_messages.js[tags=example] 98 | ---- 99 | 100 | The message consumer provides a stream of messages. The `Message#body()` method gives access to a new 101 | stream of message bodies if needed: 102 | 103 | [source,js] 104 | ---- 105 | include::event_bus_bodies.js[tags=example] 106 | ---- 107 | 108 | RxJS map/reduce composition style can be then be used: 109 | 110 | [source,js] 111 | ---- 112 | include::event_bus_map_reduce.js[tags=example] 113 | ---- 114 | 115 | === Timers 116 | 117 | Timer task can be created with `Vertx#timerStream(long)`: 118 | 119 | [source,js] 120 | ---- 121 | include::timer.js[tags=example] 122 | ---- 123 | 124 | Periodic task can be created with `Vertx#periodicStream(long)`: 125 | 126 | === Http client requests 127 | 128 | The HttpClientRequest provides a one shot callback with the 129 | `http.HttpClientResponse` object. The observable reports a request failure. 130 | 131 | [source,js] 132 | ---- 133 | include::http_client_request.js[tags=example] 134 | ---- 135 | 136 | The response can be processed as an stream of buffer: 137 | 138 | [source,js] 139 | ---- 140 | include::http_client_response.js[tags=example] 141 | ---- 142 | 143 | === Http server requests 144 | 145 | The `HttpServer#requestStream()` provides a callback for each incoming 146 | request: 147 | 148 | [source,js] 149 | ---- 150 | include::http_server_request.js[tags=example] 151 | ---- 152 | 153 | The `HttpServerRequest` can then be adapted to a buffer observable: 154 | 155 | [source,js] 156 | ---- 157 | include::http_server_request_observable.js[tags=example] 158 | ---- 159 | 160 | === Websocket client 161 | 162 | The `HttpClient#websocketStream` provides a single callback when the websocket connects, otherwise a failure: 163 | 164 | [source,js] 165 | ---- 166 | include::websocket_client.js[tags=example] 167 | ---- 168 | 169 | The `WebSocket` can then be turned into an observable of buffer easily 170 | 171 | [source,js] 172 | ---- 173 | include::websocket_client_buffer.js[tags=example] 174 | ---- 175 | 176 | === Websocket server 177 | 178 | The `HttpServer#websocketStream()` provides a callback for each incoming connection: 179 | 180 | [source,js] 181 | ---- 182 | include::websocket_server.js[tags=example] 183 | ---- 184 | 185 | The `ServerWebSocket` can be turned into a buffer observable easily: 186 | 187 | [source,js] 188 | ---- 189 | include::websocket_server_buffer.js[tags=example] 190 | ---- 191 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/src/test/resources/constant_tck_test.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Red Hat, Inc. 3 | * 4 | * Red Hat licenses this file to you under the Apache License, version 2.0 5 | * (the "License"); you may not use this file except in compliance with the 6 | * License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | var Assert = org.junit.Assert; 18 | 19 | var ConstantTCK = require('testmodel-js/constant_tck'); 20 | var RefedInterface1 = require('testmodel-js/refed_interface1'); 21 | 22 | var refed_obj = new RefedInterface1(new Packages.io.vertx.codegen.testmodel.RefedInterface1Impl()); 23 | var refed_obj2 = new RefedInterface1(new Packages.io.vertx.codegen.testmodel.RefedInterface1Impl()); 24 | 25 | var testUtils = require("test_utils"); 26 | var assertEquals = testUtils.assertEquals; 27 | 28 | function testBasic() { 29 | assertEquals(ConstantTCK.BYTE, 123); 30 | assertEquals(ConstantTCK.SHORT, 12345); 31 | assertEquals(ConstantTCK.INT, 12345464); 32 | assertEquals(ConstantTCK.LONG, 65675123); 33 | assertEquals(ConstantTCK.FLOAT, 1.23); 34 | assertEquals(ConstantTCK.DOUBLE, 3.34535); 35 | Assert.assertTrue(ConstantTCK.BOOLEAN); 36 | assertEquals("Y", "" + ConstantTCK.CHAR); 37 | assertEquals("orangutan", ConstantTCK.STRING); 38 | } 39 | 40 | function testVertxGen() { 41 | var ret = ConstantTCK.VERTX_GEN; 42 | assertEquals("chaffinch", ret.getString()); 43 | Assert.assertTrue(ret._jdel); 44 | } 45 | 46 | function testDataObject() { 47 | var ret = ConstantTCK.DATA_OBJECT; 48 | Assert.assertTrue(typeof ret === 'object'); 49 | assertEquals("foo", ret.foo); 50 | assertEquals(123, ret.bar); 51 | assertEquals(0.0, ret.wibble); 52 | } 53 | 54 | function testJson() { 55 | var ret = ConstantTCK.JSON_OBJECT; 56 | Assert.assertTrue(typeof ret === 'object') 57 | assertEquals("stilton", ret.cheese); 58 | ret = ConstantTCK.JSON_ARRAY; 59 | Assert.assertTrue(typeof ret === 'object') 60 | Assert.assertTrue(ret instanceof Array) 61 | assertEquals("socks", ret[0]); 62 | assertEquals("shoes", ret[1]); 63 | } 64 | 65 | function testEnum() { 66 | assertEquals("JULIEN", ConstantTCK.ENUM); 67 | } 68 | 69 | function testThrowable() { 70 | assertEquals("test", ConstantTCK.THROWABLE.getMessage()); 71 | } 72 | 73 | function testObject() { 74 | assertEquals(ConstantTCK.OBJECT, 4); 75 | } 76 | 77 | function testNullable() { 78 | var ret = ConstantTCK.NULLABLE_NON_NULL; 79 | assertEquals("chaffinch", ret.getString()); 80 | Assert.assertTrue(ret._jdel); 81 | Assert.assertNull(ConstantTCK.NULLABLE_NULL) 82 | } 83 | 84 | function checkArray(array) { 85 | Assert.assertTrue(Array.isArray(array)); 86 | assertEquals(array.length, 1); 87 | } 88 | 89 | function testList() { 90 | checkArray(ConstantTCK.LONG_LIST); 91 | assertEquals(ConstantTCK.LONG_LIST[0], 65675123); 92 | checkArray(ConstantTCK.VERTX_GEN_LIST); 93 | assertEquals(ConstantTCK.VERTX_GEN_LIST[0].getString(), 'chaffinch'); 94 | checkArray(ConstantTCK.JSON_OBJECT_LIST); 95 | assertEquals(ConstantTCK.JSON_OBJECT_LIST[0]['cheese'], 'stilton'); 96 | checkArray(ConstantTCK.JSON_ARRAY_LIST); 97 | assertEquals(ConstantTCK.JSON_ARRAY_LIST[0][0], 'socks'); 98 | assertEquals(ConstantTCK.JSON_ARRAY_LIST[0][1], 'shoes'); 99 | assertEquals(ConstantTCK.JSON_ARRAY_LIST[0].length, 2); 100 | checkArray(ConstantTCK.DATA_OBJECT_LIST); 101 | assertEquals("" + ConstantTCK.DATA_OBJECT_LIST[0].foo, 'foo'); 102 | assertEquals("" + ConstantTCK.DATA_OBJECT_LIST[0].bar, 123); 103 | checkArray(ConstantTCK.ENUM_LIST); 104 | assertEquals("" + ConstantTCK.ENUM_LIST[0], 'JULIEN'); 105 | } 106 | 107 | function testSet() { 108 | checkArray(ConstantTCK.LONG_SET); 109 | assertEquals(ConstantTCK.LONG_SET[0], 65675123); 110 | checkArray(ConstantTCK.VERTX_GEN_SET); 111 | assertEquals(ConstantTCK.VERTX_GEN_SET[0].getString(), 'chaffinch'); 112 | checkArray(ConstantTCK.JSON_OBJECT_SET); 113 | assertEquals(ConstantTCK.JSON_OBJECT_SET[0]['cheese'], 'stilton'); 114 | checkArray(ConstantTCK.JSON_ARRAY_SET); 115 | assertEquals(ConstantTCK.JSON_ARRAY_SET[0][0], 'socks'); 116 | assertEquals(ConstantTCK.JSON_ARRAY_SET[0][1], 'shoes'); 117 | assertEquals(ConstantTCK.JSON_ARRAY_SET[0].length, 2); 118 | checkArray(ConstantTCK.DATA_OBJECT_SET); 119 | assertEquals("" + ConstantTCK.DATA_OBJECT_SET[0].foo, 'foo'); 120 | assertEquals("" + ConstantTCK.DATA_OBJECT_SET[0].bar, 123); 121 | checkArray(ConstantTCK.ENUM_SET); 122 | assertEquals("" + ConstantTCK.ENUM_SET[0], 'JULIEN'); 123 | } 124 | 125 | function testMap() { 126 | assertEquals(ConstantTCK.LONG_MAP['foo'], 65675123); 127 | assertEquals(ConstantTCK.JSON_OBJECT_MAP['foo']['cheese'], 'stilton'); 128 | assertEquals(ConstantTCK.JSON_ARRAY_MAP['foo'][0], 'socks'); 129 | assertEquals(ConstantTCK.JSON_ARRAY_MAP['foo'][1], 'shoes'); 130 | assertEquals(ConstantTCK.JSON_ARRAY_MAP['foo'].length, 2); 131 | } 132 | 133 | if (typeof this[testName] === 'undefined') { 134 | throw "No such test: " + testName; 135 | } 136 | 137 | this[testName](); 138 | -------------------------------------------------------------------------------- /vertx-lang-js-gen/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | io.vertx 6 | vertx-lang-js-parent 7 | 3.9.17-SNAPSHOT 8 | ../pom.xml 9 | 10 | 11 | 4.0.0 12 | 13 | vertx-lang-js-gen 14 | 3.9.17-SNAPSHOT 15 | 16 | Vert.x JavaScript Language Support 17 | 18 | 19 | ${project.basedir}/src/main/asciidoc 20 | ${java.home}/../lib/tools.jar 21 | 22 | 23 | 24 | 25 | 26 | io.vertx 27 | vertx-codegen 28 | provided 29 | 30 | 31 | io.vertx 32 | vertx-docgen 33 | true 34 | 35 | 36 | io.vertx 37 | vertx-core 38 | 39 | 40 | io.vertx 41 | vertx-codetrans 42 | true 43 | 44 | 45 | org.mvel 46 | mvel2 47 | 2.3.1.Final 48 | provided 49 | 50 | 51 | junit 52 | junit 53 | 4.13.1 54 | test 55 | 56 | 57 | io.vertx 58 | vertx-codegen 59 | tck 60 | test 61 | 62 | 63 | io.vertx 64 | vertx-codegen 65 | tck-sources 66 | test 67 | 68 | 69 | io.vertx 70 | vertx-codegen 71 | sources 72 | test 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | org.apache.maven.plugins 83 | maven-surefire-plugin 84 | 85 | 86 | %4$s: %3$s - %5$s %6$s%n 87 | 88 | 89 | ${project.build.testSourceDirectory} 90 | ${project.basedir}/src/main/resources 91 | 92 | 93 | src/test/npm 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | maven-dependency-plugin 102 | 103 | 104 | 105 | unpack-codegen 106 | generate-test-sources 107 | 108 | unpack-dependencies 109 | 110 | 111 | io.vertx 112 | vertx-codegen 113 | jar 114 | tck-sources 115 | ${project.build.directory}/sources/codegen 116 | 117 | 118 | 119 | 120 | 121 | org.bsc.maven 122 | maven-processor-plugin 123 | 3.1.0 124 | 125 | 126 | 127 | generate-codegen 128 | 129 | process 130 | 131 | generate-test-sources 132 | 133 | 134 | %4$s: %3$s - %5$s %6$s%n 135 | 136 | 137 | io.vertx.codegen.CodeGenProcessor 138 | 139 | 140 | ${project.basedir}/src/test 141 | JavaScript 142 | 143 | ${project.build.directory}/sources/codegen 144 | 145 | ${project.basedir}/src/test/java 146 | 147 | 148 | 149 | 150 | 151 | 152 | junit 153 | junit 154 | 4.13.1 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/js_verticle_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var CountDownLatch = java.util.concurrent.CountDownLatch; 4 | var TimeUnit = java.util.concurrent.TimeUnit; 5 | 6 | var testUtils = require("test_utils"); 7 | var assertEquals = testUtils.assertEquals; 8 | 9 | // Use an embedded Vert.x 10 | var Vertx = require("vertx-js/vertx"); 11 | 12 | var console = require("vertx-js/util/console"); 13 | 14 | function testStopCalled() { 15 | var vertx = Vertx.vertx(); 16 | var latch = new CountDownLatch(1); 17 | vertx.deployVerticle("js:test_verticle", function(deploymentID, err) { 18 | 19 | Assert.assertNotNull(deploymentID); 20 | Assert.assertNull(err); 21 | 22 | vertx.eventBus().consumer("testComplete").handler(function(msg) { 23 | // Verticle will send a message if vertxStop is called 24 | assertEquals("foo", msg.body()); 25 | latch.countDown(); 26 | }); 27 | 28 | vertx.undeploy(deploymentID, function (v, err) { 29 | Assert.assertNull(v); 30 | Assert.assertNull(err); 31 | }); 32 | }); 33 | 34 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 35 | } 36 | 37 | function testFailureInStop() { 38 | 39 | var vertx = Vertx.vertx(); 40 | var latch = new CountDownLatch(1); 41 | vertx.deployVerticle("js:test_verticle_fail", function(deploymentID, err) { 42 | 43 | Assert.assertNotNull(deploymentID); 44 | Assert.assertNull(err); 45 | 46 | vertx.undeploy(deploymentID, function (v, err) { 47 | Assert.assertNull(v); 48 | Assert.assertNotNull(err); 49 | latch.countDown(); 50 | }); 51 | }); 52 | 53 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 54 | } 55 | 56 | function testStoppedOKIfNoVertxStop() { 57 | var vertx = Vertx.vertx(); 58 | var latch = new CountDownLatch(1); 59 | vertx.deployVerticle("js:test_verticle_no_vertxstop", function(deploymentID, err) { 60 | 61 | Assert.assertNotNull(deploymentID); 62 | Assert.assertNull(err); 63 | 64 | vertx.undeploy(deploymentID, function (v, err) { 65 | Assert.assertNull(v); 66 | Assert.assertNull(err); 67 | latch.countDown(); 68 | }); 69 | }); 70 | 71 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 72 | } 73 | 74 | function testDeployMultipleInstances() { 75 | var vertx = Vertx.vertx(); 76 | var latch = new CountDownLatch(1); 77 | var numInstances = 3; 78 | var count = 0; 79 | var tooMany = false; 80 | vertx.eventBus().consumer("fooaddress", function(msg) { 81 | count++; 82 | if (count > numInstances) { 83 | tooMany = true; 84 | } 85 | if (count == numInstances) { 86 | // End on a timer to allow any further messages to arrive 87 | vertx.setTimer(500, function() { 88 | latch.countDown(); 89 | }); 90 | } 91 | }); 92 | vertx.deployVerticle("js:test_verticle_multiple", {instances: numInstances}); 93 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 94 | Assert.assertFalse(tooMany); 95 | } 96 | 97 | function testDeployMultipleInstancesWithVertxStart() { 98 | var vertx = Vertx.vertx(); 99 | var latch1 = new CountDownLatch(3); 100 | var latch2 = new CountDownLatch(3); 101 | vertx.eventBus().consumer("fooaddressinit", function(msg) { 102 | latch1.countDown(); 103 | }); 104 | vertx.eventBus().consumer("fooaddress", function(msg) { 105 | latch2.countDown(); 106 | }); 107 | vertx.deployVerticle("js:test_verticle_vertxstart", {instances: 3}); 108 | Assert.assertTrue(latch1.await(2, TimeUnit.MINUTES)); 109 | Assert.assertTrue(latch2.await(2, TimeUnit.MINUTES)); 110 | } 111 | 112 | function testErrorInVerticle() { 113 | var vertx = Vertx.vertx(); 114 | var latch = new CountDownLatch(1); 115 | vertx.deployVerticle("js:brokenmodule_typeerror", function(depID, err) { 116 | Assert.assertNull(depID); 117 | Assert.assertNotNull(err); 118 | if (err.message.equals("TypeError: 234 has no such function \"substr\" in src/test/resources/brokenmodule_typeerror.js at line number 6")) { 119 | // Ok 120 | } else if (err.message.equals("TypeError: num.substr is not a function in src/test/resources/brokenmodule_typeerror.js at line number 6")) { 121 | // Ok 122 | } else { 123 | Assert.fail("Invalid error message " + err.message); 124 | } 125 | assertEquals("src/test/resources/brokenmodule_typeerror.js", err.fileName); 126 | assertEquals(6, err.lineNumber); 127 | 128 | latch.countDown(); 129 | }); 130 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 131 | } 132 | 133 | function testSyntaxErrorInVerticle() { 134 | var vertx = Vertx.vertx(); 135 | var latch = new CountDownLatch(1); 136 | vertx.deployVerticle("js:brokenmodule_syntaxerror", function(depID, err) { 137 | 138 | Assert.assertNull(depID); 139 | Assert.assertNotNull(err); 140 | 141 | // FIXME - currently broken- Nashorn issue 142 | //Assert.assertTrue(err.message.startsWith("SyntaxError: 234 has no such function \"substr\" in brokenmodule_typeerror.js at line number 6")); 143 | //assertEquals("brokenmodule_syntaxerror.js", err.fileName); 144 | //assertEquals(5, err.lineNumber, 0); 145 | 146 | latch.countDown(); 147 | }); 148 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 149 | } 150 | 151 | function testGlobals() { 152 | var vertx = Vertx.vertx(); 153 | var latch = new CountDownLatch(1); 154 | vertx.deployVerticle("js:test_verticle", function(deploymentID, err) { 155 | 156 | Assert.assertNotNull(deploymentID); 157 | Assert.assertNull(err); 158 | latch.countDown(); 159 | }); 160 | 161 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 162 | } 163 | 164 | function testVerticleGlobal() { 165 | var vertx = Vertx.vertx(); 166 | var latch = new CountDownLatch(1); 167 | vertx.deployVerticle("js:test_verticle_global", function(deploymentID, err) { 168 | 169 | // This should fail to deploy 170 | Assert.assertNull(deploymentID); 171 | Assert.assertNotNull(err); 172 | Assert.assertTrue(err.message.equals("ReferenceError: \"x\" is not defined in src/test/resources/test_verticle_global.js at line number 6")); 173 | latch.countDown(); 174 | }); 175 | 176 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 177 | } 178 | 179 | if (typeof this[testName] === 'undefined') { 180 | throw "No such test: " + testName; 181 | } 182 | 183 | this[testName](); 184 | -------------------------------------------------------------------------------- /vertx-lang-js/src/test/resources/require_test.js: -------------------------------------------------------------------------------- 1 | var Assert = org.junit.Assert; 2 | 3 | var testUtils = require("test_utils"); 4 | var assertEquals = testUtils.assertEquals; 5 | 6 | function testRequireNoExtension() { 7 | var testMod = require("test_mod"); 8 | assertEquals("hello", testMod); 9 | } 10 | 11 | function testRequireWithExtension() { 12 | var testMod = require("test_mod.js"); 13 | assertEquals("hello", testMod); 14 | } 15 | 16 | function testRequireInDirectoryNoExtension() { 17 | var testMod = require("somedir/test_mod2"); 18 | assertEquals("socks", testMod); 19 | } 20 | 21 | function testRequireInDirectoryWithExtension() { 22 | var testMod = require("somedir/test_mod2.js"); 23 | assertEquals("socks", testMod); 24 | } 25 | 26 | function testRequireRelative() { 27 | var testMod = require("somedir/../somedir/./test_mod3"); 28 | assertEquals("socks", testMod); 29 | } 30 | 31 | function testRequireNotFound() { 32 | try { 33 | require("nosuchmodule"); 34 | } catch (e) { 35 | assertEquals("Cannot find module nosuchmodule", e.message); 36 | } 37 | } 38 | 39 | function testBrokenModuleSyntaxError() { 40 | try { 41 | require("brokenmodule_syntaxerror"); 42 | Assert.fail(); 43 | } catch (e) { 44 | // FIXME - Nashorn issue where syntax error is not reported properly from line in eval. 45 | // So we just have to log the error to stderr in npm-jvm.js for now 46 | //Assert.assertTrue(e.message.contains("brokenmodule_syntaxerror.js@0:5:2 Expected ; but found ar")); 47 | //assertEquals("brokenmodule_syntaxerror.js", e.fileName); 48 | //assertEquals(5, e.lineNumber, 0); 49 | Assert.assertTrue(e instanceof SyntaxError); 50 | } 51 | } 52 | 53 | function testBrokenModuleTypeErrorInMainBody() { 54 | try { 55 | var blah = require("brokenmodule_typeerror"); 56 | Assert.fail(); 57 | } catch (e) { 58 | if (e.message.startsWith("234 has no such function \"substr\"")) { 59 | // Ok 60 | } else if (e.message.equals("num.substr is not a function")) { 61 | // Ok 62 | } else { 63 | Assert.fail("Unexpected error message " + e.message); 64 | } 65 | Assert.assertTrue(e.fileName.contains("brokenmodule_typeerror.js")); 66 | assertEquals(6, e.lineNumber); 67 | Assert.assertTrue(e instanceof TypeError); 68 | } 69 | } 70 | 71 | function testBrokenModuleTypeErrorInFunction() { 72 | try { 73 | var blah = require("brokenmodule_typeerror2"); 74 | blah(); 75 | Assert.fail(); 76 | } catch (e) { 77 | if (e.message.startsWith("234 has no such function \"substr\"")) { 78 | // Ok 79 | } else if (e.message.equals("num.substr is not a function")) { 80 | // Ok 81 | } else { 82 | Assert.fail("Unexpected error message " + e.message); 83 | } 84 | assertEquals(9, e.lineNumber); 85 | Assert.assertTrue(e instanceof TypeError); 86 | } 87 | } 88 | 89 | function testTopLevelIsolated() { 90 | var testMod = require("test_mod"); 91 | Assert.assertTrue(typeof someGlobal === 'undefined'); 92 | } 93 | 94 | function testCachedRequires() { 95 | var testMod1 = require("test_mod_cached_require"); 96 | var testMod2 = require("test_mod_cached_require"); 97 | var testMod3 = require("test_mod_cached_require"); 98 | Assert.assertTrue(testMod1 === testMod2); 99 | Assert.assertTrue(testMod2 === testMod3); 100 | } 101 | 102 | function testRequireNPMModule() { 103 | var testMod1 = require("src/test/npm/testmod1"); 104 | assertEquals("hello from testmod1", testMod1); 105 | } 106 | 107 | function testRequireNPMModuleUsingNodePath() { 108 | var testMod1 = require("testmod1"); 109 | assertEquals("hello from testmod1", testMod1); 110 | } 111 | 112 | function testRequireNPMModuleUsingClassPath() { 113 | var my_npm_verticle = require("my_npm_module.js"); 114 | assertEquals("Hello vertx", my_npm_verticle); 115 | } 116 | 117 | /** 118 | * Test multiple verticle deployment with the Verticle requesting a require. 119 | * 120 | * Testing for issue where the result of the require is not the expected object when multiple verticles are 121 | * initiated concurrently. 122 | * 123 | * This issue should have been addressed by the introduction of per verticle contexts. 124 | * 125 | * The test defines two additional files: test_multiple_concurrent_requires_required.js and test_multiple_concurrent_requires_verticle.js. 126 | * 127 | * The first (...required.js) is a simple CommonJS pattern module which exports a property to callers. 128 | * The second (...verticle.js) is a simple verticle that requires the above file and reports back whether the property is there via the event bus. 129 | */ 130 | function testMultipleConcurrentRequires() { 131 | 132 | // Use an embedded Vert.x 133 | var Vertx = require("vertx-js/vertx"); 134 | 135 | var console = require("vertx-js/util/console"); 136 | 137 | // Count down latch so we can wait for the deployment to finish 138 | var CountDownLatch = java.util.concurrent.CountDownLatch; 139 | var TimeUnit = java.util.concurrent.TimeUnit; 140 | 141 | // The number of instances to start. Issue occurs at a much lower number of instances, but always seems to happen with this many. 142 | var numInstances = 20; 143 | 144 | var vertx = Vertx.vertx(); 145 | var latch = new CountDownLatch(1); 146 | 147 | var count = 0; 148 | var tooMany = false; 149 | var requireFailedCount = 0; 150 | var requireOKCount = 0; 151 | 152 | vertx.eventBus().consumer("test_multiple_concurrent_requires", function( msg ) { 153 | count++; 154 | 155 | if (msg.body() == 'ok') { 156 | requireOKCount++; 157 | } else { 158 | requireFailedCount++; 159 | } 160 | 161 | if (count > numInstances) { 162 | tooMany = true; 163 | } 164 | if (count == numInstances) { 165 | // End on a timer to allow any further messages to arrive 166 | vertx.setTimer(500, function() { 167 | latch.countDown(); 168 | }); 169 | } 170 | }); 171 | 172 | // Deploy a number of instances 173 | vertx.deployVerticle("js:test_multiple_concurrent_requires_verticle", {instances: numInstances}); 174 | Assert.assertTrue(latch.await(2, TimeUnit.MINUTES)); 175 | Assert.assertFalse(tooMany); 176 | 177 | Assert.assertTrue( "Failure count must be 0", requireFailedCount == 0); 178 | } 179 | 180 | if (typeof this[testName] === 'undefined') { 181 | throw "No such test: " + testName; 182 | } 183 | 184 | this[testName](); 185 | --------------------------------------------------------------------------------