Possible to use JJS to run Java code in Javascript?

Enonic version: 6.0.0 RC2
OS: OSX 10.10.5

Like the title says, is it possible to use JJS to run Java code directly in a controller js? This should be possible to do with Nashorn.

I’ve tried putting #!/usr/bin/env jjs at the top of a controller script to enable this, but get a lot of error messages:

Expected an operand but found error (function (app, log, require, resolve, __) { var exports = {}; var module = {}; module.id = __.script.toString(); Object.defineProperty(module, ‘exports’, { get: function () { return exports; }, set: function (value) { exports = value; } }); #!/usr/bin/env jjs ^ (com.enonic.xp.resource.ResourceProblemException)

Yes, it’s possible to execute Java from our Javascript controllers. It’s not possible to put a shebang (#!) like you put on top here, but it’s done in a different way…

Right now it’s no documentation for this, but will be added very soon. In the mean time you can look at some “libs” that we have created here: https://github.com/enonic/xp

Especially look at the Java integration in one of our libs here: https://github.com/enonic/xp/blob/master/modules/lib-content/src/main/resources/site/lib/xp/content.js

Hope this helps.

BR,
Sten Roger

Thanks for that, very useful. Should definitively be included in the docs :wink:

I ended up using Java.type() to get the Java-stuff I needed instead.


For you other people reading this (maybe you are a noob on Nashorn like myself), it was as simple as:

var HttpClient = Java.type('org.apache.commons.httpclient.HttpClient');
var GetMethod = Java.type('org.apache.commons.httpclient.methods.GetMethod');

var httpclient = new HttpClient();
var method = new GetMethod("http://www.example.com");

var statusCode = httpclient.executeMethod(method);
var responseBody = method.getResponseBodyAsString();

The classpath had to be included in build.gradle:

dependencies {
  include "commons-httpclient:commons-httpclient:3.1"
}

Cheers! :blush:

1 Like