Search in sources :

Example 71 with XPath

use of javax.xml.xpath.XPath in project coprhd-controller by CoprHD.

the class RemoteRepository method getVersionsWithMetadataCatalog.

private Map<SoftwareVersion, List<SoftwareVersion>> getVersionsWithMetadataCatalog(String catalogString) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, InvalidSoftwareVersionException, MalformedURLException, RemoteRepositoryException {
    Map<SoftwareVersion, List<SoftwareVersion>> map = new HashMap<SoftwareVersion, List<SoftwareVersion>>();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(catalogString)));
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList fileList = (NodeList) xPath.compile("//File").evaluate(doc, XPathConstants.NODESET);
    for (int fileItr = 0; fileItr < fileList.getLength(); fileItr++) {
        Node fileNode = fileList.item(fileItr);
        Element element = (Element) fileNode;
        Node nameNode = element.getAttributeNode("Name");
        if (null != nameNode) {
            String fileName = nameNode.getNodeValue();
            if (fileName.endsWith(SOFTWARE_IMAGE_SUFFIX)) {
                String fileVersion = fileName.replace(SOFTWARE_IMAGE_SUFFIX, "");
                Node catalogInfoNode = element.getAttributeNode("CatalogInfo");
                String catalogInfo = catalogInfoNode.getNodeValue();
                SoftwareVersion tempVersion = new SoftwareVersion(fileVersion);
                List<SoftwareVersion> tempList = new ArrayList<SoftwareVersion>();
                if (!catalogInfo.equals("")) {
                    String upgradeFromInfoRaw = null;
                    for (String s : catalogInfo.split(",")) {
                        // key-value pairs are separated by comma
                        if (s.startsWith("upgradeFromVersions=")) {
                            upgradeFromInfoRaw = s;
                            break;
                        }
                    }
                    // only need the value
                    String upgradeFromInfo = upgradeFromInfoRaw.split("=")[1];
                    for (String versionStr : upgradeFromInfo.split(";")) {
                        // versions are separated by semicolon
                        tempList.add(new SoftwareVersion(versionStr));
                    }
                }
                map.put(tempVersion, tempList);
            }
        }
    }
    return map;
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) SoftwareVersion(com.emc.storageos.coordinator.client.model.SoftwareVersion) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 72 with XPath

use of javax.xml.xpath.XPath in project coprhd-controller by CoprHD.

the class RemoteRepository method finInstallableVersionsFromCatalogRepo.

private List<SoftwareVersion> finInstallableVersionsFromCatalogRepo(String catalogString, List<SoftwareVersion> newVersionList, List<SoftwareVersion> localVersions) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, InvalidSoftwareVersionException, MalformedURLException, RemoteRepositoryException {
    List<SoftwareVersion> validVersions = new ArrayList<SoftwareVersion>();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new InputSource(new StringReader(catalogString)));
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList fileList = (NodeList) xPath.compile("//File").evaluate(doc, XPathConstants.NODESET);
    OUTER: for (int fileItr = 0; fileItr < fileList.getLength(); fileItr++) {
        Node fileNode = fileList.item(fileItr);
        Element element = (Element) fileNode;
        Node nameNode = element.getAttributeNode("Name");
        if (null != nameNode) {
            String fileName = nameNode.getNodeValue();
            if (fileName.endsWith(SOFTWARE_IMAGE_SUFFIX)) {
                String fileVersion = fileName.replace(SOFTWARE_IMAGE_SUFFIX, "");
                SoftwareVersion tempVersion = new SoftwareVersion(fileVersion);
                if (newVersionList.contains(tempVersion)) {
                    Node catalogInfoNode = element.getAttributeNode("CatalogInfo");
                    String catalogInfo = catalogInfoNode.getNodeValue();
                    if (catalogInfo.equals("")) {
                        // Ignore the version that doesn't have the upgradeFromVersion metadata
                        continue;
                    }
                    // key-value pairs are separated by comma
                    String upgradeFromInfoRaw = catalogInfo.split(",")[0];
                    // only need the value
                    String upgradeFromInfo = upgradeFromInfoRaw.split("=")[1];
                    for (String versionStr : upgradeFromInfo.split(";")) {
                        // versions are separated by semicolon
                        for (SoftwareVersion v : localVersions) {
                            if (new SoftwareVersion(versionStr).weakEquals(v)) {
                                // wild card is used in the upgradeFromVersions list,
                                // need use weakEquals
                                validVersions.add(tempVersion);
                                continue OUTER;
                            }
                        }
                    }
                }
            }
        }
    }
    return validVersions;
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) SoftwareVersion(com.emc.storageos.coordinator.client.model.SoftwareVersion) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 73 with XPath

