Search in sources :

Example 11 with XPath

use of org.jdom2.xpath.XPath in project mycore by MyCoRe-Org.

the class MCRLayoutUtilities method getPersonalNavigation.

public static org.w3c.dom.Document getPersonalNavigation() throws JDOMException, XPathExpressionException {
    Document navi = getNavi();
    DOMOutputter accessCleaner = new DOMOutputter(new AccessCleaningDOMOutputProcessor());
    org.w3c.dom.Document personalNavi = accessCleaner.output(navi);
    XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
    NodeList emptyGroups = (NodeList) xpath.evaluate("/navigation/menu/group[not(item)]", personalNavi, XPathConstants.NODESET);
    for (int i = 0; i < emptyGroups.getLength(); ++i) {
        org.w3c.dom.Element group = (org.w3c.dom.Element) emptyGroups.item(i);
        group.getParentNode().removeChild(group);
    }
    NodeList emptyMenu = (NodeList) xpath.evaluate("/navigation/menu[not(item or group)]", personalNavi, XPathConstants.NODESET);
    for (int i = 0; i < emptyMenu.getLength(); ++i) {
        org.w3c.dom.Element menu = (org.w3c.dom.Element) emptyMenu.item(i);
        menu.getParentNode().removeChild(menu);
    }
    NodeList emptyNodes = (NodeList) xpath.evaluate("//text()[normalize-space(.) = '']", personalNavi, XPathConstants.NODESET);
    for (int i = 0; i < emptyNodes.getLength(); ++i) {
        Node emptyTextNode = emptyNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }
    personalNavi.normalizeDocument();
    if (LOGGER.isDebugEnabled()) {
        try {
            String encoding = "UTF-8";
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            transformer.transform(new DOMSource(personalNavi), new StreamResult(bout));
            LOGGER.debug("personal navigation: {}", bout.toString(encoding));
        } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException | UnsupportedEncodingException e) {
            LOGGER.warn("Error while getting debug information.", e);
        }
    }
    return personalNavi;
}
Also used : XPath(javax.xml.xpath.XPath) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) DOMOutputter(org.jdom2.output.DOMOutputter) StreamResult(javax.xml.transform.stream.StreamResult) NodeList(org.w3c.dom.NodeList) Element(org.jdom2.Element) Node(org.w3c.dom.Node) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.jdom2.Document) TransformerException(javax.xml.transform.TransformerException)

Example 12 with XPath

use of org.jdom2.xpath.XPath in project mycore by MyCoRe-Org.

the class MCRDefaultAltoChangeApplier method applyChange.

@Override
public void applyChange(MCRAltoChangeSet changeSet) {
    String derivateID = changeSet.getDerivateID();
    changeSet.getWordChanges().stream().forEach(change -> {
        List<MCRAltoWordChange> list = fileChangeMap.computeIfAbsent(change.getFile(), (k) -> new ArrayList<>());
        list.add(change);
    });
    fileChangeMap.keySet().forEach(file -> {
        LOGGER.info("Open file {} to apply changes!", file);
        MCRPath altoFilePath = MCRPath.getPath(derivateID, file);
        if (!Files.exists(altoFilePath)) {
            LOGGER.warn("Could not find file {} which was referenced by alto change!", altoFilePath);
            throw new MCRException(new IOException("Alto-File " + altoFilePath + " does not exist"));
        }
        Document altoDocument = readALTO(altoFilePath);
        List<MCRAltoWordChange> wordChangesInThisFile = fileChangeMap.get(file);
        wordChangesInThisFile.stream().forEach(wordChange -> {
            String xpath = String.format(Locale.ROOT, "//alto:String[number(@HPOS)=number('%d') and number(@VPOS)=number('%d')]", wordChange.getHpos(), wordChange.getVpos());
            List<Element> wordToChange = XPathFactory.instance().compile(xpath, Filters.element(), null, MCRConstants.ALTO_NAMESPACE).evaluate(altoDocument);
            if (wordToChange.size() != 1) {
                LOGGER.warn("Found {} words to change.", wordToChange.size());
            }
            wordToChange.forEach(word -> {
                word.setAttribute("CONTENT", wordChange.getTo());
                word.setAttribute("WC", "1");
            });
        });
        storeALTO(altoFilePath, altoDocument);
    });
}
Also used : MCRAltoWordChange(org.mycore.viewer.alto.model.MCRAltoWordChange) MCRException(org.mycore.common.MCRException) Element(org.jdom2.Element) IOException(java.io.IOException) MCRPath(org.mycore.datamodel.niofs.MCRPath) Document(org.jdom2.Document)

