Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[automation] Added script filename to engine, if engineIdentifier is a file #1196

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
*/
package org.openhab.core.automation.module.script.internal;

import java.io.File;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

Expand Down Expand Up @@ -145,6 +147,7 @@ public void loadScript(String engineIdentifier, InputStreamReader scriptData) {
} else {
ScriptEngine engine = container.getScriptEngine();
try {
tryExtractAndInjectFilename(engineIdentifier, engine);
engine.eval(scriptData);

if (engine instanceof Invocable) {
Expand All @@ -163,6 +166,17 @@ public void loadScript(String engineIdentifier, InputStreamReader scriptData) {
}
}

private void tryExtractAndInjectFilename(String engineIdentifier, ScriptEngine engine) {
try {
File maybeScriptFile = new File(engineIdentifier);
jpg0 marked this conversation as resolved.
Show resolved Hide resolved
if(maybeScriptFile.isFile()) {
jpg0 marked this conversation as resolved.
Show resolved Hide resolved
engine.getContext().setAttribute(ScriptEngine.FILENAME, maybeScriptFile.getName(), ScriptContext.ENGINE_SCOPE);
}
} catch (Exception e) {
logger.warn("Failure whilst inserting script filename: {}" + e.getMessage());
jpg0 marked this conversation as resolved.
Show resolved Hide resolved
}
}

@Override
public void removeEngine(String engineIdentifier) {
ScriptEngineContainer container = loadedScriptEngineInstances.get(engineIdentifier);
Expand Down