[SOLVED] JSR223 Javascript rule gives error after installation

Hi all,

So I finally made the decision to try and learn some javascript and move all of my DSL rules over to it.

I followed all the installation steps on this page: https://openhab-scripters.github.io/openhab-helper-libraries/Getting%20Started/Installation.html. But… it doesn’t work:slightly_frowning_face:. When i start openhab, it loads the delay rule correctly, but when the 30 seconds have passed, it give me this error in the logs:

Error during evaluation of script 'file:/etc/openhab2/automation/jsr223/javascript/personal/HelloWorld.js': java.lang.ClassNotFoundException: org.openhab.core.automation.util.RuleBuilder

What does this mean and what can I do about it?

Greetings,

jvank

Which version of OH are you using? I’ll go take a look at the script, which is working fine for me with S1621…

@jvank, I’m guessing you are using 2.4 or 2.5M1. When using the new rule engine, it is best to use a recent snapshot version of OH. If you don’t want to upgrade, replace lines 16 and 17 of core.utils.js…

var RuleBuilder 			= Java.type("org.openhab.core.automation.util.RuleBuilder");
var RuleManager 			= Java.type("org.openhab.core.automation.RuleManager");

… with this…

	try {
		var RuleBuilder = Java.type("org.openhab.core.automation.util.RuleBuilder");
	} catch(e) {
		var RuleBuilder = Java.type("org.eclipse.smarthome.automation.core.util.RuleBuilder");
	}
	
	try {
		var RuleManager = Java.type("org.openhab.core.automation.RuleManager");
	} catch(e) {
		var RuleManager = Java.type("org.eclipse.smarthome.automation.RuleManager");
	}

It appears the JS helper libraries are using the newer (post ESH reintegration) package names for some of the classes. There may be others, but I’ll put in a PR for this. You wouldn’t have had this issue with Jython :wink:.

Thanks for the tips! Sadly they didn’t fix my problem.

I tried changing the lines as you mentioned, but i still had the same issue. I have now upgraded to snapshot via openhabian-config, but I still have pretty much the same issue. I do get some more stuff in the log now:
When openhab is loading is see the 30s delay, as expected, then it gives me these messages:

2019-06-27 15:12:58.132 [INFO ] [rt.internal.loader.ScriptFileWatcher] - Loading script 'javascript/personal/HelloWorld.js'

2019-06-27 15:12:58.213 [DEBUG] [ipt.internal.ScriptEngineManagerImpl] - Added ScriptEngine for language 'js' with identifier: file:/etc/openhab2/automation/jsr223/javascript/personal/HelloWorld.js

2019-06-27 15:12:58.590 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - Error during evaluation of script 'file:/etc/openhab2/automation/jsr223/javascript/personal/HelloWorld.js': java.lang.ClassNotFoundException: org.eclipse.smarthome.automation.core.util.RuleManager

2019-06-27 15:12:58.591 [DEBUG] [rt.internal.loader.ScriptFileWatcher] - Script loaded: javascript/personal/HelloWorld.js

I still dont get this, because it says it’s loaded the script, but it still doesn’t work…
What can I do to fix this?

And yes, I get that jython may be better, but I want to learn both anyways so I’ll get to that one time :sweat_smile:

Greetings,

jvank

PS: Since the upgrade to snapshot, I get this in my logs every minute:

2019-06-27 15:21:02.454 [ERROR] [core.karaf.internal.FeatureInstaller] - Failed installing 'openhab-misc-restdocs'

Where can i disable this installation?

Sorry, I went too fast and messed up a copy/paste… I’ve corrected my post. Try that out :slightly_smiling_face:! Or grab the latest from the repo, as this is now included.

Either that is a recent issue, or it may be a symptom of not clearing the cache after upgrading. Also, try restarting OH an additional time… OH does not seem to be starting up properly the first time after the cache has been cleared.

Awesome!

I tried it, and this time it worked right away. Thanks!
I also found out that the install failed log entry could be solved by removing restdocs from addons.config

Thanks for your help and now it’s time for me to start learning how to use this stuff!

1 Like

Hi Scoot,
I’m on the newest stable version (2.5.5) but still gettin the same error

2020-05-19 16:05:02.387 [ERROR] [ipt.internal.ScriptEngineManagerImpl] - Error during evaluation of script ‘file:/etc/openhab2/automation/jsr223/javascript/personal/00_scripts/02_startup.js’: java.lang.ClassNotFoundException: org.eclipse.smarthome.automation.core.util.RuleBuilder

I tried the correct interpretation of your suggest to identify the path indicate for the change eventually but didn’t find it.

I suppose this kind of error must be disappearde after upgrading but still there anyway.
Any other suggest?
Thank you Sir

Could you post your script?

'use strict';
load('/etc/openhab2/automation/lib/javascript/personal/00_jslib/JSRule.js');