use of javax.xml.xpath.XPath in project ddf by codice.

the class CswTestCommons method getMetacardIdFromCswInsertResponse.

public static String getMetacardIdFromCswInsertResponse(Response response) throws IOException, XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    String idPath = "//*[local-name()='identifier']/text()";
    InputSource xml = new InputSource(IOUtils.toInputStream(response.getBody().asString(), UTF_8.name()));
    return xPath.compile(idPath).evaluate(xml);
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource)

Example 74 with XPath

use of javax.xml.xpath.XPath in project admin-console-beta by connexta.

the class OpenSearchSourceUtils method verifyOpenSearchCapabilities.

/**
     * Verifies that an endpoint given by the URL (and credentials) has OpenSearch capabilities.
     *
     * Possible Error Codes to be returned
     * - {@link org.codice.ddf.admin.common.report.message.DefaultMessages#CANNOT_CONNECT}
     * - {@link org.codice.ddf.admin.common.report.message.DefaultMessages#UNAUTHORIZED}
     * - {@link org.codice.ddf.admin.common.report.message.DefaultMessages#UNKNOWN_ENDPOINT}
     *
     * @param urlField endpoint url to verify
     * @param creds optional credentials for authentication
     * @return an empty {@code Report} on success, otherwise a {@code Report} containing {@link org.codice.ddf.admin.common.report.message.ErrorMessage}s
     */
protected ReportImpl verifyOpenSearchCapabilities(UrlField urlField, CredentialsField creds) {
    ReportWithResultImpl<String> responseBodyResult = requestUtils.sendGetRequest(urlField, creds, GET_CAPABILITIES_PARAMS);
    if (responseBodyResult.containsErrorMsgs()) {
        return responseBodyResult;
    }
    Document capabilitiesXml;
    try {
        capabilitiesXml = createDocument(responseBodyResult.result());
    } catch (Exception e) {
        LOGGER.debug("Failed to read response from OpenSearch endpoint.");
        responseBodyResult.addArgumentMessage(unknownEndpointError(urlField.path()));
        return responseBodyResult;
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        if ((Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(capabilitiesXml, XPathConstants.BOOLEAN)) {
            return responseBodyResult;
        }
    } catch (XPathExpressionException e) {
        LOGGER.debug("Failed to compile OpenSearch totalResults XPath.");
        responseBodyResult.addArgumentMessage(unknownEndpointError(urlField.path()));
        return responseBodyResult;
    }
    responseBodyResult.addArgumentMessage(unknownEndpointError(urlField.path()));
    return responseBodyResult;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Document(org.w3c.dom.Document) SourceUtilCommons.createDocument(org.codice.ddf.admin.sources.commons.utils.SourceUtilCommons.createDocument) XPathExpressionException(javax.xml.xpath.XPathExpressionException)

Example 75 with XPath

use of javax.xml.xpath.XPath in project amos-ss17-alexa by c-i-ber.

the class XMLParser method getPrettyXML.

public static String getPrettyXML(String xmlString) {
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new ByteArrayInputStream(xmlString.getBytes("utf-8"))));
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        transformer.transform(new DOMSource(document), streamResult);
        return stringWriter.toString();
    } catch (ParserConfigurationException | XPathExpressionException | TransformerException | IOException | SAXException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) 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) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Aggregations

XPath (javax.xml.xpath.XPath)526 Document (org.w3c.dom.Document)254 NodeList (org.w3c.dom.NodeList)230 XPathFactory (javax.xml.xpath.XPathFactory)215 Node (org.w3c.dom.Node)171 XPathExpressionException (javax.xml.xpath.XPathExpressionException)159 XPathExpression (javax.xml.xpath.XPathExpression)142 DocumentBuilder (javax.xml.parsers.DocumentBuilder)125 Element (org.w3c.dom.Element)118 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)97 IOException (java.io.IOException)89 Test (org.junit.Test)80 InputSource (org.xml.sax.InputSource)59 File (java.io.File)57 SAXException (org.xml.sax.SAXException)57 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)51 ByteArrayInputStream (java.io.ByteArrayInputStream)44 ArrayList (java.util.ArrayList)44 InputStream (java.io.InputStream)39 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)37