use of org.eclipse.smarthome.core.transform.TransformationException in project smarthome by eclipse.
the class JavaScriptTransformationService method transform.
/**
* Transforms the input <code>source</code> by Java Script. It expects the
* transformation rule to be read from a file which is stored under the
* 'configurations/transform' folder. To organize the various
* transformations one should use subfolders.
*
* @param filename
* the name of the file which contains the Java script
* transformation rule. Transformation service inject input
* (source) to 'input' variable.
* @param source
* the input to transform
*/
@Override
public String transform(String filename, String source) throws TransformationException {
Logger logger = LoggerFactory.getLogger(JavaScriptTransformationService.class);
if (filename == null || source == null) {
throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
}
logger.debug("about to transform '{}' by the Java Script '{}'", source, filename);
Reader reader;
try {
String path = ConfigConstants.getConfigFolder() + File.separator + TransformationService.TRANSFORM_FOLDER_NAME + File.separator + filename;
reader = new InputStreamReader(new FileInputStream(path));
} catch (FileNotFoundException e) {
throw new TransformationException("An error occurred while loading script.", e);
}
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
engine.put("input", source);
Object result = null;
long startTime = System.currentTimeMillis();
try {
result = engine.eval(reader);
} catch (ScriptException e) {
throw new TransformationException("An error occurred while executing script.", e);
} finally {
IOUtils.closeQuietly(reader);
}
logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime);
return String.valueOf(result);
}
use of org.eclipse.smarthome.core.transform.TransformationException in project smarthome by eclipse.
the class JSonPathTransformationService method transform.
/**
* Transforms the input <code>source</code> by JSonPath expression.
*
* @param function JsonPath expression
* @param source String which contains JSON
* @throws TransformationException If the JsonPath expression is invalid, a {@link InvalidPathException} is thrown,
* which is encapsulated in a {@link TransformationException}.
*/
@Override
public String transform(String jsonPathExpression, String source) throws TransformationException {
if (jsonPathExpression == null || source == null) {
throw new TransformationException("the given parameters 'JSonPath' and 'source' must not be null");
}
logger.debug("about to transform '{}' by the function '{}'", source, jsonPathExpression);
try {
Object transformationResult = JsonPath.read(source, jsonPathExpression);
logger.debug("transformation resulted in '{}'", transformationResult);
if (transformationResult == null) {
return UnDefType.NULL.toFullString();
} else if (transformationResult instanceof List) {
return flattenList((List<?>) transformationResult);
} else {
return transformationResult.toString();
}
} catch (PathNotFoundException e) {
throw new TransformationException("Invalid path '" + jsonPathExpression + "' in '" + source + "'");
} catch (InvalidPathException | InvalidJsonException e) {
throw new TransformationException("An error occurred while transforming JSON expression.", e);
}
}
use of org.eclipse.smarthome.core.transform.TransformationException in project smarthome by eclipse.
the class ScaleTransformationService method internalLoadTransform.
@Override
protected Map<Range, String> internalLoadTransform(String filename) throws TransformationException {
try (FileReader reader = new FileReader(filename)) {
final Map<Range, String> data = new LinkedHashMap<>();
final OrderedProperties properties = new OrderedProperties();
properties.load(reader);
for (Object orderedKey : properties.orderedKeys()) {
final String entry = (String) orderedKey;
final String value = properties.getProperty(entry);
final Matcher matcher = LIMITS_PATTERN.matcher(entry);
if (matcher.matches() && (matcher.groupCount() == 4)) {
final boolean lowerInclusive = matcher.group(1).equals("]") ? false : true;
final boolean upperInclusive = matcher.group(4).equals("[") ? false : true;
final String lowLimit = matcher.group(2);
final String highLimit = matcher.group(3);
try {
final BigDecimal lowValue = lowLimit.isEmpty() ? null : new BigDecimal(lowLimit);
final BigDecimal highValue = highLimit.isEmpty() ? null : new BigDecimal(highLimit);
final Range range = Range.range(lowValue, lowerInclusive, highValue, upperInclusive);
data.put(range, value);
} catch (NumberFormatException ex) {
throw new TransformationException("Error parsing bounds: " + lowLimit + ".." + highLimit);
}
} else {
logger.warn("Scale transform file '{}' does not comply with syntax for entry : '{}', '{}'", filename, entry, value);
}
}
return data;
} catch (final IOException ex) {
throw new TransformationException("An error occurred while opening file.", ex);
}
}
use of org.eclipse.smarthome.core.transform.TransformationException in project smarthome by eclipse.
the class XPathTransformationService method transform.
@Override
public String transform(String xpathExpression, String source) throws TransformationException {
if (xpathExpression == null || source == null) {
throw new TransformationException("the given parameters 'xpath' and 'source' must not be null");
}
logger.debug("about to transform '{}' by the function '{}'", source, xpathExpression);
StringReader stringReader = null;
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
domFactory.setValidating(false);
DocumentBuilder builder = domFactory.newDocumentBuilder();
stringReader = new StringReader(source);
InputSource inputSource = new InputSource(stringReader);
inputSource.setEncoding("UTF-8");
Document doc = builder.parse(inputSource);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(xpathExpression);
String transformationResult = (String) expr.evaluate(doc, XPathConstants.STRING);
logger.debug("transformation resulted in '{}'", transformationResult);
return transformationResult;
} catch (Exception e) {
throw new TransformationException("transformation throws exceptions", e);
} finally {
if (stringReader != null) {
stringReader.close();
}
}
}
use of org.eclipse.smarthome.core.transform.TransformationException in project smarthome by eclipse.
the class ItemUIRegistryImpl method transform.
/*
* check if there is a status value being displayed on the right side of the
* label (the right side is signified by being enclosed in square brackets [].
* If so, check if the value starts with the call to a transformation service
* (e.g. "[MAP(en.map):%s]") and execute the transformation in this case.
* If the value does not start with the call to a transformation service,
* we return the label with the mapped option value if provided (not null).
*/
private String transform(String label, String labelMappedOption) {
String ret = label;
if (getFormatPattern(label) != null) {
Matcher matcher = EXTRACT_TRANSFORMFUNCTION_PATTERN.matcher(label);
if (matcher.find()) {
String type = matcher.group(1);
String pattern = matcher.group(2);
String value = matcher.group(3);
TransformationService transformation = TransformationHelper.getTransformationService(UIActivator.getContext(), type);
if (transformation != null) {
try {
ret = label.substring(0, label.indexOf("[") + 1) + transformation.transform(pattern, value) + "]";
} catch (TransformationException e) {
logger.error("transformation throws exception [transformation={}, value={}]", transformation, value, e);
ret = label.substring(0, label.indexOf("[") + 1) + value + "]";
}
} else {
logger.warn("couldn't transform value in label because transformationService of type '{}' is unavailable", type);
ret = label.substring(0, label.indexOf("[") + 1) + value + "]";
}
} else if (labelMappedOption != null) {
ret = labelMappedOption;
}
}
return ret;
}
Aggregations