Search in sources :

Example 51 with XPathExpression

use of javax.xml.xpath.XPathExpression in project oxTrust by GluuFederation.

the class LogDir method readConfig.

private List<LogDir> readConfig(String source) {
    List<LogDir> logDirs = new ArrayList<LogDir>();
    try {
        org.w3c.dom.Document document = xmlService.getXmlDocument(FileUtils.readFileToByteArray(new File(source)));
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression entriesXPath = xPath.compile("/entries/entry");
        NodeList list = (NodeList) entriesXPath.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            String prefix = null;
            String location = null;
            String extension = null;
            NodeList subList = node.getChildNodes();
            for (int j = 0; j < subList.getLength(); j++) {
                Node subNode = subList.item(j);
                String subNodeName = subNode.getNodeName();
                String subNodeValue = subNode.getTextContent();
                if (StringHelper.equalsIgnoreCase(subNodeName, "prefix")) {
                    prefix = subNodeValue;
                } else if (StringHelper.equalsIgnoreCase(subNodeName, "location")) {
                    location = subNodeValue;
                } else if (StringHelper.equalsIgnoreCase(subNodeName, "extension")) {
                    extension = subNodeValue;
                }
            }
            if (extension == null || extension.trim().equals("")) {
                extension = "log";
            }
            LogDir logDir = new LogDir(prefix, location, extension);
            logDirs.add(logDir);
            log.debug("Prefix: " + prefix + " Location: " + location);
        }
    } catch (Exception ex) {
        log.debug("Exception while reading configuration file: " + ex);
    }
    return logDirs;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) File(java.io.File)

Example 52 with XPathExpression

use of javax.xml.xpath.XPathExpression in project oxTrust by GluuFederation.

the class FilterService method parseFilters.

