use of org.jdom2.filter.Filter 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;
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRURNObjectXPathMetadataManager method removeIdentifier.
@Override
public void removeIdentifier(MCRDNBURN identifier, MCRBase obj, String additional) {
String xpath = getProperties().get("Xpath");
Document xml = obj.createXML();
XPathFactory xPathFactory = XPathFactory.instance();
XPathExpression<Element> xp = xPathFactory.compile(xpath, Filters.element());
List<Element> elements = xp.evaluate(xml);
elements.stream().filter(element -> element.getTextTrim().equals(identifier.asString())).forEach(Element::detach);
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRIdentifierXSLUtils method getPIServiceInformation.
/**
* Gets all available services which are configured.
* e.g.
* <ul>
* <li><service id="service1" inscribed="false" permission="true" type="urn" /></li>
* <li><service id="service2" inscribed="true" permission="false" type="doi" /></li>
* </ul>
*
* @param objectID the object
* @return a Nodelist
* @throws JDOMException
*/
public static NodeList getPIServiceInformation(String objectID) throws JDOMException {
Element e = new Element("list");
MCRBase obj = MCRMetadataManager.retrieve(MCRObjectID.getInstance(objectID));
MCRConfiguration.instance().getPropertiesMap("MCR.PI.Registration.").keySet().stream().map(s -> s.substring("MCR.PI.Registration.".length())).filter(id -> !id.contains(".")).map((serviceID) -> MCRPIRegistrationServiceManager.getInstance().getRegistrationService(serviceID)).map((rs -> {
Element service = new Element("service");
service.setAttribute("id", rs.getRegistrationServiceID());
// Check if the inscriber of this service can read a PI
try {
if (rs.getMetadataManager().getIdentifier(obj, "").isPresent()) {
service.setAttribute("inscribed", "true");
} else {
service.setAttribute("inscribed", "false");
}
} catch (MCRPersistentIdentifierException e1) {
LOGGER.warn("Error happened while try to read PI from object: {}", objectID, e1);
service.setAttribute("inscribed", "false");
}
// rights
String permission = "register-" + rs.getRegistrationServiceID();
Boolean canRegister = MCRAccessManager.checkPermission(objectID, "writedb") && MCRAccessManager.checkPermission(obj.getId(), permission);
service.setAttribute("permission", canRegister.toString().toLowerCase(Locale.ROOT));
// add the type
service.setAttribute("type", rs.getType());
return service;
})).forEach(e::addContent);
return new DOMOutputter().output(e).getElementsByTagName("service");
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRAttributeValueFilter method filter.
public Element filter(Object arg0) {
Element e = super.filter(arg0);
if (e == null) {
return null;
}
String value = e.getAttributeValue(attrKey, ns);
return (value != null && value.equals(attrValue)) ? e : null;
}
use of org.jdom2.filter.Filter in project mycore by MyCoRe-Org.
the class MCRErrorServlet method generateErrorPage.
protected void generateErrorPage(HttpServletRequest request, HttpServletResponse response, String msg, Throwable ex, Integer statusCode, Class<? extends Throwable> exceptionType, String requestURI, String servletName) throws IOException, TransformerException, SAXException {
boolean exceptionThrown = ex != null;
LOGGER.log(exceptionThrown ? Level.ERROR : Level.WARN, MessageFormat.format("{0}: Error {1} occured. The following message was given: {2}", requestURI, statusCode, msg), ex);
String style = MCRFrontendUtil.getProperty(request, "XSL.Style").filter("xml"::equals).orElse("default");
request.setAttribute("XSL.Style", style);
Document errorDoc = buildErrorPage(msg, statusCode, requestURI, exceptionType, servletName, ex);
final String requestAttr = "MCRErrorServlet.generateErrorPage";
if (!response.isCommitted() && request.getAttribute(requestAttr) == null) {
if (statusCode != null) {
response.setStatus(statusCode);
} else {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
request.setAttribute(requestAttr, msg);
boolean currentSessionActive = MCRSessionMgr.hasCurrentSession();
boolean sessionFromRequest = setCurrentSession(request);
MCRSession session = null;
try {
session = MCRSessionMgr.getCurrentSession();
boolean openTransaction = session.isTransactionActive();
if (!openTransaction) {
session.beginTransaction();
}
try {
setWebAppBaseURL(session, request);
LAYOUT_SERVICE.doLayout(request, response, new MCRJDOMContent(errorDoc));
} finally {
if (!openTransaction)
session.commitTransaction();
}
} finally {
if (exceptionThrown || !currentSessionActive) {
MCRSessionMgr.releaseCurrentSession();
}
if (!sessionFromRequest) {
// new session created for transaction
session.close();
}
}
} else {
if (request.getAttribute(requestAttr) != null) {
LOGGER.warn("Could not send error page. Generating error page failed. The original message:\n{}", request.getAttribute(requestAttr));
} else {
LOGGER.warn("Could not send error page. Response allready commited. The following message was given:\n{}", msg);
}
}
}
Aggregations