JavaScript in RPE – tips,tricks and best practices


Continuing the series on using JavaScript in RPE I’d like to cover today some best practices on using JavaScript and some code snippets I found useful.

Best practices

A good set of best practices is described here and there are many other Web sites that document such practices:

I would like to highlight some of them and add a few that I found useful in my day to day usage:

  • indent the code
  • always declare the variables even if JavaScript does not require that
  • use a consistent naming convention. camelCase is a popular naming convention but any convention is good as long it is consistently used
  • even if not required you should always end each line with a semicolon
  • catch exceptions when using Java code ( see below)

Catch Exceptions

When using Java inside your JavaScript the script code will stop abruptly if the Java code runs throws an exception. When a script fails it will stop the entire document generation so this is something to avoid.  You can do this by enclosing unsafe code in try/catch to provide fallback values or at least fail graciously with additional information on the error.

try
{
   var dateStr = "This is obviously not a date";
   var inputDateFormat  = new java.text.SimpleDateFormat( "yyyy-MM-dd");
   var date =inputDateFormat.parse(dateStr);

   // .. do something with the date. maybe convert it to a different format
}
catch(err)
{
   _sessionLogger.warn( "Error parsing dates: " + err);
}

This will result in  the following warning in RPE:

Error parsing dates: JavaException: java.text.ParseException: Unparseable date: “This is obviously not a date”

Useful scripts

Strings

1. Replace a string globally in a text using regular expressions

text = text.replace( /toreplace/g, "replacement");

With the above the toreplace string will be replaced everywhere in the text variable with the replacement string. The key to replace all the occurrences is the /g flag. Note that toreplace must not be enclosed in quotes ( “)

2. Eliminate multiple spaces

text = text.replace( /\s+/g, " ");

3. trim multi line text

text = text.replace(/^[^\S\r\n]*|[^\S\r\n]*$/gm,"")

Dates

1. get the current date using JavaScript Date

var d = new Date();
d.toString(); // or d.toUTCString();

2. get the current date and print it using Java Date for full control on how the date is rendered. See SimpleDateFormat in the Java documentation for how to build the patterns.

var dateFormat = new java.text.SimpleDateFormat( "MMMM dd, yyyy HH:mm.ss");
var date = new java.util.Date();
dateFormat.format( date);

3. parse a date using Java date

var dateStr = "2014-08-14 17:08";
var inputDateFormat  = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm");
var date =inputDateFormat.parse(dateStr);

Numbers

1. convert a string to a number

var x = "123";
var n = parseInt(x, 10)

The second argument for parseInt is the radix to use.parseInt is a lenient way of converting strings to numbers and has the advantage of being very obvious in the code but I typically use this shortcut

var x = "123";
var n = x*1

There are other ways of doing this conversion . See this for more information on how they work and the pitfalls of using them: https://coderwall.com/p/5tlhmw

2. print a float with the desired number of decimals

var n = 10/6;
var strN = n.toFixed( 3);
Advertisements

Author: Dragos Cojocari

Architect for Rational Publishing Engine

8 thoughts on “JavaScript in RPE – tips,tricks and best practices”

  1. question: Using DNG/RPE I create a map that has ID mapped to about field. I want to then dynamically configure resources to pull resource for whatever is stored in the resourceIdToAbout[identifier] for the ID I am currently on. Here is what is NOT working. won’t let me use replace method. Can you help? it knows what the resourceToAbout[identifier] is, because i have it printing out to check it. Any assistance would be appreciated.
    var str = resourceIdToAbout[identifier]
    str = str.replace(“resources/”, “publish/resources?resourceURI=”)

    1. When you close the script editor RPE will compile the JavaScript to verity it for errors. This happens in isolation of all the other scripts in RPE including the one that creates and populates the resourceidToAbout map. This means that resourceidToAbout[identifier] will return “undefined” at compile team hence the error that you see. You have 2 options:

      1. surround the code in try/catch as shown in the article

      2. “tell” the JavaScript compiler that a string is always expected there:
      var str = resourceIdToAbout[identifier] + “”;
      str = str.replace(“resources/”, “publish/resources?resourceURI=”);

  2. Attempted to map all resources in project to based on ID to the About URI, only to find out multiple URIs are returned (base artifact and those appearing in Modules), although the link data is only available when using the About URI in the resources for the project (resources?projectURI=). I did not see it in the modules?resourceURI= or resources?ModuleURI= XML files, and neither of those have a reference to the base artifact URI, so I was attempting to create a map of all resources for the project then go get the URI for the ID, since both have that connection. Maybe I’m going about it all wrong, but trying to print all requirements in the Module the user selects with the Primary Text and the links (Validated By) Title fields. Feel like I’m chasing my tail. Any suggestions, because I thought i could use the map to solve this lack of connection bewteen the schemas and must be missing something.

    1. If I understand what you write correctly the challenge here is the DNG data structure not the JavaScript. If we can understand how the data is linked ( and if the links you need exist in the XML data) then it will be possible to create that mapping.

      I’m not familiar enough with DNG schema details in order to visualize well your problem and the solution to it so I suggest that you create a post on the http://jazz.net forum, tag it with DNG/RPE and add the template you are working on. This way the RPE and DNG teams will be able to chime in ( along with other users).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s