Search in sources :

Example 71 with XPathFactory

use of javax.xml.xpath.XPathFactory in project lucene-solr by apache.

the class CurrencyValue method reload.

@Override
public boolean reload() throws SolrException {
    InputStream is = null;
    Map<String, Map<String, Double>> tmpRates = new HashMap<>();
    try {
        log.debug("Reloading exchange rates from file " + this.currencyConfigFile);
        is = loader.openResource(currencyConfigFile);
        javax.xml.parsers.DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            dbf.setXIncludeAware(true);
            dbf.setNamespaceAware(true);
        } catch (UnsupportedOperationException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "XML parser doesn't support XInclude option", e);
        }
        try {
            Document doc = dbf.newDocumentBuilder().parse(is);
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPath xpath = xpathFactory.newXPath();
            // Parse exchange rates.
            NodeList nodes = (NodeList) xpath.evaluate("/currencyConfig/rates/rate", doc, XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); i++) {
                Node rateNode = nodes.item(i);
                NamedNodeMap attributes = rateNode.getAttributes();
                Node from = attributes.getNamedItem("from");
                Node to = attributes.getNamedItem("to");
                Node rate = attributes.getNamedItem("rate");
                if (from == null || to == null || rate == null) {
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Exchange rate missing attributes (required: from, to, rate) " + rateNode);
                }
                String fromCurrency = from.getNodeValue();
                String toCurrency = to.getNodeValue();
                Double exchangeRate;
                if (null == CurrencyField.getCurrency(fromCurrency)) {
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Specified 'from' currency not supported in this JVM: " + fromCurrency);
                }
                if (null == CurrencyField.getCurrency(toCurrency)) {
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Specified 'to' currency not supported in this JVM: " + toCurrency);
                }
                try {
                    exchangeRate = Double.parseDouble(rate.getNodeValue());
                } catch (NumberFormatException e) {
                    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Could not parse exchange rate: " + rateNode, e);
                }
                addRate(tmpRates, fromCurrency, toCurrency, exchangeRate);
            }
        } catch (SAXException | XPathExpressionException | ParserConfigurationException | IOException e) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error parsing currency config.", e);
        }
    } catch (IOException e) {
        throw new SolrException(ErrorCode.SERVER_ERROR, "Error while opening Currency configuration file " + currencyConfigFile, e);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Atomically swap in the new rates map, if it loaded successfully
    this.rates = tmpRates;
    return true;
}
Also used : XPath(javax.xml.xpath.XPath) NamedNodeMap(org.w3c.dom.NamedNodeMap) HashMap(java.util.HashMap) InputStream(java.io.InputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HashMap(java.util.HashMap) Map(java.util.Map) NamedNodeMap(org.w3c.dom.NamedNodeMap) SolrException(org.apache.solr.common.SolrException)

Example 72 with XPathFactory

use of javax.xml.xpath.XPathFactory in project poi by apache.

the class XSSFImportFromXML method importFromXML.

/**
     * Imports an XML into the XLSX using the Custom XML mapping defined
     *
     * @param xmlInputString the XML to import
     * @throws SAXException if error occurs during XML parsing
     * @throws XPathExpressionException if error occurs during XML navigation
     * @throws ParserConfigurationException if there are problems with XML parser configuration
     * @throws IOException  if there are problems reading the input string
     */
public void importFromXML(String xmlInputString) throws SAXException, XPathExpressionException, IOException {
    DocumentBuilder builder = DocumentHelper.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xmlInputString.trim())));
    List<XSSFSingleXmlCell> singleXmlCells = _map.getRelatedSingleXMLCell();
    List<XSSFTable> tables = _map.getRelatedTables();
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    // Setting namespace context to XPath
    // Assuming that the namespace prefix in the mapping xpath is the
    // same as the one used in the document
    xpath.setNamespaceContext(new DefaultNamespaceContext(doc));
    for (XSSFSingleXmlCell singleXmlCell : singleXmlCells) {
        STXmlDataType.Enum xmlDataType = singleXmlCell.getXmlDataType();
        String xpathString = singleXmlCell.getXpath();
        Node result = (Node) xpath.evaluate(xpathString, doc, XPathConstants.NODE);
        // result can be null if value is optional (xsd:minOccurs=0), see bugzilla 55864
        if (result != null) {
            String textContent = result.getTextContent();
            logger.log(POILogger.DEBUG, "Extracting with xpath " + xpathString + " : value is '" + textContent + "'");
            XSSFCell cell = singleXmlCell.getReferencedCell();
            logger.log(POILogger.DEBUG, "Setting '" + textContent + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " + cell.getSheet().getSheetName());
            setCellValue(textContent, cell, xmlDataType);
        }
    }
    for (XSSFTable table : tables) {
        String commonXPath = table.getCommonXpath();
        NodeList result = (NodeList) xpath.evaluate(commonXPath, doc, XPathConstants.NODESET);
        // the first row contains the table header
        int rowOffset = table.getStartCellReference().getRow() + 1;
        int columnOffset = table.getStartCellReference().getCol() - 1;
        for (int i = 0; i < result.getLength(); i++) {
            // TODO: implement support for denormalized XMLs (see
            // OpenOffice part 4: chapter 3.5.1.7)
            Node singleNode = result.item(i).cloneNode(true);
            for (XSSFXmlColumnPr xmlColumnPr : table.getXmlColumnPrs()) {
                int localColumnId = (int) xmlColumnPr.getId();
                int rowId = rowOffset + i;
                int columnId = columnOffset + localColumnId;
                String localXPath = xmlColumnPr.getLocalXPath();
                localXPath = localXPath.substring(localXPath.substring(1).indexOf('/') + 2);
                // TODO: convert the data to the cell format
                String value = (String) xpath.evaluate(localXPath, singleNode, XPathConstants.STRING);
                logger.log(POILogger.DEBUG, "Extracting with xpath " + localXPath + " : value is '" + value + "'");
                XSSFRow row = table.getXSSFSheet().getRow(rowId);
                if (row == null) {
                    row = table.getXSSFSheet().createRow(rowId);
                }
                XSSFCell cell = row.getCell(columnId);
                if (cell == null) {
                    cell = row.createCell(columnId);
                }
                logger.log(POILogger.DEBUG, "Setting '" + value + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " + table.getXSSFSheet().getSheetName());
                setCellValue(value, cell, xmlColumnPr.getXmlDataType());
            }
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) XSSFTable(org.apache.poi.xssf.usermodel.XSSFTable) XSSFSingleXmlCell(org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) XSSFRow(org.apache.poi.xssf.usermodel.XSSFRow) XSSFXmlColumnPr(org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr) StringReader(java.io.StringReader) XSSFCell(org.apache.poi.xssf.usermodel.XSSFCell) STXmlDataType(org.openxmlformats.schemas.spreadsheetml.x2006.main.STXmlDataType)

Example 73 with XPathFactory

use of javax.xml.xpath.XPathFactory in project stanbol by apache.

the class HtmlExtractionRegistry method initialize.

public void initialize(InputStream configFileStream) throws InitializationException {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = parser.parse(new InputSource(configFileStream));
        Node node;
        NodeList nodes = (NodeList) xPath.evaluate("/htmlextractors/extractor", document, XPathConstants.NODESET);
        if (nodes != null) {
            TransformerFactory transFac = TransformerFactory.newInstance();
            transFac.setURIResolver(new BundleURIResolver());
            for (int j = 0, iCnt = nodes.getLength(); j < iCnt; j++) {
                Node nd = nodes.item(j);
                node = (Node) xPath.evaluate("@id", nd, XPathConstants.NODE);
                String id = node.getNodeValue();
                Node srcNode = (Node) xPath.evaluate("source", nd, XPathConstants.NODE);
                if (srcNode != null) {
                    node = (Node) xPath.evaluate("@type", srcNode, XPathConstants.NODE);
                    String srcType = node.getNodeValue();
                    if (srcType.equals("xslt")) {
                        String rdfFormat = "rdfxml";
                        String rdfSyntax = SupportedFormat.RDF_XML;
                        node = (Node) xPath.evaluate("@syntax", srcNode, XPathConstants.NODE);
                        if (node != null) {
                            //TODO check syntax types
                            rdfFormat = node.getNodeValue();
                            if (rdfFormat.equalsIgnoreCase("turtle")) {
                                rdfSyntax = SupportedFormat.TURTLE;
                            } else if (rdfFormat.equalsIgnoreCase("xturtle")) {
                                rdfSyntax = SupportedFormat.X_TURTLE;
                            } else if (rdfFormat.equalsIgnoreCase("ntriple")) {
                                rdfSyntax = SupportedFormat.N_TRIPLE;
                            } else if (rdfFormat.equalsIgnoreCase("n3")) {
                                rdfSyntax = SupportedFormat.N3;
                            } else if (!rdfFormat.equalsIgnoreCase("rdfxml")) {
                                throw new InitializationException("Unknown RDF Syntax: " + rdfFormat + " for " + id + " extractor");
                            }
                        }
                        String fileName = DOMUtils.getText(srcNode);
                        XsltExtractor xsltExtractor = new XsltExtractor(id, fileName, transFac);
                        xsltExtractor.setSyntax(rdfSyntax);
                        // name of URI/URL parameter of the script (default
                        // "uri")
                        node = (Node) xPath.evaluate("@uri", srcNode, XPathConstants.NODE);
                        if (node != null) {
                            xsltExtractor.setUriParameter(node.getNodeValue());
                        }
                        registry.put(id, xsltExtractor);
                        activeExtractors.add(id);
                    } else if (srcType.equals("java")) {
                        String clsName = srcNode.getNodeValue();
                        Object extractor = Class.forName(clsName).newInstance();
                        if (extractor instanceof HtmlExtractionComponent) {
                            registry.put(id, (HtmlExtractionComponent) extractor);
                            activeExtractors.add(id);
                        } else {
                            throw new InitializationException("clsName is not an HtmlExtractionComponent");
                        }
                    } else {
                        LOG.warn("No valid type for extractor found: " + id);
                    }
                    LOG.info("Extractor for: " + id);
                }
            }
        }
    } catch (FileNotFoundException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (XPathExpressionException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (DOMException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (InstantiationException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new InitializationException(e.getMessage(), e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) TransformerFactory(javax.xml.transform.TransformerFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DOMException(org.w3c.dom.DOMException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 74 with XPathFactory

use of javax.xml.xpath.XPathFactory in project bnd by bndtools.

the class bnd method doPerReport.

/**
	 * Calculate the coverage if there is coverage info in the test file.
	 */
private void doPerReport(Tag report, File file) throws Exception {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // never forget this!
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(file);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        doCoverage(report, doc, xpath);
        doHtmlReport(report, file, doc, xpath);
    } catch (Exception e) {
        report.addAttribute("coverage-failed", e.toString());
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document) InvocationTargetException(java.lang.reflect.InvocationTargetException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ZipException(java.util.zip.ZipException)

Example 75 with XPathFactory

use of javax.xml.xpath.XPathFactory in project dhis2-core by dhis2.

the class DhisConvenienceTest method xpathTest.

// -------------------------------------------------------------------------
// Allow xpath testing of DXF2
// -------------------------------------------------------------------------
protected String xpathTest(String xpathString, String xml) throws XPathExpressionException {
    InputSource source = new InputSource(new StringReader(xml));
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new Dxf2NamespaceResolver());
    return xpath.evaluate(xpathString, source);
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) InputSource(org.xml.sax.InputSource) StringReader(java.io.StringReader)

Aggregations

XPathFactory (javax.xml.xpath.XPathFactory)75 XPath (javax.xml.xpath.XPath)59 XPathExpression (javax.xml.xpath.XPathExpression)40 Document (org.w3c.dom.Document)34 NodeList (org.w3c.dom.NodeList)34 XPathExpressionException (javax.xml.xpath.XPathExpressionException)26 DocumentBuilder (javax.xml.parsers.DocumentBuilder)24 Node (org.w3c.dom.Node)24 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)22 InputSource (org.xml.sax.InputSource)16 Test (org.junit.Test)15 IOException (java.io.IOException)13 PBXNativeTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXNativeTarget)11 PBXTarget (com.facebook.buck.apple.xcode.xcodeproj.PBXTarget)11 ImmutableMap (com.google.common.collect.ImmutableMap)11 Path (java.nio.file.Path)11 SAXException (org.xml.sax.SAXException)11 PBXFileReference (com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference)10 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)9 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)7