I’ve been exploring creating JavaScript rules through MainUI and I’ve run into something that appears to have changed. I can’t say how recently it changed, in the past couple of weeks at least.
Problem:
Before now I was able to access openHAB actions using something like:
var Exec = Java.type("org.openhab.core.model.script.actions.Exec");
var Duration = Java.type("java.time.Duration");
var results = Exec.executeCommandLine(Duration.ofSeconds(1), "echo", "hello");
This now fails on the Java.type
line. When I run the rule triggered by an Item I get an error like
2020-11-12 09:14:55.695 [ERROR] [e.automation.internal.RuleEngineImpl] - Failed to execute rule 'experiment': Fail to execute action
: 1
When I trigger the rule by pressing the play button I get the following on the same line:
2020-11-12 09:14:46.843 [WARN ] [e.automation.internal.RuleEngineImpl] - Fail to execute action: 1
java.lang.RuntimeException: java.lang.ClassNotFoundException: org.openhab.core.model.script.actions.Log cannot be found by org.apache.aries.jax.rs.whiteboard_1.0.9
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:531) ~[jdk.scripting.nashorn:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:456) ~[jdk.scripting.nashorn:?]
This used to work.
As I’ve experimented to figure out what is going on I did find that the following works, but only when the rule is triggered by an Item:
var Log = this.Log;
Log.logError("Experiments", "This is an OH error log");
When the rule is triggered manually it complains that Log is undefined. When the rule is triggered from another rule, even when that other rule was triggered by an Item Log is undefined.
@ysc, should this be working or is the Docker builds behind am I’m running a version of OH 3 prior to the change you recently made that should have put the Action into the scope when triggered manually. I’m running Build #2006.
I wanted to open this on the forum to see if others are seeing the same and make sure I’m not doing something wrong before opening an issue.
Update:
It looks like what I’m seeing is a little different than expected.
When a rule is first executed after it is first loaded/updated it gets a context. That context is reused for each subsequent run of the rule. If the rule is first run manually, the context is missing that magical special sauce that allows access to the Actions. So even if later on the Rule is triggered by an Item it won’t have access to the Actions.
However, if the rule is first triggered using an Item event the full context is received. This allows the rule access to the Actions even if it is later run manually by pressing the play button.
So the root problem is how the rule is triggered that very first time.