2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.transform.javascript.internal;
15 import javax.script.Bindings;
16 import javax.script.CompiledScript;
17 import javax.script.ScriptException;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.transform.TransformationException;
22 import org.openhab.core.transform.TransformationService;
23 import org.osgi.service.component.annotations.Component;
24 import org.osgi.service.component.annotations.Reference;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * The implementation of {@link TransformationService} which transforms the
30 * input by Java Script.
32 * @author Pauli Anttila - Initial contribution
33 * @author Thomas Kordelle - pre compiled scripts
36 @Component(property = { "openhab.transform=JS" })
37 public class JavaScriptTransformationService implements TransformationService {
39 private Logger logger = LoggerFactory.getLogger(JavaScriptTransformationService.class);
40 private @NonNullByDefault({}) JavaScriptEngineManager manager;
43 public void setJavaScriptEngineManager(JavaScriptEngineManager manager) {
44 this.manager = manager;
47 public void unsetJavaScriptEngineManager(JavaScriptEngineManager manager) {
52 * Transforms the input <code>source</code> by Java Script. It expects the
53 * transformation rule to be read from a file which is stored under the
54 * 'configurations/transform' folder. To organize the various
55 * transformations one should use subfolders.
57 * @param filename the name of the file which contains the Java script
58 * transformation rule. Transformation service inject input
59 * (source) to 'input' variable.
60 * @param source the input to transform
63 public @Nullable String transform(String filename, String source) throws TransformationException {
64 if (filename == null || source == null) {
65 throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
68 final long startTime = System.currentTimeMillis();
69 logger.debug("about to transform '{}' by the JavaScript '{}'", source, filename);
74 final CompiledScript cScript = manager.getScript(filename);
75 final Bindings bindings = cScript.getEngine().createBindings();
76 bindings.put("input", source);
77 result = String.valueOf(cScript.eval(bindings));
79 } catch (ScriptException e) {
80 throw new TransformationException("An error occurred while executing script. " + e.getMessage(), e);
82 logger.trace("JavaScript execution elapsed {} ms. Result: {}", System.currentTimeMillis() - startTime,