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);
}
}
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;
}
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);
}
}
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;
}
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);
}
Aggregations