public void parseFilters(GluuSAMLTrustRelationship trustRelationship) throws SAXException, IOException, ParserConfigurationException, FactoryConfigurationError, XPathExpressionException {
    if (trustRelationship.getGluuSAMLMetaDataFilter() != null) {
        XPath xPath = XPathFactory.newInstance().newXPath();
        for (String filterXML : trustRelationship.getGluuSAMLMetaDataFilter()) {
            Document xmlDocument = xmlService.getXmlDocument(filterXML.getBytes());
            if (xmlDocument.getFirstChild().getAttributes().getNamedItem("xsi:type").getNodeValue().equals(VALIDATION_TYPE)) {
                MetadataFilter filter = createMetadataFilter("validation");
                XPathExpression contactCountXPath = xPath.compile("count(/MetadataFilter/ExtensionSchema)");
                int schemasNumber = Integer.parseInt(contactCountXPath.evaluate(xmlDocument));
                for (int i = 1; i <= schemasNumber; i++) {
                    contactCountXPath = xPath.compile("/MetadataFilter/ExtensionSchema[" + i + "]");
                    filter.getExtensionSchemas().add(contactCountXPath.evaluate(xmlDocument));
                }
                trustRelationship.getMetadataFilters().put("validation", filter);
                continue;
            }
            if (xmlDocument.getFirstChild().getAttributes().getNamedItem("xsi:type").getNodeValue().equals(ENTITY_ROLE_WHITE_LIST_TYPE)) {
                MetadataFilter filter = createMetadataFilter("entityRoleWhiteList");
                filter.setRemoveRolelessEntityDescriptors(Boolean.parseBoolean(xmlDocument.getFirstChild().getAttributes().getNamedItem("removeRolelessEntityDescriptors").getNodeValue()));
                filter.setRemoveEmptyEntitiesDescriptors(Boolean.parseBoolean(xmlDocument.getFirstChild().getAttributes().getNamedItem("removeEmptyEntitiesDescriptors").getNodeValue()));
                XPathExpression contactCountXPath = xPath.compile("count(/MetadataFilter/RetainedRole)");
                int schemasNumber = Integer.parseInt(contactCountXPath.evaluate(xmlDocument));
                for (int i = 1; i <= schemasNumber; i++) {
                    contactCountXPath = xPath.compile("/MetadataFilter/RetainedRole[" + i + "]");
                    filter.getRetainedRoles().add(contactCountXPath.evaluate(xmlDocument));
                }
                trustRelationship.getMetadataFilters().put("entityRoleWhiteList", filter);
                continue;
            }
            if (xmlDocument.getFirstChild().getAttributes().getNamedItem("xsi:type").getNodeValue().equals(VALID_UNTIL_REQUIRED_TYPE)) {
                MetadataFilter filter = createMetadataFilter("requiredValidUntil");
                filter.setMaxValidityInterval(Integer.parseInt(xmlDocument.getFirstChild().getAttributes().getNamedItem("maxValidityInterval").getNodeValue()));
                trustRelationship.getMetadataFilters().put("requiredValidUntil", filter);
                continue;
            }
            if (xmlDocument.getFirstChild().getAttributes().getNamedItem("xsi:type").getNodeValue().equals(SIGNATURE_VALIDATION_TYPE)) {
                MetadataFilter filter = createMetadataFilter("signatureValidation");
                filter.setFilterCertFileName(StringHelper.removePunctuation(trustRelationship.getInum()));
                trustRelationship.getMetadataFilters().put("signatureValidation", filter);
                continue;
            }
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) MetadataFilter(org.gluu.oxtrust.model.MetadataFilter) Document(org.w3c.dom.Document)

Example 53 with XPathExpression

use of javax.xml.xpath.XPathExpression in project galley by Commonjava.

the class XPathManager method getXPath.

public XPathExpression getXPath(final String path, final boolean cache) throws XPathExpressionException {
    XPathExpression expression = null;
    //        if ( cache )
    //        {
    //            synchronized ( this )
    //            {
    //                final WeakReference<XPathExpression> ref = xpaths.get( path );
    //                if ( ref != null )
    //                {
    //                    expression = ref.get();
    //                }
    //
    //                if ( expression == null )
    //                {
    //                    expression = xpath.compile( path );
    //                    xpaths.put( path, new WeakReference<XPathExpression>( expression ) );
    //                }
    //            }
    //        }
    //        else
    //        {
    expression = xpath.compile(path);
    return expression;
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression)

Example 54 with XPathExpression

use of javax.xml.xpath.XPathExpression in project uPortal by Jasig.

the class PositionManager method isNotReparentable.

/**
     * Return true if the passed in node or any downstream (higher index) siblings <strong>relative
     * to its destination location</strong> have moveAllowed="false".
     */
private static boolean isNotReparentable(NodeInfo ni, Element compViewParent, Element positionSet) {
    // This one is easy -- can't re-parent a node with dlm:moveAllowed=false
    if (ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
        return true;
    }
    try {
        /*
             *  Annoying to do in Java, but we need to find our own placeholder
             *  element in the positionSet
             */
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni.getId() + "']";
        final XPathExpression findPlaceholder = xpath.compile(findPlaceholderXpath);
        final NodeList findPlaceholderList = (NodeList) findPlaceholder.evaluate(positionSet, XPathConstants.NODESET);
        switch(findPlaceholderList.getLength()) {
            case 0:
                LOG.warn("Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
                return true;
            case 1:
                // This is healthy
                break;
            default:
                LOG.warn("More than one node found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
                return true;
        }
        // At last
        final Element placeholder = (Element) findPlaceholderList.item(0);
        for (Element nextPlaceholder = (Element) placeholder.getNextSibling(); // As long as we have a placeholder to look at
        nextPlaceholder != null; nextPlaceholder = (Element) nextPlaceholder.getNextSibling()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Considering whether node ''" + ni.getId() + "' is Reparentable;  subsequent sibling is:  " + nextPlaceholder.getAttribute("name"));
            }
            /*
                 * Next task:  we have to find the non-placeholder representation of
                 * the nextSiblingPlaceholder within the compViewParent
                 */
            final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder.getAttribute("name") + "']";
            final XPathExpression unmaskPlaceholder = xpath.compile(unmaskPlaceholderXpath);
            final NodeList unmaskPlaceholderList = (NodeList) unmaskPlaceholder.evaluate(compViewParent, XPathConstants.NODESET);
            switch(unmaskPlaceholderList.getLength()) {
                case 0:
                    // to a node that has been moved to this context (afaik)
                    continue;
                case 1:
                    final Element nextSibling = (Element) unmaskPlaceholderList.item(0);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Considering whether node ''" + ni.getId() + "' is Reparentable;  subsequent sibling '" + nextSibling.getAttribute("ID") + "' has dlm:moveAllowed=" + !nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false"));
                    }
                    // Need to perform some checks...
                    if (nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
                        /*
                             *  The following check is a bit strange;  it seems to verify
                             *  that the current NodeInfo and the nextSibling come from the
                             *  same fragment.  If they don't, the re-parenting is allowable.
                             *  I believe this check could only be unsatisfied in the case
                             *  of tabs.
                             */
                        Precedence p = Precedence.newInstance(nextSibling.getAttribute(Constants.ATT_FRAGMENT));
                        if (ni.getPrecedence().isEqualTo(p)) {
                            return true;
                        }
                    }
                    break;
                default:
                    LOG.warn("More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath + "\" in compViewParent");
                    return true;
            }
        }
    } catch (XPathExpressionException xpe) {
        throw new RuntimeException("Failed to evaluate XPATH", xpe);
    }
    // Re-parenting is "not disallowed" (double-negative less readable)
    return false;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) XPathFactory(javax.xml.xpath.XPathFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element)

Example 55 with XPathExpression

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

the class GmdTransformer method setMetacardDates.

private void setMetacardDates(Metacard metacard, final XstreamPathValueTracker pathValueTracker) {
    try (InputStream inputStream = getSourceInputStream()) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Unable to configure features on document builder.", e);
        }
        domFactory.setNamespaceAware(false);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(inputStream);
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression dataExpression = xPath.compile(GmdConstants.RESOURCE_DATE_PATH);
        NodeList dataList = (NodeList) dataExpression.evaluate(document, XPathConstants.NODESET);
        if (dataList != null && dataList.getLength() > 0) {
            List<String> dateList = new ArrayList<>();
            List<String> dateTypes = pathValueTracker.getAllValues(toPath(GmdConstants.CITATION_DATE_TYPE_PATH));
            for (int i = 0; i < dataList.getLength(); i++) {
                Node node = dataList.item(i);
                String datestring = node.getTextContent().trim().replaceAll(WHITE_SPACE_PATTER.pattern(), " ").replaceAll(NEW_LINE_PATTERN.pattern(), " ");
                String[] stringArray = datestring.split(" ");
                dateList.add(stringArray[0]);
            }
            if (CollectionUtils.isNotEmpty(dateList) && CollectionUtils.isNotEmpty(dateTypes) && dateList.size() == dateTypes.size()) {
                setDates(dateList, dateTypes, metacard);
            }
        }
    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        LOGGER.debug("Unable to parse dates in XML document.  Metacard Created / Effective / Modified dates will not be set.", e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InputStream(java.io.InputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

XPathExpression (javax.xml.xpath.XPathExpression)98 XPath (javax.xml.xpath.XPath)69 NodeList (org.w3c.dom.NodeList)56 Document (org.w3c.dom.Document)48 XPathExpressionException (javax.xml.xpath.XPathExpressionException)40 XPathFactory (javax.xml.xpath.XPathFactory)40 Node (org.w3c.dom.Node)38 DocumentBuilder (javax.xml.parsers.DocumentBuilder)24 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)19 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)13 HashMap (java.util.HashMap)13 Element (org.w3c.dom.Element)12 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 IOException (java.io.IOException)11 Path (java.nio.file.Path)11 PBXFileReference (com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference)10 InputSource (org.xml.sax.InputSource)9