JavaScript

JavaScript
lac31
As an application developer experienced in languages such as Java or C#, but new to JavaScript, you can explore the various elements of JavaScript that are relevant to specifying business logic in 
CA Live API Creator
.
In this article:
CA Live API Creator
and JavaScript
CA Live API Creator
 uses JavaScript as a well-known and popular language to:
  • Keep things agile. You can simplify operations by loading and executing JavaScript code from text files and databases, instead of compiling the code into class files.
  • Avoid the pitfalls of JavaScript, such as async programming and lack of code completion. A hurdle for many application developers arises out of browser-based usage, where synchronous operations (reading a file or a database) can block the browser.
    JavaScript introduces the concept of asynchronous calls, with callbacks to process actual results. The following code snippet is an example from Rowan Manning's blog:
    console.log('First');
    jQuery.get('page.html', function (data) {
      console.log("Second"); // <--- this happens last
    });
    console.log('Third');
    As Rowan points out, the result is "First", "Third", "Second". This result is because 
    get
     is asynchronous, so execution proceeds past the
     
    statement (to "Third"). "Second" executes later, only when the 
    get
     call completes
    .
    JavaScript is an un-typed language. Code such as 
    var theValue = "some string"
     can be convenient, but you lose some services such as code completion in an integrated development environment. This service depends on typing information. 
    CA Live API Creator
    retains this capability for system objects.
    For more information about viewing a JavaScript tutorial, see the W3Schools JavaScript tutorial.
  • Retain the use of existing software that is running in the Java virtual machine (JVM). This server-side JavaScript is interoperable with Java. You can instantiate Java objects in JavaScript. Your server-side code, such as events, provides asynchronous event handling.
  • Execute your JavaScript code in browsers and on servers using the Nashorn JavaScript engine. While initial JavaScript use was in the browser, it is now commonly accepted as a server language.
  • Support its data structure. JavaScript has a simple data structure notation. This data structure leads to its adoption as a data interchange format for RESTful APIs. The JavaScript Object Notation (JSON) class provides functions to convert strings to objects, for example:
    myData = {name: "first", address: "california"};
    myString = JSON.stringify(myData); // suitable for logging, send as API request/response data
    myData2 = JSON.parse(myString); // get API response into JavaScript data
CA Live API Creator
 uses JavaScript in the following contexts:
  • In the browser.
     Internally, API Creator navigates the Document Object Model (DOM) (fields in a browser form) and handles events using JavaScript.
  • To create servers.
     
    CA Live API Creator
     uses Node.js for database access. Node.js provides a single language that covers the browser and the server. This server-side implementation of JavaScript is flexible, but low-level and complex.
  • As a scripting language for command-line scripting and scripting inside a virtual machine (VM). 
    You can build command language commands using JavaScript, in particular in Node.js. The JavaScript code can access Java code inside the JVM, including data sharing. This access provides the interpreted/un-typed simplicity of JavaScript with Java. Common implementations include Rhino and Nashorn.
Reserved JavaScript Context Variables
Do not use reserved JavaScript context variables as variable names. For example, the following code snippet sets reserved JavaScript context variables as variable names:
 
var
row
= null;
var
oldRow
= null;
var
json
= null;
var
logicRequest
= null;
For a list of the reserved JavaScript context variables, see Quick Reference.
JavaScript Tooling
The following tooling is built around JavaScript:
  • Browser tools to debug JavaScript.
     Most browsers provide tools to debug JavaScript.
  • Node.js. 
    The following Node.js elements are useful to
    CA Live API Creator
    :
    • Node.js for command languages.
       Node packages can include information that makes their functionality available in command lines. The Admin command-line interface (CLI) uses the Node packages.
    • Node.js Node Package Manager (npm).
       Node.js has simplified installing packages with the conventions around npm.
