Top Level library package (server-only).
Contains generally useful functions that don’t fit into the other categories. The Myna namespace is also contains several other objects and libraries
Myna.Database, Myna.DataManager, Myna.File, Myna.HttpConnection, Myna.JavaUtils, Myna.Ldap, Myna.Mail, Myna.Permissions, Myna.Profiler, Myna.Query, Myna.Table, Myna.Template, Myna.Thread, Myna.ValidationResult, Myna.WebService,
| Myna | Top Level library package (server-only). |
| Functions | |
| abort | Halts JavaScript execution, optionally showing a message or dumping an object |
| beanToObject | Attempts to convert a JavaBean in to JavaScript object |
| captureContent | executes a function and returns any content generated by that function |
| createSyncFunction | returns a thread-safe version of a javascript function |
| createUuid | Creates a Universally Unique Identifier |
| createByteArray | returns a java Byte array of the supplied size |
| createCharArray | returns a java Character array of the supplied size |
| dump | returns nested HTML table representing the supplied object |
| dumpText | returns ASCII tree representing the supplied object |
| executeShell | Executes a shell command/script |
| executeWinBatch | Executes a Windows batch file |
| formatError | returns an html formatted string representing the supplied exception. |
| freeMemory | attempts to free the specified amount of memory within the timeout, returning true if successful. |
| enumToArray | Converts a Java enumeration into a JavaScript Array. |
| getGeneralProperties | Returns the Java Properties object loaded from /WEB-INF/classes/general.properties |
| include | executes a .js, .sjs, or .ejs file in the current thread |
| includeDirectory | executes all .sjs files in the supplied directory, in the current thread |
| includeDirectoryOnce | executes all .sjs files in the supplied directory, in the current thread, if they have not been executed before in this request |
| includeText | Includes a text file in the current thread |
| includeOnce | Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, if that path has not already been loaded. |
| includeContent | Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, and returns the output instead of printing |
| includeTemplate | Includes a file as a Myna.XTemplate |
| loadProperties | loads a Java properties file and returns it as a JavaScript object |
| loadAppProperties | loads an application.sjs file and returns the parsed app object |
| lock | Gets an exclusive lock by name. |
| clusterLock | Gets an exclusive lock by name for the whole cluster. |
| log | logs a string to the general log table |
| logSync | A single threaded synchronous version of Myna.log |
| mapToObject | returns a Java Map as a JavaScript Object |
| normalizeError | analyzes an error object returns a “standard” error. |
| parseJavaStack | returns an array of strings representing each line of the Java stack in the supplied error object |
| parseJsStack | returns an array of strings representing each line of the javascript stack in the supplied error object |
| This is an alias for $res.print | |
| printDump | shortcut for $res.print(Myna.dump()) |
| println | shortcut for this.print(<text> + “<br>”) |
| printConsole | prints text to java.lang.System.out |
| sealObject | This seals a JavaScript object, preventing it from being modified. |
| saveProperties | Saves the supplied object as a Java Properties file |
| sleep | pauses execution of the current thread for time milliseconds |
| xmlToObject | returns an XML object as a plain JavaScript Object |
| xmlToPdf | Converts an xml/xhtml object into a PDF file |
| htmlToXhtml | Converts an HTML string into an XHTML string |
Myna.abort=function Myna_abort( label, value )
Halts JavaScript execution, optionally showing a message or dumping an object
| label | Optional If supplied by itself, this is simply out put to the browser. If value is supplied as well, this because the title for the dump. |
| value | Optional Value to dump |
void
Myna.beanToObject=function Myna_beanToObject( bean )
Attempts to convert a JavaBean in to JavaScript object
| bean | Java object to convert |
JavaScript Object
This function examines bean and looks for functions that start with “get” followed by at least one other character. These functions are executed and their values are returned as a Javascript object where the property names are the get functions minus the “get” and the following character lower cased. Functions that start with “is” are treated similarly, except the “is” is kept in the proerty name
*EXAMPLE*
this class...
public class PersonBean implements java.io.Serializable {
private name="bob";
private deceased=true;
...
public String getName() {
return this.name;
}
public boolean isDeceased() {
return this.deceased;
}
}
would become...
{
name:"bob",
isDeceased:true
}
Myna.captureContent=function Myna_captureContent( func, scope )
executes a function and returns any content generated by that function
| func | function to execute |
| scope | Optional, default true The scope in which to execute func |
content generated by func
Myna.createSyncFunction=function Myna_createSyncFunction( functionObject )
returns a thread-safe version of a javascript function
| functionObject | JavaScript Function object to synchronize |
a thread-safe version functionObject, similar to synchronized keyword for Java functions
Myna.createUuid=function Myna_createUuid()
Creates a Universally Unique Identifier
String UUID
A UUID is a 128 bit number represented as a HEX string that is expected to unique even when compared to numbers generated by other generators. Here is an example:
f005889f-2b8d-409c-a126-f01eb50846d4
Good uses for UUIDs are anything that needs to be uniquely identified such as :
Myna UUID’s are based on a cryptographically secure random number generator, and are therefore NOT sortable by time.
Myna.createByteArray=function Myna_createByteArray( size )
returns a java Byte array of the supplied size
When working with binary data or streams it is often necessary to pass a Byte array to java functions as a buffer. This function will create this buffer for you
Myna.createCharArray=function Myna_createCharArray( size )
returns a java Character array of the supplied size
When working with striong data or streams it is often necessary to pass a Character array to java functions as a buffer. This function will create this buffer for you
Myna.dump=function Myna_dump( obj, label, maxDepth )
returns nested HTML table representing the supplied object
| obj | Object to dump |
| label | Optional Caption for the dump table |
| maxDepth | Optional, default=4 Maximum depth of recursion. This is to protect against circular references and to speed performance. |
Nested HTML and (client-side) JavaScript table representing the supplied object
Myna.dumpText=function Myna_dump( obj, label, maxDepth )
returns ASCII tree representing the supplied object
| obj | Object to dump |
| label | Optional Caption for the dump table |
| maxDepth | Optional, default=4 Maximum depth of recursion. This is to protect against circular references and to speed performance. |
Myna.executeShell=function Myna_executeShell( shellCommand, script, waitForOutput )
Executes a shell command/script
| shellCommand | Command shell to execute such as “cmd”, “csh”, “bash”. Can include a platform specific path and arguments to the shell like “/bin/perl -I/usr/local/perl_includes” |
| script | String of commands to execute in the shell |
| waitForOutput | Optional, default=true If true, this function will wait for the script to complete and return a result object with stderr, stdout, and the exit code. If False returns empty result object immediately |
A JavaScript object that looks like this:
{
output:"here is the stdout",
errors:"here is the stderr",
exitCode:-1
}This function attempts to execute the supplied script in the supplied shell. This is obviously platform dependent, so you may want to consult $server.osName. It saves script to a tempfile and then executes shellCommand with the temp file name as the last parameter
var result =Myna.executeShell("bash",<ejs>
echo "began script at `date`"
du -sh "<%=new Myna.File("/").javaFile.getAbsolutePath()%>"
echo "finished script at `date`"
</ejs>)
if (result.exitCode == 0){
Myna.print("<pre>" +result.output + "</pre>");
} else {
Myna.print("<pre>" +result.errors + "</pre>");
}
Myna.executeWinBatch=function Myna_executeWinBatch( script, waitForOutput )
Executes a Windows batch file
| script | String of commands to execute in the shell |
| waitForOutput | Optional, default=true If true, this function will wait for the script to complete and return a result object with stderr, stdout, and the exit code. If False returns empty result object immediately |
A JavaScript object that looks like this:
{
output:"here is the stdout",
errors:"here is the stderr",
exitCode:-1
}This function attempts to execute the supplied script as a Windows batch file. This is obviously platform dependent, so you may want to consult $server.osName. It saves script to a tempfile and then executes that file at a windows batch file
See Also: executeShell
Myna.executeWinBatch("notepad.exe i:\\custom\\mpages\\applist.js")
Myna.formatError=function Myna_formatError( e )
returns an html formatted string representing the supplied exception.
| e | a caught exception |
Myna.freeMemory=function Myna_freeMemory( size, timeout )
attempts to free the specified amount of memory within the timeout, returning true if successful.
| size | number of bytes to free |
| timeout | Optional, default 0 timeout in miliseconds to wait for memory to become available; |
true if memory is available
if timeout is 0, or memory is currently avaialble, this function will return immediately. Otherwise this function will repeatedly call System.gc() to attempt to free memory until enough is available or the timeout is exceeded
$server.memMax, $server.memCurrent, $server.memAvailable, $server.memFree, $server.memUsed
Myna.enumToArray=function Myna_enumToArray( enumeration )
Converts a Java enumeration into a JavaScript Array.
| enumeration | Java enumeration to iterate over |
JS Array object
Myna.getGeneralProperties=function Myna_getGeneralProperties()
Returns the Java Properties object loaded from /WEB-INF/classes/general.properties
Myna.include=function Myna_include( path, scope )
executes a .js, .sjs, or .ejs file in the current thread
| path | MynaPath or Myna.File representing location of file |
| scope | Optional, default <$server.globalScope> This is the object that will be passed as the “this” object to the script. any “global” variables created in the script will be created on scope object instead. |
scope after execution
If the file extension is one of js, sjs, or ejs:
This function executes the the script at path against the supplied scope. This behavior is similar to the JavaScript “apply” function. The code in the file will be treated like the body of a function on scope.
Myna.includeDirectory=function Myna_includeDirectory( path, scope )
executes all .sjs files in the supplied directory, in the current thread
| path | MynaPath representing a directory |
| scope | Optional, default <$server.globalScope> This is the object that will be passed as the “this” object to the each script in path. Any “global” variables created in the script will be created on scope object instead. |
scope after execution
Myna.includeDirectoryOnce=function Myna_includeDirectory( path, scope )
executes all .sjs files in the supplied directory, in the current thread, if they have not been executed before in this request
| path | MynaPath representing a directory |
| scope | Optional, default <$server.globalScope> This is the object that will be passed as the “this” object to the each script in path. Any “global” variables created in the script will be created on scope object instead. |
scope after execution
Myna.includeText=function Myna_includeText( path )
Includes a text file in the current thread
| path | MynaPath repesenting location of file |
void
Myna.includeOnce=function Myna_includeOnce( path, scope )
Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, if that path has not already been loaded.
| path | MynaPath repesenting location of file |
| scope | Optional, default <$server.globalScope> This is the object that will be passed as the “this” object to the script |
scope after execution
This function will call include for this path only once in this request.
Myna.includeContent=function Myna_includeContent( path, scope, cacheOptions )
Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, and returns the output instead of printing
| path | MynaPath repesenting location of file |
| scope | Optional, default <$server.globalScope> This is the object that will be passed as the “this” object to the script |
| cacheOptions | Optional, default null If this is defined, then these options will be passed to a Myna.Cache instance for the results of this include |
content generated by the included file
Myna.includeTemplate=function Myna_includeTemplate( path, values )
Includes a file as a Myna.XTemplate
| path | MynaPath repesenting location of file |
| values | Optional, default {} An object representing the values to qapply to this template |
void
This function combines an Myna.XTemplate definition stored in a text file with a set of values and prints the result.
Myna.loadProperties=function Myna_loadProperties( filepath )
loads a Java properties file and returns it as a JavaScript object
| filepath | MynaPath of properties file |
JavaScript object of the Properties Map, as per Myna.mapToObject
Myna.loadAppProperties=function Myna_loadProperties( filepath )
loads an application.sjs file and returns the parsed app object
| filepath | MynaPath of application.sjs file |
var admin_props = Myna.loadAppProperties("/myna/administrator/application.sjs");
Myna.println(admin_props.appname);
Myna.lock=function Myna_getLock( name, timeout, func )
Gets an exclusive lock by name.
| name | name of the lock to acquire |
| timeout | time in seconds to wait to acquire a lock. If this is 0, the lock will only be acquired if no other thread is using it |
| func | function to execute inside the lock |
true if a lock was acquired and func was executed
If more than one thread calls lock() near the same time, the first call will get access and the other call will be placed in a FIFO queue until the first thread lock finishes. For this reason it is best to “return” from func as soon as possible. If your function throws an exception, its lock will be released. If timeout is exceeded while waiting for a lock, then Myna.lock will return false
// classic check-lock-check-update algorithm
// this is the most thread-safe way to create global resources
if (!$server.get("globalVar")){
Myna.lock("create globalVar",0,function(){
//second check in case another thread created globalVar
if (!$server.get("globalVar")){
$server.set("globalVar",{})
}
})
}
Myna.clusterLock=function Myna_getLock( name, timeout, func )
Gets an exclusive lock by name for the whole cluster.
| name | name of the lock to acquire |
| timeout | time in seconds to wait to acquire a lock. If this is 0, the lock will only be acquired if no other thread is using it |
| func | function to execute inside the lock |
true if a lock was acquired and func was executed
If more than one thread calls lock() near the same time, the first call will get access and the other call will be placed in a FIFO queue until the first thread calls release() on the returned lock object. For this reason it is best to “return” from func as soon as possible. If your function throws an exception, its lock will be released. If timeout is exceeded while waiting for a lock, then Myna.clusterLock will return false
//getting a cluster-wide lock on an DB operation
var success=Myna.clusterLock("Update Employees",10,function(){
new Myna.Query(...)
}
Myna.log=function Myna_log( type, label, detail, app_name )
logs a string to the general log table
| type | Any short text value representing the type of log, such as DEBUG, INFO, ERROR, WARN, PROFILE, etc. This value is forced upper case |
| label | As short single-line text description of the log |
| detail | Optional, default null an HTML description of the log |
| app_name | Optional, default $application.appName A short text value representing the application that generated the log. This value is forced lower case |
This function logs to the myna_log_general table in the myna_log datasource. If you run multiple instances of Myna, it may be helpful to point the myna_log datasource of each instance to the same database. You Can view the logs through the Myna Adminstrator
Normally Myna.log attempts to perform logging in a low priority asynchronous thread. If Myna.log is called from within a Myna.Thread instance, however, it will not spawn a separate thread for logging. This prevents recursive thread spawning for logging. For example if you need to call Myna.dump on a large object, you may get better performance by dumping in a separate thread:
//slow way:
Myna.log("debug","Dump of myHugeQuery",Myna.dump(myHugeQuery));
//faster way (releases the current thread immediately)
new Myna.Thread(function(myHugeQuery){
Myna.log("debug","Dump of myHugeQuery",Myna.dump(myHugeQuery));
},[myHugeQuery],-90)
Myna.logSync=function Myna_logSync( type, label, detail, app_name )
A single threaded synchronous version of Myna.log
See Myna.log for parameters and detail
Myna.mapToObject=function Myna_mapToObject( map )
returns a Java Map as a JavaScript Object
| map | Java Map (or subclass/implementation) |
a Java Map as a JavaScript Object
This function loops through all of the entries in the map and creates a property on the returned object for each key and sets it equal to the entry’s value.
Myna.normalizeError=function Myna_normalizeError( e )
analyzes an error object returns a “standard” error.
| e | a caught exception |
| message | Short error message |
| file | File containing the error |
| line | Line number of the error |
| javaStack | return from parseJavaStack |
| jsStack | return from parseJsStack |
Myna.parseJavaStack=function Myna_parseJavaStack( e )
returns an array of strings representing each line of the Java stack in the supplied error object
| e | a caught exception |
This function calls Java’s internal stacktrace function and splits the result by line
Myna.parseJsStack=function Myna_parseJsStack( e )
returns an array of strings representing each line of the javascript stack in the supplied error object
| e | a caught exception |
This function calls Rhino’s internal stacktrace function and splits the result by line
Myna.print=function Myna_print( string )
This is an alias for $res.print
| string | string to append to the output buffer |
void
Myna.printDump=function Myna_printDump( obj, label, maxDepth )
shortcut for $res.print(Myna.dump())
| obj | Object to dump |
| label | Optional Caption for the dump table |
| maxDepth | Optional, default=4 Maximum depth of recursion. This is to protect against circular references and to speed performance. |
void
Myna.println=function Myna_println( text )
shortcut for this.print(<text> + “<br>”)
| text | text to print |
void
Myna.printConsole=function( header, text )
prints text to java.lang.System.out
| header | Text label to print first, including timestamp. If text is omitted then this is assumed to be the text and will be printed without a header |
| text | If provided this will be printed after the header |
Myna.sealObject=function Myna_sealObject( obj )
This seals a JavaScript object, preventing it from being modified.
| obj | JavaScript Object to seal |
Myna.saveProperties=function Myna_saveProperties( object, filepath )
Saves the supplied object as a Java Properties file
| object | A Java or JavaScript Object |
| filepath | MynaPath of destination file |
void
This function loops over the keys of object, and saves each non-function property and it’s value as a Java properties file.
<Myna.getKeys>
Myna.sleep=function Myna_sleep( time )
pauses execution of the current thread for time milliseconds
| time | time in miliseconds pause execution; |
Myna.xmlToObject=function xmlToObject( xml )
returns an XML object as a plain JavaScript Object
| xml | XML object |
This function recursively loops through all of the nodes in xml and returns an Object representing its structure. Since this removes all the advantages of XML objects, it is best used only for debugging.
var xml =
<topnode>
<list>
<thing type="color">
red
</thing>
<thing type="emotion">
twiterpated
</thing>
</list>
</topnode>;
Myna.println(
Myna.xmlToObject(
xml
).toJson()
)
//prints:
{
"attributes":{},
"children":[{
"attributes":{},
"children":[{
"attributes":{
"type":"color"
},
"children":[],
"name":"thing",
"namespace":"",
"value":"red"
},{
"attributes":{
"type":"emotion"
},
"children":[],
"name":"thing",
"namespace":"",
"value":"twiterpated"
}],
"name":"list",
"namespace":"",
"value":null
}],
"name":"topnode",
"namespace":"",
"value":null
}
Myna.xmlToPdf= function( input, output, baseUrl )
Converts an xml/xhtml object into a PDF file
| input | Input XML. See Input Types below |
| output | optional, default null Output location. See Output Types below |
| baseUrl | Optional, default null Only necessary for input types that don’t include a path, but do refer to images or css via relative paths. Input Types: |
This function uses Flying Saucer (xhtmlrenderer) to convert XML/XHTML content, resolving embedded stylesheets and images.
Flying Saucer understands most CSS 2.1 definitions.
For XHTML, STYLE tags need to be in the HEAD section. External stylesheets need to be in a LINK tag in the HEAD section
For raw XML, a <?xml-stylesheet href=’’ type=’text/css’?> definition is necessary
//Transform any page to a PDF (assuming it is valid XHTML)
//at the bottom of a page
...
if ($req.data.asPDF=="true"){
$res.printBinary(Myna.xmlToPdf($res.clear()),"application/pdf","WebPage.pdf");
}
Myna.htmlToXhtml =function( html, isFragment )
Converts an HTML string into an XHTML string
| html | HTML string. Can be a whole document or a fragment |
| isFragment | optional, default false set to true to treat html as a fragment and not create missing HTML and BODY tags |
HTML allows a lot of sloppiness that is not valid in XHTML. Start tags with no end tag, mis-matched case, missing parent tags like body and HTML. Also, to properly display XHTML in browsers, it is necessary to both escape SCRIPT and STYLE tag contents in CDATA tags, but also comment those CDATA sections.
This function takes an HTML string, and attempts to transform it into valid XHTML. Missing end tags are guessed and case is normalized. SCRIPT and STYLE sections are escaped properly, and well-formed, indented XHTML is returned.
The returned XHTML string will not include a ?xml? or DOCTYPE header. If you want those things, you will need to prepend them yourself.
Halts JavaScript execution, optionally showing a message or dumping an object
Myna.abort=function Myna_abort( label, value )
Attempts to convert a JavaBean in to JavaScript object
Myna.beanToObject=function Myna_beanToObject( bean )
executes a function and returns any content generated by that function
Myna.captureContent=function Myna_captureContent( func, scope )
returns a thread-safe version of a javascript function
Myna.createSyncFunction=function Myna_createSyncFunction( functionObject )
Creates a Universally Unique Identifier
Myna.createUuid=function Myna_createUuid()
returns a java Byte array of the supplied size
Myna.createByteArray=function Myna_createByteArray( size )
returns a java Character array of the supplied size
Myna.createCharArray=function Myna_createCharArray( size )
returns nested HTML table representing the supplied object
Myna.dump=function Myna_dump( obj, label, maxDepth )
returns ASCII tree representing the supplied object
Myna.dumpText=function Myna_dump( obj, label, maxDepth )
Executes a shell command/script
Myna.executeShell=function Myna_executeShell( shellCommand, script, waitForOutput )
Executes a Windows batch file
Myna.executeWinBatch=function Myna_executeWinBatch( script, waitForOutput )
returns an html formatted string representing the supplied exception.
Myna.formatError=function Myna_formatError( e )
attempts to free the specified amount of memory within the timeout, returning true if successful.
Myna.freeMemory=function Myna_freeMemory( size, timeout )
Converts a Java enumeration into a JavaScript Array.
Myna.enumToArray=function Myna_enumToArray( enumeration )
Returns the Java Properties object loaded from /WEB-INF/classes/general.properties
Myna.getGeneralProperties=function Myna_getGeneralProperties()
executes a .js, .sjs, or .ejs file in the current thread
Myna.include=function Myna_include( path, scope )
executes all .sjs files in the supplied directory, in the current thread
Myna.includeDirectory=function Myna_includeDirectory( path, scope )
executes all .sjs files in the supplied directory, in the current thread, if they have not been executed before in this request
Myna.includeDirectoryOnce=function Myna_includeDirectory( path, scope )
Includes a text file in the current thread
Myna.includeText=function Myna_includeText( path )
Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, if that path has not already been loaded.
Myna.includeOnce=function Myna_includeOnce( path, scope )
Includes a text file or executes a .js, .sjs, or .ejs file in the current thread, and returns the output instead of printing
Myna.includeContent=function Myna_includeContent( path, scope, cacheOptions )
Includes a file as a Myna.XTemplate
Myna.includeTemplate=function Myna_includeTemplate( path, values )
loads a Java properties file and returns it as a JavaScript object
Myna.loadProperties=function Myna_loadProperties( filepath )
loads an application.sjs file and returns the parsed app object
Myna.loadAppProperties=function Myna_loadProperties( filepath )
Gets an exclusive lock by name.
Myna.lock=function Myna_getLock( name, timeout, func )
Gets an exclusive lock by name for the whole cluster.
Myna.clusterLock=function Myna_getLock( name, timeout, func )
logs a string to the general log table
Myna.log=function Myna_log( type, label, detail, app_name )
A single threaded synchronous version of Myna.log
Myna.logSync=function Myna_logSync( type, label, detail, app_name )
returns a Java Map as a JavaScript Object
Myna.mapToObject=function Myna_mapToObject( map )
analyzes an error object returns a “standard” error.
Myna.normalizeError=function Myna_normalizeError( e )
returns an array of strings representing each line of the Java stack in the supplied error object
Myna.parseJavaStack=function Myna_parseJavaStack( e )
returns an array of strings representing each line of the javascript stack in the supplied error object
Myna.parseJsStack=function Myna_parseJsStack( e )
This is an alias for $res.print
Myna.print=function Myna_print( string )
Appends content to the response buffer.
print:function ( text )
shortcut for $res.print(Myna.dump())
Myna.printDump=function Myna_printDump( obj, label, maxDepth )
shortcut for this.print(text + “br”)
Myna.println=function Myna_println( text )
prints text to java.lang.System.out
Myna.printConsole=function( header, text )
This seals a JavaScript object, preventing it from being modified.
Myna.sealObject=function Myna_sealObject( obj )
Saves the supplied object as a Java Properties file
Myna.saveProperties=function Myna_saveProperties( object, filepath )
pauses execution of the current thread for time milliseconds
Myna.sleep=function Myna_sleep( time )
returns an XML object as a plain JavaScript Object
Myna.xmlToObject=function xmlToObject( xml )
Converts an xml/xhtml object into a PDF file
Myna.xmlToPdf= function( input, output, baseUrl )
Converts an HTML string into an XHTML string
Myna.htmlToXhtml =function( html, isFragment )