use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.
the class MCRMODSLinkedMetadataTest method testUpdate.
@Test
public void testUpdate() throws IOException, URISyntaxException, MCRPersistenceException, MCRActiveLinkException, JDOMException, SAXException, MCRAccessException {
MCRObject seriesNew = new MCRObject(getResourceAsURL(seriesID + "-updated.xml").toURI());
MCRMetadataManager.update(seriesNew);
Document bookNew = MCRXMLMetadataManager.instance().retrieveXML(bookID);
XPathBuilder<Element> builder = new XPathBuilder<>("/mycoreobject/metadata/def.modsContainer/modsContainer/mods:mods/mods:relatedItem/mods:titleInfo/mods:title", Filters.element());
builder.setNamespace(MCRConstants.MODS_NAMESPACE);
XPathExpression<Element> seriesTitlePath = builder.compileWith(XPathFactory.instance());
Element titleElement = seriesTitlePath.evaluateFirst(bookNew);
Assert.assertNotNull("No title element in related item: " + new XMLOutputter(Format.getPrettyFormat()).outputString(bookNew), titleElement);
Assert.assertEquals("Title update from series was not promoted to book of series.", "Updated series title", titleElement.getText());
}
use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.
the class MCRMODSWrapperTest method setElement.
@Test
public void setElement() throws SAXParseException, IOException {
Element mods = loadMODSDocument().detachRootElement();
MCRMODSWrapper wrapper = new MCRMODSWrapper();
wrapper.setID("JUnit", 4711);
wrapper.setMODS(mods);
Map<String, String> attrMap = new HashMap<>();
attrMap.put("authorityURI", "http://mycore.de/classifications/mir_filetype.xml");
attrMap.put("displayLabel", "mir_filetype");
attrMap.put("valueURI", "http://mycore.de/classifications/mir_filetype.xml#excel");
wrapper.setElement("classification", "", attrMap);
Document mcrObjXml = wrapper.getMCRObject().createXML();
String checkXpathString = "//mods:mods/mods:classification[" + "@authorityURI='http://mycore.de/classifications/mir_filetype.xml' and " + "@displayLabel='mir_filetype' and " + "@valueURI='http://mycore.de/classifications/mir_filetype.xml#excel'" + "]";
XPathExpression<Element> xpathCheck = XPathFactory.instance().compile(checkXpathString, Filters.element(), null, MCRConstants.MODS_NAMESPACE);
assertTrue(xpathCheck.evaluate(mcrObjXml).size() > 0);
}
use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.
the class MCRMODSWrapperTest method testWrapMODSDocument.
/**
* Test method for {@link org.mycore.mods.MCRMODSWrapper#wrapMODSDocument(org.jdom2.Element, java.lang.String)}.
*/
@Test
public void testWrapMODSDocument() throws SAXParseException, URISyntaxException, JDOMException, IOException {
Document modsDoc = loadMODSDocument();
MCRObject mcrObj = MCRMODSWrapper.wrapMODSDocument(modsDoc.getRootElement(), "JUnit");
assertTrue("Generated MCRObject is not valid.", mcrObj.isValid());
Document mcrObjXml = mcrObj.createXML();
// check load from XML throws no exception
MCRObject mcrObj2 = new MCRObject(mcrObjXml);
mcrObjXml = mcrObj2.createXML();
XPathExpression<Element> xpathCheck = XPathFactory.instance().compile("//mods:mods", Filters.element(), null, MCRConstants.MODS_NAMESPACE);
assertEquals("Did not find mods data", 1, xpathCheck.evaluate(mcrObjXml).size());
}
use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.
the class MCRRestAPIObjectsHelper method listDerivateContentAsXML.
private static Document listDerivateContentAsXML(MCRDerivate derObj, String path, int depth, UriInfo info) throws IOException {
Document doc = new Document();
MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
root = MCRPath.toMCRPath(root.resolve(path));
if (depth == -1) {
depth = Integer.MAX_VALUE;
}
if (root != null) {
Element eContents = new Element("contents");
eContents.setAttribute("mycoreobject", derObj.getOwnerID().toString());
eContents.setAttribute("mycorederivate", derObj.getId().toString());
doc.addContent(eContents);
if (!path.endsWith("/")) {
path += "/";
}
MCRPath p = MCRPath.getPath(derObj.getId().toString(), path);
if (p != null && Files.exists(p)) {
Element eRoot = MCRPathXML.getDirectoryXML(p).getRootElement();
eContents.addContent(eRoot.detach());
createXMLForSubdirectories(p, eRoot, 1, depth);
}
// add href Attributes
String baseURL = MCRJerseyUtil.getBaseURL(info) + MCRConfiguration.instance().getString("MCR.RestAPI.v1.Files.URL.path");
baseURL = baseURL.replace("${mcrid}", derObj.getOwnerID().toString()).replace("${derid}", derObj.getId().toString());
XPathExpression<Element> xp = XPathFactory.instance().compile(".//child[@type='file']", Filters.element());
for (Element e : xp.evaluate(eContents)) {
String uri = e.getChildText("uri");
if (uri != null) {
int pos = uri.lastIndexOf(":/");
String subPath = uri.substring(pos + 2);
while (subPath.startsWith("/")) {
subPath = path.substring(1);
}
e.setAttribute("href", baseURL + subPath);
}
}
}
return doc;
}
use of org.jdom2.xpath.XPathExpression in project mycore by MyCoRe-Org.
the class MCRRestAPIClassifications method showObject.
/**
* returns a single classification object
*
* @param classID - the classfication id
* @param format
* Possible values are: json | xml (required)
* @param filter
* a ';'-separated list of ':'-separated key-value pairs, possible keys are:
* - lang - the language of the returned labels, if ommited all labels in all languages will be returned
* - root - an id for a category which will be used as root
* - nonempty - hide empty categories
* @param style
* a ';'-separated list of values, possible keys are:
* - 'checkboxtree' - create a json syntax which can be used as input for a dojo checkboxtree;
* - 'checked' - (together with 'checkboxtree') all checkboxed will be checked
* - 'jstree' - create a json syntax which can be used as input for a jsTree
* - 'opened' - (together with 'jstree') - all nodes will be opened
* - 'disabled' - (together with 'jstree') - all nodes will be disabled
* - 'selected' - (together with 'jstree') - all nodes will be selected
* @param request - the HTTPServletRequestObject
* @param callback - used in JSONP to wrap json result into a Javascript function named by callback parameter
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
@GET
// @Path("/id/{value}{format:(\\.[^/]+?)?}") -> working, but returns empty string instead of default value
@Path("/{classID}")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response showObject(@Context HttpServletRequest request, @PathParam("classID") String classID, @QueryParam("format") @DefaultValue("xml") String format, @QueryParam("filter") @DefaultValue("") String filter, @QueryParam("style") @DefaultValue("") String style, @QueryParam("callback") @DefaultValue("") String callback) throws MCRRestAPIException {
MCRRestAPIUtil.checkRestAPIAccess(request, MCRRestAPIACLPermission.READ, "/v1/classifications");
String rootCateg = null;
String lang = null;
boolean filterNonEmpty = false;
boolean filterNoChildren = false;
for (String f : filter.split(";")) {
if (f.startsWith("root:")) {
rootCateg = f.substring(5);
}
if (f.startsWith("lang:")) {
lang = f.substring(5);
}
if (f.startsWith("nonempty")) {
filterNonEmpty = true;
}
if (f.startsWith("nochildren")) {
filterNoChildren = true;
}
}
if (format == null || classID == null) {
return Response.serverError().status(Status.BAD_REQUEST).build();
// TODO response.sendError(HttpServletResponse.SC_NOT_FOUND,
// "Please specify parameters format and classid.");
}
try {
MCRCategory cl = DAO.getCategory(MCRCategoryID.rootID(classID), -1);
if (cl == null) {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Classification not found.", "There is no classification with the given ID."));
}
Document docClass = MCRCategoryTransformer.getMetaDataDocument(cl, false);
Element eRoot = docClass.getRootElement();
if (rootCateg != null) {
XPathExpression<Element> xpe = XPathFactory.instance().compile("//category[@ID='" + rootCateg + "']", Filters.element());
Element e = xpe.evaluateFirst(docClass);
if (e != null) {
eRoot = e;
} else {
throw new MCRRestAPIException(Response.Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_NOT_FOUND, "Category not found.", "The classfication does not contain a category with the given ID."));
}
}
if (filterNonEmpty) {
Element eFilter = eRoot;
if (eFilter.getName().equals("mycoreclass")) {
eFilter = eFilter.getChild("categories");
}
filterNonEmpty(docClass.getRootElement().getAttributeValue("ID"), eFilter);
}
if (filterNoChildren) {
eRoot.removeChildren("category");
}
String authHeader = MCRJSONWebTokenUtil.createJWTAuthorizationHeader(MCRJSONWebTokenUtil.retrieveAuthenticationToken(request));
if (FORMAT_JSON.equals(format)) {
String json = writeJSON(eRoot, lang, style);
// eventually: allow Cross Site Requests: .header("Access-Control-Allow-Origin", "*")
if (callback.length() > 0) {
return Response.ok(callback + "(" + json + ")").type("application/javascript; charset=UTF-8").build();
} else {
return Response.ok(json).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
}
}
if (FORMAT_XML.equals(format)) {
String xml = writeXML(eRoot, lang);
return Response.ok(xml).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, authHeader).build();
}
} catch (Exception e) {
LogManager.getLogger(this.getClass()).error("Error outputting classification", e);
// TODO response.sendError(HttpServletResponse.SC_NOT_FOUND, "Error outputting classification");
}
return null;
}
Aggregations