Example usage for javax.xml.xpath XPath compile

List of usage examples for javax.xml.xpath XPath compile

Introduction

In this page you can find the example usage for javax.xml.xpath XPath compile.

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:com.espertech.esper.event.xml.SchemaXMLPropertyParser.java

/**
 * Return the xPath corresponding to the given property.
 * The propertyName String may be simple, nested, indexed or mapped.
 *
 * @param propertyName is the event property name
 * @param namespace is the default namespace
 * @param schemaModel is the schema model
 * @param xPathFactory is the xpath factory instance to use
 * @param rootElementName is the name of the root element
 * @param eventAdapterService for type lookup and creation
 * @param xmlEventType the resolving type
 * @param isAllowFragment whether fragmenting is allowed
 * @param defaultNamespace default namespace
 * @return xpath expression/*from   www . j  av  a  2  s.co  m*/
 * @throws EPException is there are XPath errors
 */
public static EventPropertyGetter getXPathResolution(String propertyName, XPathFactory xPathFactory,
        String rootElementName, String namespace, SchemaModel schemaModel,
        EventAdapterService eventAdapterService, BaseXMLEventType xmlEventType, boolean isAllowFragment,
        String defaultNamespace) throws EPException {
    if (log.isDebugEnabled()) {
        log.debug("Determining XPath expression for property '" + propertyName + "'");
    }

    XPathNamespaceContext ctx = new XPathNamespaceContext();
    List<String> namespaces = schemaModel.getNamespaces();

    String defaultNamespacePrefix = null;
    for (int i = 0; i < namespaces.size(); i++) {
        String prefix = "n" + i;
        ctx.addPrefix(prefix, namespaces.get(i));
        if ((defaultNamespace != null) && (defaultNamespace.equals(namespaces.get(i)))) {
            defaultNamespacePrefix = prefix;
        }
    }

    Tree ast = PropertyParser.parse(propertyName);
    Property property = PropertyParser.parse(propertyName, false);
    boolean isDynamic = property.isDynamic();

    SchemaElementComplex rootComplexElement = SchemaUtil.findRootElement(schemaModel, namespace,
            rootElementName);
    String prefix = ctx.getPrefix(rootComplexElement.getNamespace());
    if (prefix == null) {
        prefix = "";
    } else {
        prefix += ':';
    }

    StringBuilder xPathBuf = new StringBuilder();
    xPathBuf.append('/');
    xPathBuf.append(prefix);
    if (rootElementName.startsWith("//")) {
        xPathBuf.append(rootElementName.substring(2));
    } else {
        xPathBuf.append(rootElementName);
    }

    SchemaElementComplex parentComplexElement = rootComplexElement;
    Pair<String, QName> pair = null;

    if (ast.getChildCount() == 1) {
        pair = makeProperty(rootComplexElement, ast.getChild(0), ctx, true, isDynamic, defaultNamespacePrefix);
        if (pair == null) {
            throw new PropertyAccessException("Failed to locate property '" + propertyName + "' in schema");
        }
        xPathBuf.append(pair.getFirst());
    } else {
        for (int i = 0; i < ast.getChildCount(); i++) {
            boolean isLast = (i == ast.getChildCount() - 1);
            Tree child = ast.getChild(i);
            pair = makeProperty(parentComplexElement, child, ctx, isLast, isDynamic, defaultNamespacePrefix);
            if (pair == null) {
                throw new PropertyAccessException("Failed to locate property '" + propertyName
                        + "' nested property part '" + child.toString() + "' in schema");
            }

            String text = child.getChild(0).getText();
            SchemaItem obj = SchemaUtil.findPropertyMapping(parentComplexElement, text);
            if (obj instanceof SchemaElementComplex) {
                parentComplexElement = (SchemaElementComplex) obj;
            }
            xPathBuf.append(pair.getFirst());
        }
    }

    String xPath = xPathBuf.toString();
    if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
        log.debug(".parse XPath for property '" + propertyName + "' is expression=" + xPath);
    }

    // Compile assembled XPath expression
    XPath path = xPathFactory.newXPath();
    path.setNamespaceContext(ctx);

    if (log.isDebugEnabled()) {
        log.debug("Compiling XPath expression '" + xPath + "' for property '" + propertyName
                + "' using namespace context :" + ctx);
    }

    XPathExpression expr;
    try {
        expr = path.compile(xPath);
    } catch (XPathExpressionException e) {
        String detail = "Error constructing XPath expression from property expression '" + propertyName
                + "' expression '" + xPath + "'";
        if (e.getMessage() != null) {
            throw new EPException(detail + " :" + e.getMessage(), e);
        }
        throw new EPException(detail, e);
    }

    // get type
    SchemaItem item = property.getPropertyTypeSchema(rootComplexElement, eventAdapterService);
    if ((item == null) && (!isDynamic)) {
        return null;
    }

    Class resultType;
    if (!isDynamic) {
        resultType = SchemaUtil.toReturnType(item);
    } else {
        resultType = Node.class;
    }

    FragmentFactory fragmentFactory = null;
    if (isAllowFragment) {
        fragmentFactory = new FragmentFactoryDOMGetter(eventAdapterService, xmlEventType, propertyName);
    }
    return new XPathPropertyGetter(propertyName, xPath, expr, pair.getSecond(), resultType, fragmentFactory);
}

