The javascript accessor executes JavaScript language scripts.
It is based on Mozilla Rhino JavaScript
.
The operator specifies the resource to be executed as a program.
The script may either be a plain/text script or
may be encapsulated in an XML document with the script specified as the text of the root element.
When using XML it is strongly advisable to enclose your script inside a CDATA section, for example:
<script><![CDATA[ ...your script .. ]]></script>
The JavaScript program is compiled to Java bytecode with the maximum optimisation settings.
Script Context
When executed, each script is provided an instance
of the INKFConvenienceHelper
class as the local
variable context.
The context variable has two purposes.
It supports introspection of the request which initiated the script
and it allows sub-requests to be issued.
For more details see the NKF Reference Guide.
Once a response object is created:
response=context.createResponseFrom(...);
it will be returned via the context when the script exits.
Parameters
Parameters can be passed to a script using named arguments.
Argument values are available within the script through the
context
using the this:param URI address space convention.
For example if the javascript accessor is requested with...
active:javascript+operator@myscript.js+myargument@data.xml
The myargument parameter can be obtained inside the script
using the context and the argument URI "this:param:myargument".
context.source("this:param:myargument")
Classpath
A JavaScript script inherits the Java classpath of the execution context.
The order for locating a class is as
follows:
- The ext-script module
- The superstack back to the module where the javascript accessor was invoked
- The libraries and imports of the module originating the script execution request.
- The NetKernel core classes
- The Java VM classpath
A Java class can be imported for use in a Javascript script with an import statement:
importPackage(Packages.java.util.Random);
Javascript Libraries
Libraries of JavaScript (either methods or variables) can be loaded
from the execution context. using the
context.importLibrary(libURI)
method:
myLibraryURI = "libs/library1.js";
context.importLibrary( myLibraryURI);
Place this code prior to code that requires the library methods or variables - relative URIs are resolved
with respect to the current working URI.
Example
This example shows a JavaScript script performing an XSLT transformation,
logging the result and returning the result as the response:
//Create and issue XSLT request
sr=context.createSubRequest();
sr.setURI("active:xslt");
sr.addArgument("operand","data1.xml");
sr.addArgument("operator","style1.xsl");
rep=context.issueSubRequest(sr);
//Log result
sr=context.createSubRequest();
sr.setURI("active:log");
sr.addArgument("operand",rep);
context.issueSubRequest(sr);
//Create response, set metadata and exit
resp=context.createResponseFrom(rep);
resp.setMimeType("text/plain");
resp.setExpired();