JavaScript for Event Handling and Functions
API Creator employs JavaScript for event handling and functions. Most programmers have some familiarity with it. JavaScript's interpretive nature is suitable for no-compile/no-deploy API creation and provides the basic control flow and object access (for example, 
row.balance
) that is required. In the context of short event handlers, the un-typed nature of JavaScript is less of an issue. JavaScript provides features often not found for JavaScript coding, such as code completion for system objects.
CA Live API Creator
employs JavaScript as a server-side scripting language in the API Server JVM. Your JavaScript has access to other code running in the JVM. API Server provides the threading functions, eliminating async issues. You can write simple loops to process results, and they run in the expected (synchronous) order. The API Creator JavaScript code editor provides code completion services for row variables. API Creator knows the context of a logic event (for example, the event for
customer
) and can therefore provide the
customer
attributes in a list you can select from.
Use the JSON Object
In JavaScript, you can convert JavaScript values to and from their JSON string representation by invoking the following JSON object functions:
stringify(<value>) parse(<JSON string>)
These functions do not support
CA Live API Creator
-specific objects, such as
row
and 
oldRow
, or other custom Java objects as arguments.
Example:
Consider a formula rule that has the
row
object in its JavaScript scope. You can convert the JavaScript value to a JSON string representation using the following code:
var stringifiedRow = JSON.
stringify(row)
; // stringifiedRow will always have the value '{}'
Instantiate JavaScript Objects
You can instantiate objects in JavaScript using the
new
operator. This usage is restricted to creating instances of user-defined JavaScript object types or of one of the built-in object types:
var variable-name = 
new
 constructor[([arguments])]
For example, instantiate a String type using the following syntax:
var variable-name = 
new
 String(“Your String here”);
Instantiate Java Objects Inside JavaScript
You can add Java libraries to your API by adding them to your
classpath
. Your JavaScript code can access the Java classes that are defined in your Java libraries.
For more information about how to use Java JAR files in your APIs, see Logic Libraries.
Follow these steps:
  1. Access the 
    Class
     object from the Java libraries in the Java code using the following syntax: 
    var ClassObject = Java.type(“<full name of the Java class>”);
    Example:
    The following code snippet accesses the 
    org.bar.Foo
     Java class and uses the 
    Class
     object to call the 
    staticMethodOfFoo
     static method that is declared inside the 
    org.bar.Foo
     class:
    var Foo = Java.type(“org.bar.Foo”);
    Foo.staticMethodOfFoo(); 
  2. Instantiate the 
    Class
     object using the
    new
    operator.
    Example:
    The following code snippet instantiates the 
    org.bar.Foo
     class in your JavaScript code and includes a non-parameterized constructor:
    var fooObject = new Foo(); 
    // Method calls.
    fooObject.instanceMethodOfFoo();
    Example:
    The following code snippet instantiates the 
    org.bar.Foo
     class in your JavaScript code and includes a parameterized constructor:
    var fooObject = new Foo(<parameter>); 
    // Method calls.
    fooObject.instanceMethodOfFoo();
The Java object is instantiated inside JavaScript.
 
Looping Examples
You can use the following code snippets to see how to use 
for...each
 in JavaScript code in
CA Live API Creator
.
for...each Loop Example
The following code snippet prints each array element for each 
(variable in object) {statement}
:
// for each (variable in object) { statement }
// print each array element
var arr = [ "hello", "world" ];
for each (a in arr) {
  print(a)
}
for...each Java Arrays Example
The following code snippet creates a ten-element
int
array, assigns squares, and prints values for each array element:
var JArray = Java.type("int[]");
// create 10 element int array
var arr = new JArray(10);
// assign squares
for (i in arr) {
  arr[i] = i*i;
}
// print values of each array element
for each (i in arr) {
  print(i);
for...each Java Map Example
The following code snippet prints all Java System property names and value pairs and prints all environment variables with values:
var System = Java.type("java.lang.System")
// print all Java System property name, value pairs
for each (p in System.properties.entrySet()) {
  print(p.key, "=", p.value)
}
// print all environment variables with values
for each (e in System.env.entrySet()) {
  print(e.key, "=", e.value)
}
You can loop through related data using the following construct:
var worksForEmps = row.EmpsList; // get emps in dept row
for each (var eachEmp in worksForEmps) {
logicContext.logDebug(eachEmp);
}