Example 13 with XPath

use of org.jdom2.xpath.XPath in project mycore by MyCoRe-Org.

the class MCRXEditorTransformer method createEmptyDocumentFromXPath.

private void createEmptyDocumentFromXPath(String xPath) throws JaxenException, JDOMException {
    Element root = createRootElement(xPath);
    editorSession.setEditedXML(new Document(root));
    editorSession.setBreakpoint("Starting with empty XML document");
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 14 with XPath

use of org.jdom2.xpath.XPath in project mycore by MyCoRe-Org.

the class MCRBinding method bind.

private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException {
    this.xPath = xPath;
    Map<String, Object> variables = buildXPathVariables();
    XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(), variables, MCRConstants.getStandardNamespaces());
    boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes()));
    for (Object boundNode : boundNodes) if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document))
        throw new RuntimeException("XPath MUST only bind either element, attribute or document nodes: " + xPath);
    LOGGER.debug("Bind to {} selected {} node(s)", xPath, boundNodes.size());
    if (boundNodes.isEmpty() && buildIfNotExists) {
        MCRNodeBuilder builder = new MCRNodeBuilder(variables);
        Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode()));
        LOGGER.debug("Bind to {} generated node {}", xPath, MCRXPathBuilder.buildXPath(built));
        boundNodes.add(built);
        trackNodeCreated(builder.getFirstNodeBuilt());
    }
}
Also used : MCRNodeBuilder(org.mycore.common.xml.MCRNodeBuilder) MCRRemoveAttribute(org.mycore.frontend.xeditor.tracker.MCRRemoveAttribute) MCRAddedAttribute(org.mycore.frontend.xeditor.tracker.MCRAddedAttribute) Attribute(org.jdom2.Attribute) MCRAddedElement(org.mycore.frontend.xeditor.tracker.MCRAddedElement) MCRRemoveElement(org.mycore.frontend.xeditor.tracker.MCRRemoveElement) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 15 with XPath

use of org.jdom2.xpath.XPath in project mycore by MyCoRe-Org.

the class MCRSubselectReturnTarget method bindsFirstOrMoreThanOneElement.

private boolean bindsFirstOrMoreThanOneElement(String xPath, MCREditorSession session) throws JaxenException, JDOMException {
    MCRBinding binding = new MCRBinding(xPath, false, session.getRootBinding());
    boolean result = (binding.getBoundNode() instanceof Element) && !xPath.endsWith("]");
    binding.detach();
    return result;
}
Also used : Element(org.jdom2.Element) MCRBinding(org.mycore.frontend.xeditor.MCRBinding)

Aggregations

Element (org.jdom2.Element)24 Document (org.jdom2.Document)11 IOException (java.io.IOException)4 Attribute (org.jdom2.Attribute)4 JDOMException (org.jdom2.JDOMException)4 MCRException (org.mycore.common.MCRException)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 URISyntaxException (java.net.URISyntaxException)3 Text (org.jdom2.Text)3 XPath (org.jdom2.xpath.XPath)3 XPathFactory (org.jdom2.xpath.XPathFactory)3 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)3 MCRObject (org.mycore.datamodel.metadata.MCRObject)3 XmlException (gov.cms.qpp.conversion.xml.XmlException)2 List (java.util.List)2 TransformerException (javax.xml.transform.TransformerException)2 XPath (javax.xml.xpath.XPath)2 MCRPersistenceException (org.mycore.common.MCRPersistenceException)2 MCRPath (org.mycore.datamodel.niofs.MCRPath)2 MCRPersistentIdentifierException (org.mycore.pi.exceptions.MCRPersistentIdentifierException)2