Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

SlightlyLoony
Tera Contributor

find_real_file.pngRecently I helped someone troubleshoot a script problem that turned out to be a case of mistaken identity: the script's author thought she had a Java String instance, but in fact she had a JavaScript String instance — and that led to some badly broken code.

If "Huh?" or "Less gobbledegook, please!" is your reaction, you might want to read on...

The broken script looked like this:


var gr = new GlideRecord('cmdb_ci_computer');
gr.addQuery('name', 'ovrhf003');
gr.query();
gr.next();
var domain = gr.getValue('os_domain');
gs.log(domain.contains('ROCOCO'));

When run, this script generates a big, fat old "undefined". What gives?

The problem is that the string value returned by the gr.getValue('os_domain') invocation is a JavaScript String instance — and the JavaScript String class does not contain a .contains() method. That's a method from the Java String class. We troubleshot it with this logging code:

var gr = new GlideRecord('cmdb_ci_computer');
gr.addQuery('name', 'ovrhf003');
gr.query();
gr.next();
var domain = new Packages.java.lang.String(gr.getValue('os_domain'));
gs.log(typeof domain);

When we ran this, the log showed "string" — meaning that it was a JavaScript String instance. Fortunately, it's very easy to convert the JavaScript String to a Java String:

var gr = new GlideRecord('cmdb_ci_computer');
gr.addQuery('name', 'ovrhf003');
gr.query();
gr.next();
var domain = new Packages.java.lang.String(gr.getValue('os_domain'));
gs.log(domain.contains('ROCOCO'));

This code works fine. While this example is kind of silly (see below for a better alternative), it's a good example of something to keep in mind when you get results in a script that you can't otherwise explain. Maybe you've got a JavaScript class instance where you expected a Java class instance, or vice versa.

Here's an even better way to handle the problem above: this approach has the advantage of (a) working, and (b) avoiding conversion to a Java class instance:

var gr = new GlideRecord('cmdb_ci_computer');
gr.addQuery('name', 'ovrhf003');
gr.query();
gr.next();
var domain = gr.getValue('os_domain');
gs.log(domain.indexOf('ROCOCO') >= 0);


Today's photo is a close-up of the strings in a cactus stem. Pretty stringy, eh?