spatialillusions / milsymbol

Military Symbols in JavaScript
www.spatialillusions.com/milsymbol
MIT License
547 stars 134 forks source link

Sample ScriptEngine to run milsymbol.js within Java #173

Closed aherreraGH closed 6 years ago

aherreraGH commented 6 years ago

Hello Mans,

I'm trying to figure out how to put this together within Java... Using the ScriptEngine is very new to me, and I'm at a loss on how to implement this. I found some simple examples to try, but couldn't find an example that runs something similar to what you have new ms.Symbol(...) and generates the results from that.

Do you have a simple working example I can use to follow along and see how it needs to be put together? Or even a link to a ScriptEngine example that matches up with what you have set up?

Thank you in advance.

spatialillusions commented 6 years ago

Hi,

I haven't used ScriptEngine by my self, but I know that others has got it working. You could try out something like this, but use SVG output instead of Canvas. IIRC that was the way they solved it.

https://stackoverflow.com/review/suggested-edits/17250369 But use SVG output instead of Canvas.

aherreraGH commented 6 years ago

Thank you, will check it out... I see that uses JavaFX + WebEngine. If I figure out how to make it work, I'll drop the code here for your review, and possibly share with others.

Thank you again!

aherreraGH commented 6 years ago

Here's what I ended up using:

Add in the script engine:

private static final ScriptEngineManager manager = new ScriptEngineManager();
private static final ScriptEngine engine = manager.getEngineByName("nashorn");

BufferedReader to get the JS contents:

bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/com/blah/blah/js/milsymbol.js")));
bufferedReader2 = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/com/blah/blah/js/milsymbol-init.js")));

Apparently, you can eval more than 1 JS file:

engine.eval(bufferedReader);
engine.eval(bufferedReader2);
invokeEngine = (Invocable) engine;

The init JS file shown above has just a simple function that calls your milsymbol.js correctly. The code below has the function I added inside of the init JS file "getSVGSymbol".

Then write to a file (in the application I'm plugging this code into, it needs to load the SVG from a directory - hopefully I can find some API that allows me to just have it render the thing right away):

SVGUtils.writeToSVG(new File(dirToSaveTo+"/"+name+".svg"), (invokeEngine.invokeFunction("getSVGSymbol", params)).toString());

And that's it. It worked well this way. Hope this helps others that need to use the ScriptEngine.