The System namespace offers a general set of functions which is always available in the JavaScript scripting environment of VCF Automation. Sometimes it can be helpful to extend this set of functions to offer new possibilities that fit in seamlessly. This blog post shows an approach how to extend the system namespace.
Extend System Namespace
To extend the system namespace, simply define a function that begins with the prefix System and whose function name is separated from the prefix by a period. In the following example two functions are defined on this way, base64ToString and stringToBase64. The prefix of the function name is in both cases System, for example System.base64ToString. With this simple approach, the System namespace was extended to include these two functions.
Hint: The property
com.vmware.scripting.javascript.allow-native-object must be set to true in VCF Automation at System Settings > Configuration Properties to use the following example.
/**
* Decodes a base64 encoded string.<br>
*
* @function base64ToString
* @param {string} value - Text to decode from base64.
* @returns {string}
*/
System.base64ToString = function(value) {
if (typeof value === "undefined" || value === null) {
throw new Error("value argument can not be undefined or null");
}
const resultArr = java.util.Base64.getDecoder().decode(
java.lang.String(value).getBytes()
);
var result = "";
resultArr.forEach( function(charByte) {
result += String.fromCharCode(parseInt(charByte));
});
return String(result);
}
/**
* Encodes string to base64.<br>
*
* @function stringToBase64
* @param {string} value - Text to encode in base64.
* @returns {string}
*/
System.stringToBase64 = function(value) {
if (typeof value === "undefined" || value === null) {
throw new Error("value argument can not be undefined or null");
}
return String(
java.util.Base64.getEncoder().encodeToString(
java.lang.String(value).getBytes()
)
);
}
|
The source code is saved as a separate action in VCF Automation.
To use these extensions, simply call the action. This allows the additional functions to be used seamlessly, as if they had always been present in the namespace.
System.getModule("de.stschnell").extendSystemNamespace();
function main() {
const base64Str = System.stringToBase64("Hello World");
System.log(base64Str);
const str = System.base64ToString(base64Str);
System.log(str);
}
main();
|
Conclusion
Extending existing namespaces is not a problem with the approach shown here. Without creating new namespaces, the existing ones can be meaningfully supplemented and extended. And it is possible to add attributes on the same way.