Search in sources :

Example 86 with JDOMException

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

the class MCRObjectCommands method xslt.

private static void xslt(String objectId, String xslFilePath, boolean force) throws IOException, JDOMException, SAXException, URISyntaxException, TransformerException, MCRPersistenceException, MCRAccessException, ParserConfigurationException {
    File xslFile = new File(xslFilePath);
    URL xslURL;
    if (!xslFile.exists()) {
        try {
            xslURL = new URL(xslFilePath);
        } catch (MalformedURLException e) {
            LOGGER.error("XSL parameter is not a file or URL: {}", xslFilePath);
            return;
        }
    } else {
        xslURL = xslFile.toURI().toURL();
    }
    MCRObjectID mcrId = MCRObjectID.getInstance(objectId);
    Document document = MCRXMLMetadataManager.instance().retrieveXML(mcrId);
    // do XSL transform
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setErrorListener(MCRErrorListener.getInstance());
    transformerFactory.setURIResolver(MCRURIResolver.instance());
    XMLReader xmlReader = MCRXMLParserFactory.getNonValidatingParser().getXMLReader();
    xmlReader.setEntityResolver(MCREntityResolver.instance());
    SAXSource styleSource = new SAXSource(xmlReader, new InputSource(xslURL.toURI().toString()));
    Transformer transformer = transformerFactory.newTransformer(styleSource);
    for (Entry<String, String> property : MCRConfiguration.instance().getPropertiesMap().entrySet()) {
        transformer.setParameter(property.getKey(), property.getValue());
    }
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    JDOMResult result = new JDOMResult();
    transformer.transform(new JDOMSource(document), result);
    Document resultDocument = Objects.requireNonNull(result.getDocument(), "Could not get transformation result");
    String originalName = document.getRootElement().getName();
    String resultName = resultDocument.getRootElement().getName();
    if (!force && !originalName.equals(resultName)) {
        LOGGER.error("{}: root name '{}' does not match result name '{}'.", objectId, originalName, resultName);
        return;
    }
    // update on diff
    if (MCRXMLHelper.deepEqual(document, resultDocument)) {
        return;
    }
    if (resultName.equals(MCRObject.ROOT_NAME)) {
        MCRMetadataManager.update(new MCRObject(resultDocument));
    } else if (resultName.equals(MCRDerivate.ROOT_NAME)) {
        MCRMetadataManager.update(new MCRDerivate(resultDocument));
    } else {
        LOGGER.error("Unable to transform '{}' because unknown result root name '{}'.", objectId, resultName);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) InputSource(org.xml.sax.InputSource) JDOMResult(org.jdom2.transform.JDOMResult) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) JDOMSource(org.jdom2.transform.JDOMSource) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) Document(org.jdom2.Document) URL(java.net.URL) SAXSource(javax.xml.transform.sax.SAXSource) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) File(java.io.File) XMLReader(org.xml.sax.XMLReader)

Example 87 with JDOMException

use of org.jdom2.JDOMException 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 88 with JDOMException

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

the class MCRWebsiteWriteProtection method getMessage.

public static org.w3c.dom.Document getMessage() throws JDOMException, IOException {
    Element config = getConfiguration();
    if (config == null) {
        return new DOMOutputter().output(new Document());
    } else {
        Element messageElem = config.getChild("message");
        Document message = new Document(messageElem.clone());
        return new DOMOutputter().output(message);
    }
}
Also used : DOMOutputter(org.jdom2.output.DOMOutputter) Element(org.jdom2.Element) Document(org.jdom2.Document)

Example 89 with JDOMException

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

the class MCRTransferPackageUtil method importObjectCLI.

/**
 * Same as {@link #importObject(Path, String)} but returns a list of derivates which
 * should be imported afterwards.
 *
 * @param targetDirectory
 *                the directory where the *.tar was unpacked
 * @param objectId
 *                object id to import
 * @throws JDOMException
 *                coulnd't parse the import order xml
 * @throws IOException
 *                when an I/O error prevents a document from being fully parsed
 * @throws MCRActiveLinkException
 *                if object is created (no real update), see {@link MCRMetadataManager#create(MCRObject)}
 * @throws MCRAccessException
 *                if write permission is missing or see {@link MCRMetadataManager#create(MCRObject)}
 */
public static List<String> importObjectCLI(Path targetDirectory, String objectId) throws JDOMException, IOException, MCRActiveLinkException, MCRAccessException {
    SAXBuilder sax = new SAXBuilder();
    Path targetXML = targetDirectory.resolve(CONTENT_DIRECTORY).resolve(objectId + ".xml");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(MessageFormat.format("Importing {0}", targetXML.toAbsolutePath().toString()));
    }
    Document objXML = sax.build(targetXML.toFile());
    MCRObject mcr = new MCRObject(objXML);
    mcr.setImportMode(true);
    List<String> derivates = new LinkedList<>();
    // one must copy the ids before updating the mcr objects
    for (MCRMetaLinkID id : mcr.getStructure().getDerivates()) {
        derivates.add(id.getXLinkHref());
    }
    // delete children & derivate -> will be added later
    mcr.getStructure().clearChildren();
    mcr.getStructure().clearDerivates();
    // update
    MCRMetadataManager.update(mcr);
    // return list of derivates
    return derivates;
}
Also used : Path(java.nio.file.Path) MCRPath(org.mycore.datamodel.niofs.MCRPath) SAXBuilder(org.jdom2.input.SAXBuilder) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) Document(org.jdom2.Document) LinkedList(java.util.LinkedList)

Example 90 with JDOMException

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

the class MCRFilesystemNode method setAdditionalData.

/**
 * Stores additional XML data for this node. The name of the data element is
 * used as unique key for storing data. If data with this name already
 * exists, it is overwritten.
 *
 * @param data
 *            the additional XML data to be saved
 * @throws IOException
 *             if the XML data can not be retrieved
 * @throws JDOMException
 *             if the XML data can not be parsed
 */
public void setAdditionalData(Element data) throws IOException, JDOMException {
    MCRFile dataFile = MCRFile.getRootFile(ID);
    Document doc;
    if (dataFile == null) {
        String name = "MCRFilesystemNode.additionalData";
        dataFile = new MCRFile(name, ID);
        doc = new Document(new Element("additionalData"));
    } else {
        doc = dataFile.getContentAsJDOM();
    }
    Element child = doc.getRootElement().getChild(data.getName());
    if (child != null) {
        child.detach();
    }
    doc.getRootElement().addContent(data.clone());
    dataFile.setContentFrom(doc);
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document)

Aggregations

Element (org.jdom2.Element)157 Document (org.jdom2.Document)116 JDOMException (org.jdom2.JDOMException)91 IOException (java.io.IOException)76 SAXBuilder (org.jdom2.input.SAXBuilder)70 Test (org.junit.Test)36 File (java.io.File)33 ArrayList (java.util.ArrayList)22 InputStream (java.io.InputStream)17 StringReader (java.io.StringReader)16 Attribute (org.jdom2.Attribute)16 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)14 SAXException (org.xml.sax.SAXException)14 HashMap (java.util.HashMap)13 XMLOutputter (org.jdom2.output.XMLOutputter)13 URL (java.net.URL)12 XmlFile (jmri.jmrit.XmlFile)12 List (java.util.List)11 MCRObject (org.mycore.datamodel.metadata.MCRObject)11 MCRException (org.mycore.common.MCRException)10