List of usage examples for org.jdom2.xpath XPathFactory instance
public static final XPathFactory instance()
From source file:org.mycore.mods.MCRMODSWrapper.java
License:Open Source License
private XPathExpression<Element> buildXPath(String xPath) throws JDOMException { return XPathFactory.instance().compile(xPath, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE); }
From source file:org.mycore.oai.classmapping.MCRClassificationMappingEventHandler.java
License:Open Source License
private void createMapping(MCRObject obj) { MCRMetaElement mappings = obj.getMetadata().getMetadataElement("mappings"); if (mappings != null) { oldMappings = mappings.clone();//from w w w. ja v a 2s.c om obj.getMetadata().removeMetadataElement("mappings"); } Element currentClassElement = null; try { Document doc = new Document((Element) obj.getMetadata().createXML().detach()); XPathExpression<Element> classElementPath = XPathFactory.instance().compile("//*[@categid]", Filters.element()); List<Element> classList = classElementPath.evaluate(doc); if (classList.size() > 0) { mappings = new MCRMetaElement(); mappings.setTag("mappings"); mappings.setClass(MCRMetaClassification.class); mappings.setHeritable(false); mappings.setNotInherit(true); obj.getMetadata().setMetadataElement(mappings); } for (Element classElement : classList) { currentClassElement = classElement; MCRCategory categ = DAO.getCategory(new MCRCategoryID(classElement.getAttributeValue("classid"), classElement.getAttributeValue("categid")), 0); addMappings(mappings, categ); } } catch (Exception je) { if (currentClassElement == null) { LOGGER.error("Error while finding classification elements", je); } else { LOGGER.error("Error while finding classification elements for " + new XMLOutputter().outputString(currentClassElement), je); } } finally { if (mappings == null || mappings.size() == 0) { obj.getMetadata().removeMetadataElement("mappings"); } } }
From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java
License:Open Source License
/** * returns a single classification object * * @param classID - the classfication id * @param format//from w w w .jav a 2 s . c om * 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 callback used for JSONP - wrap json result into a Javascript function named by callback parameter * @return a Jersey Response object */ @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(@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) { 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) { return MCRRestAPIError.create(Response.Status.BAD_REQUEST, "Classification not found.", "There is no classification with the given ID.").createHttpResponse(); } 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 { return MCRRestAPIError .create(Response.Status.BAD_REQUEST, "Category not found.", "The classfication does not contain a category with the given ID.") .createHttpResponse(); } } 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"); } 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").build(); } } if (FORMAT_XML.equals(format)) { String xml = writeXML(eRoot, lang); return Response.ok(xml).type("application/xml; charset=UTF-8").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; }
From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java
License:Open Source License
/** * Output xml/*from w w w . ja v a 2 s. co m*/ * @param eRoot - the root element * @param lang - the language which should be filtered or null for no filter * @return a string representation of the XML * @throws IOException */ private static String writeXML(Element eRoot, String lang) throws IOException { StringWriter sw = new StringWriter(); if (lang != null) { // <label xml:lang="en" text="part" /> XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']", Filters.element(), null, Namespace.XML_NAMESPACE); for (Element e : xpE.evaluate(eRoot)) { e.getParentElement().removeContent(e); } } XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); Document docOut = new Document(eRoot.detach()); xout.output(docOut, sw); return sw.toString(); }
From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java
License:Open Source License
private static Element listDerivateContent(MCRObject mcrObj, MCRDerivate derObj, String deriPath, UriInfo info) throws IOException { Element eContents = new Element("contents"); eContents.setAttribute("mycoreobject", mcrObj.getId().toString()); eContents.setAttribute("derivate", derObj.getId().toString()); if (!deriPath.endsWith("/")) { deriPath += "/"; }/*w w w. j av a2 s . c o m*/ MCRPath p = MCRPath.getPath(derObj.getId().toString(), deriPath); if (p != null) { eContents.addContent(MCRPathXML.getDirectoryXML(p).getRootElement().detach()); } String baseURL = MCRJerseyUtil.getBaseURL(info) + MCRConfiguration.instance().getString("MCR.RestAPI.v1.Files.URL.path"); baseURL = baseURL.replace("${mcrid}", mcrObj.getId().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 path = uri.substring(pos + 2); while (path.startsWith("/")) { path = path.substring(1); } e.setAttribute("href", baseURL + path); } } return eContents; }
From source file:org.mycore.urn.events.MCRURNEventHandler.java
License:Open Source License
/** * Handles object created events. This method updates the urn store. * The urn is retrieved from object metadata with an XPath expression which can be configured by properties * MCR.Persistence.URN.XPath.{type} or as a default MCR.Persistence.URN.XPath * * @param evt//from w ww.j av a 2s. com * the event that occurred * @param obj * the MCRObject that caused the event */ @Override protected final void handleObjectCreated(MCREvent evt, MCRObject obj) { try { MCRBaseContent content = new MCRBaseContent(obj); Document doc = content.asXML(); String type = obj.getId().getTypeId(); MCRConfiguration conf = MCRConfiguration.instance(); String xPathString = conf.getString("MCR.Persistence.URN.XPath." + type, conf.getString("MCR.Persistence.URN.XPath", "")); if (!xPathString.isEmpty()) { String urn = null; XPathExpression<Object> xpath = XPathFactory.instance().compile(xPathString, Filters.fpassthrough(), null, MCRConstants.getStandardNamespaces()); Object o = xpath.evaluateFirst(doc); if (o instanceof Attribute) { urn = ((Attribute) o).getValue(); } //element or text node else if (o instanceof Content) { urn = ((Content) o).getValue(); } if (urn != null) { if (MCRURNManager.getURNforDocument(obj.getId().toString()) == null) { MCRURNManager.assignURN(urn, obj.getId().toString()); } else { if (!MCRURNManager.getURNforDocument(obj.getId().toString()).equals(urn)) { LOGGER.warn("URN in metadata " + urn + "isn't equals with registered URN " + MCRURNManager.getURNforDocument(obj.getId().toString()) + ", please check!"); } } } else { if (MCRURNManager.hasURNAssigned(obj.getId().toString())) { MCRURNManager.removeURNByObjectID(obj.getId().toString()); } } } } catch (Exception ex) { LOGGER.error("Could not store / update the urn for object with id " + obj.getId().toString() + " into the database", ex); } }
From source file:org.mycore.user2.MCRUserServlet.java
License:Open Source License
/** * Handles MCRUserServlet?action=save&id={userID}. * This is called by user-editor.xml editor form to save the * changed user data from editor submission. Redirects to * show user data afterwards. //ww w.ja v a2 s. c o m */ private void saveUser(HttpServletRequest req, HttpServletResponse res) throws Exception { MCRUser currentUser = MCRUserManager.getCurrentUser(); if (!checkUserIsNotNull(res, currentUser, null)) { return; } boolean hasAdminPermission = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION); boolean allowed = hasAdminPermission || MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION); if (!allowed) { String msg = MCRTranslation.translate("component.user2.UserServlet.noCreatePermission"); res.sendError(HttpServletResponse.SC_FORBIDDEN, msg); return; } Document doc = (Document) (req.getAttribute("MCRXEditorSubmission")); Element u = doc.getRootElement(); String userName = u.getAttributeValue("name"); String realmID = MCRRealmFactory.getLocalRealm().getID(); if (hasAdminPermission) { realmID = u.getAttributeValue("realm"); } MCRUser user; boolean userExists = MCRUserManager.exists(userName, realmID); if (!userExists) { user = new MCRUser(userName, realmID); LOGGER.info("create new user " + userName + " " + realmID); // For new local users, set password String pwd = u.getChildText("password"); if ((pwd != null) && (pwd.trim().length() > 0) && user.getRealm().equals(MCRRealmFactory.getLocalRealm())) { MCRUserManager.updatePasswordHashToSHA256(user, pwd); } } else { user = MCRUserManager.getUser(userName, realmID); if (!(hasAdminPermission || currentUser.equals(user) || currentUser.equals(user.getOwner()))) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } XPathExpression<Attribute> hintPath = XPathFactory.instance().compile("password/@hint", Filters.attribute()); Attribute hintAttr = hintPath.evaluateFirst(u); String hint = hintAttr == null ? null : hintAttr.getValue(); if ((hint != null) && (hint.trim().length() == 0)) { hint = null; } user.setHint(hint); updateBasicUserInfo(u, user); if (hasAdminPermission) { boolean locked = "true".equals(u.getAttributeValue("locked")); user.setLocked(locked); boolean disabled = "true".equals(u.getAttributeValue("disabled")); user.setDisabled(disabled); Element o = u.getChild("owner"); if (o != null && !o.getAttributes().isEmpty()) { String ownerName = o.getAttributeValue("name"); String ownerRealm = o.getAttributeValue("realm"); MCRUser owner = MCRUserManager.getUser(ownerName, ownerRealm); if (!checkUserIsNotNull(res, owner, ownerName + "@" + ownerRealm)) { return; } user.setOwner(owner); } else { user.setOwner(null); } String validUntilText = u.getChildTextTrim("validUntil"); if (validUntilText == null || validUntilText.length() == 0) { user.setValidUntil(null); } else { String dateInUTC = validUntilText; if (validUntilText.length() == 10) { dateInUTC = convertToUTC(validUntilText, "yyyy-MM-dd"); } MCRISO8601Date date = new MCRISO8601Date(dateInUTC); user.setValidUntil(date.getDate()); } } else { // save read user of creator user.setRealm(MCRRealmFactory.getLocalRealm()); user.setOwner(currentUser); } Element gs = u.getChild("roles"); if (gs != null) { user.getSystemRoleIDs().clear(); user.getExternalRoleIDs().clear(); List<Element> groupList = (List<Element>) gs.getChildren("role"); for (Element group : groupList) { String groupName = group.getAttributeValue("name"); if (hasAdminPermission || currentUser.isUserInRole(groupName)) { user.assignRole(groupName); } else { LOGGER.warn("Current user " + currentUser.getUserID() + " has not the permission to add user to group " + groupName); } } } if (userExists) { MCRUserManager.updateUser(user); } else { MCRUserManager.createUser(user); } res.sendRedirect(res.encodeRedirectURL( "MCRUserServlet?action=show&id=" + URLEncoder.encode(user.getUserID(), "UTF-8"))); }
From source file:org.xflatdb.xflat.convert.converters.JAXBPojoConverter.java
License:Apache License
private XPathExpression<Object> makeIdSelector(Class<?> clazz) { IdAccessor accessor = IdAccessor.forClass(clazz); if (!accessor.hasId()) { return null; }/*from w w w . ja v a 2 s . c o m*/ Namespace ns = null; StringBuilder ret = new StringBuilder(clazz.getSimpleName()); XmlAttribute attribute = (XmlAttribute) accessor.getIdPropertyAnnotation(XmlAttribute.class); if (attribute != null) { ret.append("/@"); if (attribute.namespace() != null) { ns = Namespace.getNamespace("id", attribute.namespace()); ret.append(ns.getPrefix()).append(":"); } if (attribute.name() != null) { ret.append(attribute.name()); } else { ret.append(accessor.getIdPropertyName()); } } else { ret.append("/"); XmlElement element = (XmlElement) accessor.getIdPropertyAnnotation(XmlElement.class); if (element != null) { if (element.namespace() != null) { ns = Namespace.getNamespace("id", attribute.namespace()); ret.append(ns.getPrefix()).append(":"); } if (element.name() != null) { ret.append(element.name()); } else { ret.append(accessor.getIdPropertyName()); } } else { ret.append(accessor.getIdPropertyName()); } } if (ns == null) { return XPathFactory.instance().compile(ret.toString()); } return XPathFactory.instance().compile(ret.toString(), Filters.fpassthrough(), null, ns); }
From source file:org.xflatdb.xflat.db.IdAccessor.java
License:Apache License
private static XPathExpression<Object> getAlternateId(Id idPropertyAnnotation) { if (idPropertyAnnotation == null) return null; String expression = idPropertyAnnotation.value(); if (expression == null || "".equals(expression)) { return null; }/* w w w . ja v a 2 s .co m*/ List<Namespace> namespaces = null; if (idPropertyAnnotation.namespaces() != null && idPropertyAnnotation.namespaces().length > 0) { for (String ns : idPropertyAnnotation.namespaces()) { if (!ns.startsWith("xmlns:")) { continue; } int eqIndex = ns.indexOf("="); if (eqIndex < 0 || eqIndex >= ns.length() - 1) { continue; } String prefix = ns.substring(6, eqIndex); String url = ns.substring(eqIndex + 1); if (url.startsWith("\"") || url.startsWith("'")) url = url.substring(1); if (url.endsWith("\"") || url.endsWith("'")) url = url.substring(0, url.length() - 1); if ("".equals(prefix) || "".equals(url)) continue; if (namespaces == null) namespaces = new ArrayList<>(); namespaces.add(Namespace.getNamespace(prefix, url)); } } //compile it return XPathFactory.instance().compile(expression, Filters.fpassthrough(), null, namespaces == null ? Collections.EMPTY_LIST : namespaces); }
From source file:org.xflatdb.xflat.ShardsetConfig.java
License:Apache License
/** * Creates a ShardsetConfig with the minimum configuration necessary for static-range sharding. * The remainder can be left default or set as desired. * @param <U> The generic type of the ID property; all objects in the table must have the same property. * @param xpathProperty An XPath expression selecting a property of the data to shard on. * @param propertyClass The class of the property selected by the xpath expression. * @param intervalProvider A IntervalProvider that determines the static ranges for the * property, each range will have its own file. * @return A new shardset config./*from w w w .j av a 2s . c o m*/ */ public static <U> ShardsetConfig<U> by(String xpathProperty, Class<U> propertyClass, IntervalProvider<U> intervalProvider) { return by(XPathFactory.instance().compile(xpathProperty), propertyClass, intervalProvider); }