From source file:cz.cas.lib.proarc.common.export.mets.JhoveUtility.java

/**
 * Gets MIX of a source image file.//from w  ww .java 2s .  co m
 *
 * @param sourceFile image file to describe with MIX
 * @param jhoveContext JHove
 * @param deviceMix optional device description
 * @param dateCreated optional date of creation of the source
 * @param originalFileName optional image file name
 * @return the MIX description
 * @throws MetsExportException failure
 */
public static JHoveOutput getMix(File sourceFile, JhoveContext jhoveContext, MixType deviceMix,
        XMLGregorianCalendar dateCreated, String originalFileName) throws MetsExportException {

    JHoveOutput jhoveOutput = new JHoveOutput();

    if (sourceFile == null || !sourceFile.isFile() || !sourceFile.exists()) {
        LOG.log(Level.SEVERE, "target file '" + sourceFile + "' cannot be found.");
        throw new MetsExportException("target file '" + sourceFile + "' cannot be found.", false, null);
    }
    try {
        JhoveBase jhoveBase = jhoveContext.getJhoveBase();
        File outputFile = File.createTempFile("jhove", "output");
        LOG.log(Level.FINE, "JHOVE output file " + outputFile);
        Module module = jhoveBase.getModule(null);
        OutputHandler aboutHandler = jhoveBase.getHandler(null);
        OutputHandler xmlHandler = jhoveBase.getHandler("XML");
        LOG.log(Level.FINE, "Calling JHOVE dispatch(...) on file " + sourceFile);
        jhoveBase.dispatch(jhoveContext.getJhoveApp(), module, aboutHandler, xmlHandler,
                outputFile.getAbsolutePath(), new String[] { sourceFile.getAbsolutePath() });
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document jHoveDoc = builder.parse(outputFile);

        outputFile.delete();
        Node node = getNodeRecursive(jHoveDoc, "mix");
        if (node == null) {
            return jhoveOutput;
        }
        Mix mix = MixUtils.unmarshal(new DOMSource(node), Mix.class);

        XPath xpath = XPathFactory.newInstance().newXPath();
        String formatVersion = xpath
                .compile("*[local-name()='jhove']/*[local-name()='repInfo']/*[local-name()='version']")
                .evaluate(jHoveDoc);
        if ((formatVersion == null) || ("0".equals(formatVersion)) || (formatVersion.trim().length() == 0)) {
            formatVersion = "1.0";
        }
        String formatName = xpath
                .compile("*[local-name()='jhove']/*[local-name()='repInfo']/*[local-name()='mimeType']")
                .evaluate(jHoveDoc);
        if ((formatName == null) || (formatName.trim().length() == 0)) {
            formatName = "unknown";
        }
        jhoveOutput.setFormatVersion(formatVersion);
        // merge device and jhove Mix
        mergeMix(mix, deviceMix);
        // insert date time created
        if ((dateCreated != null) && (mix != null)) {
            insertDateCreated(mix, dateCreated);
        }

        // insert ChangeHistory
        if ((dateCreated != null) && (originalFileName != null)) {
            insertChangeHistory(mix, dateCreated, originalFileName);
        }

        // add formatVersion
        if (mix != null) {
            if (mix.getBasicDigitalObjectInformation() == null) {
                mix.setBasicDigitalObjectInformation(new BasicDigitalObjectInformationType());
            }
            if (mix.getBasicDigitalObjectInformation().getFormatDesignation() == null) {
                mix.getBasicDigitalObjectInformation()
                        .setFormatDesignation(new BasicDigitalObjectInformationType.FormatDesignation());
            }
            StringType formatNameType = new StringType();
            StringType formatVersionType = new StringType();
            formatNameType.setValue(formatName);
            formatVersionType.setValue(formatVersion);
            mix.getBasicDigitalObjectInformation().getFormatDesignation().setFormatName(formatNameType);
            mix.getBasicDigitalObjectInformation().getFormatDesignation().setFormatVersion(formatVersionType);
        }

        // workarround for bug in Jhove - Unknown compression for jpeg2000
        if ("image/jp2".equals(formatName)) {
            if (mix.getBasicDigitalObjectInformation() == null) {
                mix.setBasicDigitalObjectInformation(new BasicDigitalObjectInformationType());
            }
            mix.getBasicDigitalObjectInformation().getCompression().clear();
            Compression compression = new BasicDigitalObjectInformationType.Compression();
            StringType jpeg2000Type = new StringType();
            jpeg2000Type.setValue("JPEG 2000");
            compression.setCompressionScheme(jpeg2000Type);
            mix.getBasicDigitalObjectInformation().getCompression().add(compression);
        }
        jhoveOutput.setMix(mix);
    } catch (Exception e) {
        throw new MetsExportException("Error inspecting file '" + sourceFile + "' - " + e.getMessage(), false,
                e);
    }
    return jhoveOutput;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readJARAConfiguration(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    // jara url// w  w w .  ja v  a2  s .  c om
    jaraUrl = (String) xpath.compile("/configuration/general/jara/url/@value").evaluate(xmlConfiguration,
            XPathConstants.STRING);
    jaraUrl = Utils.removeLastSlash(jaraUrl);

    // jara config directory
    jaraConfigPath = (String) xpath.compile("/configuration/general/jara/config-dir/@value")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readNordirGeodirUrl(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    nordirGeodirUrl = null;//from  www  .j  av  a2  s .  c  om

    nordirGeodirUrl = (String) xpath.compile("/configuration/general/nordir-geodir-url/@value")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
}

From source file:com.twentyn.patentExtractor.PatentDocument.java

/**
 * Extracts the text content from text fields in a patent XML document.
 *
 * @param docBuilder A document builder to use when constructing intermediate XML/HTML documents in the extraction
 *                   process.// ww  w  . j a va2  s  .  c  om
 * @param paths      A list of XPath paths from which to exactract text.
 * @param xpath      An XPath instance to use when running XPath queries.
 * @param doc        The XML document from which to extract text.
 * @return A list of strings representing the textual content of the document.  These could be sentences,
 * paragraphs, or larger text units, but should represent some sort of structure in the document's text.
 * @throws ParserConfigurationException
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws XPathExpressionException
 */
private static List<String> getRelevantDocumentText(DocumentBuilder docBuilder, String[] paths, XPath xpath,
        Document doc) throws ParserConfigurationException, TransformerConfigurationException,
        TransformerException, XPathExpressionException {
    List<String> allTextList = new ArrayList<>(0);
    for (String path : paths) {
        XPathExpression exp = xpath.compile(path);
        NodeList textNodes = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
        allTextList.addAll(extractTextFromHTML(docBuilder, textNodes));
    }

    return allTextList;
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static Document replaceTokens(Document doc, Policy configTokens)
        throws XPathExpressionException, TransformerConfigurationException {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(configTokens);
    logger.info("============= to apply the following config tokens ================\n{}", json);

    try {/*from www.  j av a2  s .c  om*/
        for (int i = 0; i < configTokens.tokens.size(); i++) {

            logger.debug("=============Checking for Xpath Expressions {}  ================\n",
                    configTokens.tokens.get(i).xpath);
            XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath);

            NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

            for (int j = 0; j < nodes.getLength(); j++) {

                if (nodes.item(j).hasChildNodes()) {
                    logger.debug("=============Updated existing value {} to new value {} ================\n",
                            nodes.item(j).getTextContent(), configTokens.tokens.get(i).value);
                    nodes.item(j).setTextContent(configTokens.tokens.get(i).value);
                }
            }

        }

        return doc;
    } catch (XPathExpressionException e) {

        logger.error(String.format(
                "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s",
                e.getMessage()), e);
        throw e;
    }

}

From source file:com.ephesoft.dcma.util.XMLUtil.java

/**
 * @param doc {@link org.w3c.dom.Document}
 * @param xPathExpression {@link String}
 * @return//from ww w  .  jav  a 2  s .  c  o  m
 */
public static String getValueFromXML(final Document doc, final String xPathExpression)
        throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String requiredValue = "";
    XPathExpression expr = xpath.compile(xPathExpression);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    Node item = nodes.item(0);
    if (item != null) {
        requiredValue = item.getFirstChild().getNodeValue();
    }
    return requiredValue;
}

From source file:com.seer.datacruncher.utils.generic.CommonUtils.java

public static NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(xpathExpression);
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    return (NodeList) result;
}

From source file:Main.java

public static XPathExpression buildXPath(String path, Map<String, String> map) {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    if (map != null)
        xpath.setNamespaceContext(new NamespaceContext() {

            public Iterator getPrefixes(String namespaceURI) {
                throw new UnsupportedOperationException();
            }/* ww  w .  ja  va  2s .  c  om*/

            public String getPrefix(String namespaceURI) {
                throw new UnsupportedOperationException();
            }

            public String getNamespaceURI(String prefix) {
                Objects.requireNonNull(prefix);
                if (map.containsKey(prefix))
                    return map.get(prefix);
                return XMLConstants.NULL_NS_URI;
            }
        });

    try {
        return xpath.compile(path);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.radium226.github.maven.MetaDataDownloader.java

public static String evaluateXPath(InputStream pomInputStream, String expression)
        throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new NamespaceContext() {

        @Override//from   ww  w .  j a v  a 2s .com
        public String getNamespaceURI(String prefix) {
            if (prefix.equals("ns")) {
                return "http://maven.apache.org/POM/4.0.0";
            }

            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
    XPathExpression xPathExpression = xPath.compile(expression);
    String version = (String) xPathExpression.evaluate(new InputSource(pomInputStream), XPathConstants.STRING);
    return version;
}