All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sdl.webapp.tridion.xpath.XPathResolver Maven / Gradle / Ivy

There is a newer version: 2.3.2
Show newest version
package com.sdl.webapp.tridion.xpath;

import com.google.common.collect.ImmutableBiMap;
import com.sdl.webapp.common.util.SimpleNamespaceContext;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * Resolver for particular xPath string.
 * Uses {@link javax.xml.xpath.XPathExpression} which is not thread-safe.
 */
public enum XPathResolver {
    XPATH_LINKS("//a[@xlink:href]"),
    XPATH_YOUTUBE("//img[@data-youTubeId]"),
    XPATH_IMAGES("//img[@data-schemaUri]");


    /**
     * Constant XHTML_NS_URI="http://www.w3.org/1999/xhtml"
     */
    public static final String XHTML_NS_URI = "http://www.w3.org/1999/xhtml";
    /**
     * Constant XLINK_NS_URI="http://www.w3.org/1999/xlink"
     */
    public static final String XLINK_NS_URI = "http://www.w3.org/1999/xlink";

    private static final NamespaceContext NAMESPACE_CONTEXT = new SimpleNamespaceContext(
            ImmutableBiMap.builder()
                    .put("xhtml", XHTML_NS_URI)
                    .put("xlink", XLINK_NS_URI)
                    .build());

    private ThreadLocal expression;
    private String sourceString;

    XPathResolver(final String sourceString) {
        // note that PathExpression is not thread-safe
        this(sourceString, new ThreadLocal() {
            @Override
            protected XPathExpression initialValue() {
                try {
                    final XPath xpath = XPathFactory.newInstance().newXPath();
                    xpath.setNamespaceContext(NAMESPACE_CONTEXT);
                    return xpath.compile(sourceString);
                } catch (XPathExpressionException e) {
                    throw new RuntimeException(
                            "Error while creating XPath expression", e);
                }
            }
        });
    }

    XPathResolver(String sourceString, ThreadLocal expression) {
        this.expression = expression;
        this.sourceString = sourceString;
    }

    /**
     * 

Getter for the field expression.

* * @return a {@link java.lang.ThreadLocal} object. */ public ThreadLocal getExpression() { return expression; } /** *

expr.

* * @return a {@link java.lang.ThreadLocal} object. */ public ThreadLocal expr() { return expression; } /** *

Getter for the field sourceString.

* * @return a {@link java.lang.String} object. */ public String getSourceString() { return sourceString; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy