Skip to content

Commit

Permalink
Merge pull request eclipse-vertx#133 from nelsonsilva/commonjs
Browse files Browse the repository at this point in the history
Added suport for CommonJS modules
  • Loading branch information
purplefox committed May 11, 2012
2 parents 16473db + 361018a commit 96506dc
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 15 deletions.
3 changes: 3 additions & 0 deletions src/examples/javascript/commonjs/handler.js
@@ -0,0 +1,3 @@
module.exports = function(req) {
req.response.end("<html><body><h1>Hello from vert.x using CommonJS!</h1></body></html>");
};
8 changes: 8 additions & 0 deletions src/examples/javascript/commonjs/main.js
@@ -0,0 +1,8 @@
var Server, handler;

Server = require('./server');
handler = require('./handler');

server = new Server(8080, 'localhost');
server.use(handler);
server.start();
13 changes: 13 additions & 0 deletions src/examples/javascript/commonjs/server.js
@@ -0,0 +1,13 @@
vertx=require('vertx');

module.exports = function(port, host){
var server = vertx.createHttpServer();

this.use = function(handler){
server.requestHandler(handler);
};

this.start = function() {
server.listen(port, host);
};
};
76 changes: 74 additions & 2 deletions src/main/java/org/vertx/java/deploy/impl/rhino/RhinoVerticle.java
Expand Up @@ -18,16 +18,30 @@

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.commonjs.module.ModuleScript;
import org.mozilla.javascript.commonjs.module.Require;
import org.mozilla.javascript.commonjs.module.RequireBuilder;
import org.mozilla.javascript.commonjs.module.provider.ModuleSource;
import org.mozilla.javascript.commonjs.module.provider.SoftCachingModuleScriptProvider;
import org.mozilla.javascript.commonjs.module.provider.UrlModuleSourceProvider;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.logging.impl.LoggerFactory;
import org.vertx.java.deploy.Verticle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
* @author <a href="http://tfox.org">Tim Fox</a>
Expand Down Expand Up @@ -64,6 +78,62 @@ private static void addStandardObjectsToScope(ScriptableObject scope) {
ScriptableObject.putProperty(scope, "stderr", jsStderr);
}

// Extracted from Rhino1_7R3_RELEASE/toolsrc/org/mozilla/javascript/tools/shell/Global.java
public static Require installRequire(Context cx, ScriptableObject scope, List<String> modulePath, boolean sandboxed) {
RequireBuilder rb = new RequireBuilder();
rb.setSandboxed(sandboxed);
List<URI> uris = new ArrayList<URI>();
if (modulePath != null) {
for (String path : modulePath) {
try {
URI uri = new URI(path);
if (!uri.isAbsolute()) {
// call resolve("") to canonify the path
uri = new File(path).toURI().resolve("");
}
if (!uri.toString().endsWith("/")) {
// make sure URI always terminates with slash to
// avoid loading from unintended locations
uri = new URI(uri + "/");
}
uris.add(uri);
} catch (URISyntaxException usx) {
throw new RuntimeException(usx);
}
}
}
rb.setModuleScriptProvider(
new SoftCachingModuleScriptProvider(new UrlModuleSourceProvider(uris, null)){
@Override
public ModuleScript getModuleScript(Context cx, String moduleId, URI uri, Scriptable paths) throws Exception {
// Allow loading modules from <dir>/index.js
if(uri != null && new File(uri).isDirectory()){
uri = URI.create(moduleId + File.separator + "index.js");
}
return super.getModuleScript(cx, moduleId, uri, paths);
}
});
Require require = rb.createRequire(cx, scope);
require.install(scope);
return require;
}

private static Require installRequire(ClassLoader cl, Context cx, ScriptableObject scope){
List<String> modulePaths= new ArrayList<>();

// Add the classpath URLs
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url : urls){
modulePaths.add(url.getPath());
}

// Hack to add the javascript core library to the module path
String corePath = new File(cl.getResource("vertx.js").getPath()).getParent();
modulePaths.add(corePath);

return installRequire(cx, scope, modulePaths, false);
}

private static void loadScript(ClassLoader cl, Context cx, ScriptableObject scope, String scriptName) throws Exception {
InputStream is = cl.getResourceAsStream(scriptName);
if (is == null) {
Expand All @@ -83,14 +153,16 @@ public void start() throws Exception {
scope = cx.initStandardObjects();

addStandardObjectsToScope(scope);

scope.defineFunctionProperties(new String[] { "load" }, RhinoVerticle.class, ScriptableObject.DONTENUM);

// This is pretty ugly - we have to set some thread locals so we can get a reference to the scope and
// classloader in the load() method - this is because Rhino insists load() must be static
scopeThreadLocal.set(scope);
clThreadLocal.set(cl);

loadScript(cl, cx, scope, scriptName);
Require require = installRequire(cl, cx, scope);
require.requireMain(cx, scriptName);

try {
stopFunction = (Function)scope.get("vertxStop", scope);
Expand Down
33 changes: 20 additions & 13 deletions src/main/javascript/vertx.js
Expand Up @@ -14,16 +14,23 @@
* limitations under the License.
*/

load('core/buffer.js');
load('core/event_bus.js');
load('core/net.js');
load('core/http.js');
load('core/streams.js');
load('core/timers.js');
load('core/utils.js');
load('core/sockjs.js');
load('core/parse_tools.js');
load('core/shared_data.js');
load('core/filesystem.js');
load('core/deploy.js');
load('core/logger.js');
(function(){

load('core/buffer.js');
load('core/event_bus.js');
load('core/net.js');
load('core/http.js');
load('core/streams.js');
load('core/timers.js');
load('core/utils.js');
load('core/sockjs.js');
load('core/parse_tools.js');
load('core/shared_data.js');
load('core/filesystem.js');
load('core/deploy.js');
load('core/logger.js');

(this.module && module.exports)? module.exports = vertx : this.vertx = vertx;

})();

0 comments on commit 96506dc

Please sign in to comment.