Search in sources :

Example 1 with TransformationException

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);
}
Also used : ScriptException(javax.script.ScriptException) TransformationException(org.eclipse.smarthome.core.transform.TransformationException) InputStreamReader(java.io.InputStreamReader) FileNotFoundException(java.io.FileNotFoundException) ScriptEngineManager(javax.script.ScriptEngineManager) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) Logger(org.slf4j.Logger) FileInputStream(java.io.FileInputStream) ScriptEngine(javax.script.ScriptEngine)

Example 2 with TransformationException

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);
    }
}
Also used : TransformationException(org.eclipse.smarthome.core.transform.TransformationException) InvalidJsonException(com.jayway.jsonpath.InvalidJsonException) List(java.util.List) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) InvalidPathException(com.jayway.jsonpath.InvalidPathException)

Example 3 with TransformationException

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);
    }
}
Also used : TransformationException(org.eclipse.smarthome.core.transform.TransformationException) Matcher(java.util.regex.Matcher) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal) LinkedHashMap(java.util.LinkedHashMap) FileReader(java.io.FileReader)

Example 4 with TransformationException

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();
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) TransformationException(org.eclipse.smarthome.core.transform.TransformationException) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) Document(org.w3c.dom.Document) TransformationException(org.eclipse.smarthome.core.transform.TransformationException)

Example 5 with TransformationException

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;
}
Also used : TransformationException(org.eclipse.smarthome.core.transform.TransformationException) Matcher(java.util.regex.Matcher) TransformationService(org.eclipse.smarthome.core.transform.TransformationService)

Aggregations

TransformationException (org.eclipse.smarthome.core.transform.TransformationException)8 Matcher (java.util.regex.Matcher)3 StringReader (java.io.StringReader)2 TransformationService (org.eclipse.smarthome.core.transform.TransformationService)2 Logger (org.slf4j.Logger)2 InvalidJsonException (com.jayway.jsonpath.InvalidJsonException)1 InvalidPathException (com.jayway.jsonpath.InvalidPathException)1 PathNotFoundException (com.jayway.jsonpath.PathNotFoundException)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileReader (java.io.FileReader)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 StringWriter (java.io.StringWriter)1 BigDecimal (java.math.BigDecimal)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 ScriptEngine (javax.script.ScriptEngine)1