RosaeNLG Java Wrapper
Install
As a maven dependency:
<dependency>
<groupId>org.rosaenlg</groupId>
<artifactId>java-wrapper</artifactId>
<version>1.4.1</version> <!-- put the proper version here -->
</dependency>
Usage
-
Create a
RosaeContext
object. This will load the proper RosaeNLG lib for the required language and compile the template. ARosaeContext
object can be created from a JSON package or from classic.pug
files. -
Use this RosaeContext to render your templates with
render
. -
You can also generate a JavaScript function for client side rendering using
getCompiledClient()
.
See JavaDoc.
Creating a RosaeContext
object is quite long, but you can reuse it as many times as you want on the same template with different input data.
Example
In a chanson.json
file:
p
| il #[+verb(getAnonMS(), {verb: 'chanter', tense:'FUTUR'} )]
| "#{chanson.nom}"
| de #{chanson.auteur}
CompileOptions compileOpts = new CompileOptions();
compileOpts.setLanguage("fr_FR");
final RosaeContext rc = new RosaeContext(
"chanson.pug",
new File("test-templates-repo"),
compileOpts);
JSONObject renderOpts = new JSONObject();
renderOpts.put("language", "fr_FR");
JSONObject chanson = new JSONObject();
chanson.put("nom", "Non, je ne regrette rien");
chanson.put("auteur", "Édith Piaf");
renderOpts.put("chanson", chanson);
String rendered = rc.render(renderOpts.toString());
You should get Il chantera "Non, je ne regrette rien" d’Édith Piaf.
Exceptions
Exceptions can arise both at compilation time and at runtime. With Graal JavaScript exceptions are not automatically transformed in Java exceptions.
The wrapper:
-
catches the js exceptions
-
throws a basic Java Exception with the js exception content in its message
Options and input data
Basically, RosaeNLG requires:
-
to compile: templates and compile options (mainly language)
-
to render: data
Templates
Templates are given in the constructor:
-
as a string for simple templates (with no inclusions of other templates)
-
as a path to
.pug
files; the files (main template + includes) are read before being given to Graal, as in Graal RosaeNLG has no access to the filesystem -
as a JSON package containing everything
Security
RosaeNLG js lib is run inside a Graal VM. The Graal VM brings some security: an embedder writes an application server (the host application) that runs JavaScript guest applications from a less trusted source, knowing that allowAllAccess
is not set using RosaeNLG: the js lib (and the templates) cannot access the JVM internals.
Pug templates cannot make any require
so there is no access to fs
(node.js filesystem lib) nor http
.