2 * Copyright (c) 2010-2020 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.xpath.internal;
15 import java.io.StringReader;
17 import javax.xml.parsers.DocumentBuilder;
18 import javax.xml.parsers.DocumentBuilderFactory;
19 import javax.xml.xpath.XPath;
20 import javax.xml.xpath.XPathConstants;
21 import javax.xml.xpath.XPathExpression;
22 import javax.xml.xpath.XPathFactory;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.core.transform.TransformationException;
27 import org.openhab.core.transform.TransformationService;
28 import org.osgi.service.component.annotations.Component;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.xml.sax.InputSource;
36 * The implementation of {@link TransformationService} which transforms the input by XPath Expressions.
38 * @author Thomas.Eichstaedt-Engelen
41 @Component(property = { "openhab.transform=XPATH" })
42 public class XPathTransformationService implements TransformationService {
44 private final Logger logger = LoggerFactory.getLogger(XPathTransformationService.class);
47 public @Nullable String transform(String xpathExpression, String source) throws TransformationException {
48 if (xpathExpression == null || source == null) {
49 throw new TransformationException("the given parameters 'xpath' and 'source' must not be null");
52 logger.debug("about to transform '{}' by the function '{}'", source, xpathExpression);
54 StringReader stringReader = null;
57 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
58 domFactory.setNamespaceAware(true);
59 domFactory.setValidating(false);
60 DocumentBuilder builder = domFactory.newDocumentBuilder();
62 stringReader = new StringReader(source);
63 InputSource inputSource = new InputSource(stringReader);
64 inputSource.setEncoding("UTF-8");
66 Document doc = builder.parse(inputSource);
68 XPath xpath = XPathFactory.newInstance().newXPath();
69 XPathExpression expr = xpath.compile(xpathExpression);
71 String transformationResult = (String) expr.evaluate(doc, XPathConstants.STRING);
73 logger.debug("transformation resulted in '{}'", transformationResult);
75 return transformationResult;
76 } catch (Exception e) {
77 throw new TransformationException("transformation throws exceptions", e);
79 if (stringReader != null) {