function startup()
{
    logInfo("startup()")
    
    var itemSysStartup = getItem("SysStartup");
    sendCommand(itemSysStartup,ON);

    var itemSpeedtestRerun = getItem("SpeedtestRerun");
    postUpdate(itemSpeedtestRerun,OFF);

    var itemSpeedtestSummary = getItem("SpeedtestSummary");
    postUpdate(itemSpeedtestSummary,"-");

    var itemSysStartupForce = getItem("SysStartupForce");
    sendCommand(itemSysStartupForce,OFF);

    sendCommand(itemSysStartup,OFF);
}

startup();

and

/**
 * Copyright (c) 2018 by Helmut Lehmeyer.
 * 
 * @author Helmut Lehmeyer 
 */

'use strict';

se.importPreset("RuleSupport");
se.importPreset("RuleSimple");
se.importPreset("RuleFactories");
se.importPreset("default");

var OPENHAB_CONF = Java.type("java.lang.System").getenv("OPENHAB_CONF"); // most this is /etc/openhab2
load(OPENHAB_CONF+'/automation/lib/javascript/personal/00_jslib/helper.js');
load(OPENHAB_CONF+'/automation/lib/javascript/personal/00_jslib/triggersAndConditions.js');



//Simplifies spelling for rules.
(function (context) {
	'use strict';

    context.JSRule = function(obj) {
        logInfo("JSRule added: '"+obj.name+"' "+obj.description);

        var rname =  obj.name ? obj.name.replace(/[^\w]/g, "-") : "nameless-generic";
        var ruid = obj.uid ? obj.uid : uuid.randomUUID() + "-" + rname;
        
        var rule = new SimpleRule()
        {
            execute: function(module,input)
            {
                try {
                    obj.execute(module,input);
                    //logInfo("'"+obj.name+"' executed");
                }
                catch(e) {
                    var out =""
                    if (e instanceof TypeError) {
                        out+="TypeError"
                    } else if (e instanceof RangeError) {
                        out+="RanegError"
                    } else if (e instanceof EvalError) {
                        out+="EvalError"
                    } else {
                        out+="Error"
                    }
                    logError(obj.name+" "+out+": "+e.toString());
                }
                finally {
                    // always runs even if there was an error, good place for cleanup
                }
            }
        };

        if(obj.description)
        {
            rule.setDescription(obj.name +" / "+ obj.description);
        }
        
        if(obj.name)
        {
            rule.setName(obj.name);
        }

        rule.setTemplateUID(ruid);

        var triggers = obj.triggers ? obj.triggers : obj.getEventTrigger();
        if(triggers && triggers.length > 0)
        {
            rule.setTriggers(triggers);
            automationManager.addRule(rule);
        }
        return rule;
    },

	//TODO like in org.eclipse.smarthome.automation.core.dto.RuleDTOMapper 
	// or org.eclipse.smarthome.automation.sample.extension.java.internal.WelcomeHomeRulesProvider
	//Missing SimpleRuleActionHandler!!
	context.JSRuleNew = function (obj) {
		//logInfo("################  JSRule Line: "+__LINE__+"  #################");
		//2. OR second option, to add Rules in rulefile. Is not needed.
		var rname =  obj.name ? obj.name.replace(/[^\w]/g, "-") : "nameless-generic";
		var ruid = obj.uid ? obj.uid : uuid.randomUUID() + "-" + rname;
		var triggers = obj.triggers ? obj.triggers : obj.getEventTrigger();
		return RuleBuilder.create(ruid)
			.withActions(obj.execute ? [obj.execute] : null)
			//.withConditions(obj.conditions ? obj.conditions : [])
			.withTriggers(triggers && triggers.length > 0 ? triggers : null)
			.withConfiguration(new Configuration(obj.configuration))
			.withConfigurationDescriptions(obj.configurationDescription ? [obj.configurationDescription] : null)
			.withTemplateUID(obj.templateUID ? obj.templateUID : ruid)
			.withVisibility(obj.visibility ? obj.visibility : null)
			.withTags(obj.tags ? obj.tags : null)
			.withName(obj.name ? obj.name : null)
			.withDescription(obj.description ? obj.description : null)
			.build();
	}
	
}) (this);

What is /etc/openhab2/automation/lib/javascript/personal/00_jslib/JSRule.js? Have you tried the updated JS libraries?

Hi, and thanks again for following me
I’m basically following this old project where Phyton and Javascript scripts were availables in download and are packet ready
My change was to restructuring the automation and Libraries based on the new approach (the suggest you just referring to)

Those are very out of date and specify OH 2.4.0. Maybe @illnesse can update them or help you out (the readme says to file an issue or to hit him up in the other topic). Although, he migrated to the libraries that I maintain…

1 Like