List of usage examples for org.jdom2.filter Filters attribute
public static final Filter<Attribute> attribute()
From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java
License:Apache License
/** * Gets a list of selectable values from a single select from path. * @param singleSelectFromPath a path of the form <code>doc('mydoc')/mypath</code>, that points to the selectable values. * @return a {@link List} with the selectable values * @throws IOException If there are I/O errors while loading documents to select values from. * @throws JDOMException If there are problems at XML parsing while loading documents to select values from. *///from w w w . j a v a 2 s. com private List<String> getSelectableValuesFromSinglePath(String singleSelectFromPath) throws JDOMException, IOException { String[] selectFromDocAndPath = divideDocAndPath(singleSelectFromPath); File documentFile = new File(selectFromDocAndPath[0]); if (!documentFile.isAbsolute()) { documentFile = new File(this.pathToConfiguration, selectFromDocAndPath[0]); } Document documentToSelectFrom = loadJDOMDocumentFromFile(documentFile); List<String> gatheredPossibleValues = new ArrayList<>(); if (selectFromDocAndPath[1].matches(".+/@[^@/]+$")) { //It is an attribute path List<Attribute> selectableValuesQueryResult = performJAXENXPath(selectFromDocAndPath[1], documentToSelectFrom, Filters.attribute(), xpathNamespaces); for (int i = 0; i < selectableValuesQueryResult.size(); i++) { gatheredPossibleValues.add(selectableValuesQueryResult.get(i).getValue()); } } else { //It is a text path List<Text> selectableValuesQueryResult = performJAXENXPath(selectFromDocAndPath[1], documentToSelectFrom, Filters.text(), xpathNamespaces); for (int i = 0; i < selectableValuesQueryResult.size(); i++) { gatheredPossibleValues.add(selectableValuesQueryResult.get(i).getTextNormalize()); } } return gatheredPossibleValues; }
From source file:com.medvision360.medrecord.basex.MockLocatableParser.java
License:Creative Commons License
@Override public Locatable parse(InputStream is, String encoding) throws IOException { SAXBuilder builder = new SAXBuilder(); Document d;// w w w .jav a 2 s .c o m try { d = builder.build(new InputStreamReader(is, encoding)); } catch (JDOMException e) { throw new IOException(e); } HierObjectID uid = new HierObjectID(xpath(d, "//uid/value", Filters.element())); String archetypeNodeId = xpath(d, "//@archetype_node_id", Filters.attribute()); DvText name = new DvText(xpath(d, "//name/value", Filters.element())); Archetyped archetypeDetails = new Archetyped(xpath(d, "//archetype_id/value", Filters.element()), "1.4"); Locatable locatable = new MockLocatable(uid, archetypeNodeId, name, archetypeDetails, null, null, null); return locatable; }
From source file:com.xebialabs.overcast.support.libvirt.jdom.DiskXml.java
License:Apache License
/** * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of * disk elements and that the order is the same. *//* ww w . j ava2s . co m*/ public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { XPathFactory xpf = XPathFactory.instance(); XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); List<Element> disks = diskExpr.evaluate(domainXml); Iterator<StorageVol> cloneDiskIter = volumes.iterator(); for (Element disk : disks) { Attribute file = fileExpr.evaluateFirst(disk); StorageVol cloneDisk = cloneDiskIter.next(); file.setValue(cloneDisk.getPath()); } }
From source file:com.xebialabs.overcast.support.libvirt.jdom.DiskXml.java
License:Apache License
/** Get the disks connected to the domain. */ public static List<Disk> getDisks(Connect connect, Document domainXml) { try {/*from ww w . j a va 2 s . c o m*/ List<Disk> ret = Lists.newArrayList(); XPathFactory xpf = XPathFactory.instance(); XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); List<Element> disks = diskExpr.evaluate(domainXml); for (Element disk : disks) { Attribute type = typeExpr.evaluateFirst(disk); Attribute file = fileExpr.evaluateFirst(disk); Attribute dev = devExpr.evaluateFirst(disk); StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); } return ret; } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } }
From source file:ec.edu.cedia.redi.ldclient.provider.ScopusAuthorProvider.java
License:Apache License
/** * Parse each XML result of publications. Assings each publication resource * to its author. See//from ww w .j a va2 s .c o m * <a href="http://api.elsevier.com/documentation/SCOPUSSearchAPI.wadl">Scopus * Search API</a>. * * @param input * @param requestUrl * @param triples * @return list of publication resources * @throws DataRetrievalException */ private List<String> parseSearchPub(InputStream input, String requestUrl, final Model triples) throws DataRetrievalException { try { List<String> publications = new ArrayList<>(); ValueFactory vf = ValueFactoryImpl.getInstance(); String authorId = requestUrl.substring(requestUrl.indexOf("au-id(") + 6, requestUrl.indexOf(")&")); URI author = vf.createURI("http://api.elsevier.com/content/author/author_id/", authorId); final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(input); XPathExpression<Attribute> path = XPathFactory.instance().compile( "/atom:search-results/atom:entry/atom:link[@ref='self']/@href", Filters.attribute(), null, Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom")); List<Attribute> publicationsFound = path.evaluate(doc); for (int i = 0; i < publicationsFound.size(); i++) { String pubResource = publicationsFound.get(i).getValue(); triples.add(author, FOAF.PUBLICATIONS, vf.createURI(pubResource)); publications.add(pubResource + "?apiKey=" + apiKey + "&httpAccept=application/rdf%2Bxml"); } return publications; } catch (JDOMException | IOException ex) { throw new DataRetrievalException(ex); } }
From source file:io.appium.uiautomator2.core.AccessibilityNodeInfoDumper.java
License:Apache License
public NodeInfoList findNodes(String xpathSelector, boolean multiple) { try {/* w w w . j av a2 s . c om*/ XPATH.compile(xpathSelector, Filters.element()); } catch (IllegalArgumentException e) { throw new InvalidSelectorException(e); } try { RESOURCES_GUARD.acquire(); } catch (InterruptedException e) { throw new UiAutomator2Exception(e); } uiElementsMapping = new SparseArray<>(); try (InputStream xmlStream = toStream()) { final Document document = SAX_BUILDER.build(xmlStream); final XPathExpression<org.jdom2.Attribute> expr = XPATH .compile(String.format("(%s)/@%s", xpathSelector, UI_ELEMENT_INDEX), Filters.attribute()); final NodeInfoList matchedNodes = new NodeInfoList(); final long timeStarted = SystemClock.uptimeMillis(); for (org.jdom2.Attribute uiElementId : expr.evaluate(document)) { final UiElement uiElement = uiElementsMapping.get(uiElementId.getIntValue()); if (uiElement == null || uiElement.getNode() == null) { continue; } matchedNodes.add(uiElement.getNode()); if (!multiple) { break; } } Logger.debug(String.format("Took %sms to retrieve %s matches for '%s' XPath query", SystemClock.uptimeMillis() - timeStarted, matchedNodes.size(), xpathSelector)); return matchedNodes; } catch (JDOMParseException e) { throw new UiAutomator2Exception(String.format( "%s. " + "Try changing the '%s' driver setting to 'true' in order to workaround the problem.", e.getMessage(), Settings.NORMALIZE_TAG_NAMES.toString()), e); } catch (Exception e) { throw new UiAutomator2Exception(e); } finally { performCleanup(); RESOURCES_GUARD.release(); } }
From source file:org.mycore.datamodel.metadata.validator.MCREditorOutValidator.java
License:Open Source License
/** * tries to generate a valid MCRObject as JDOM Document. * /*from w w w . j a v a2 s .c om*/ * @return MCRObject */ public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException { MCRObject obj; // load the JDOM object XPathFactory.instance().compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute()).evaluate(input) .forEach(Attribute::detach); try { byte[] xml = new MCRJDOMContent(input).asByteArray(); obj = new MCRObject(xml, true); } catch (SAXParseException e) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); LOGGER.warn("Failure while parsing document:\n" + xout.outputString(input)); throw e; } Date curTime = new Date(); obj.getService().setDate("modifydate", curTime); // return the XML tree input = obj.createXML(); return input; }
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. //from www . j a va2 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:unidue.ub.statistics.resolver.JOPResolver.java
/** * Queries the JOP brief xml service to get the total status of electronic availability, and adds that state * to the ElectronicData element. In case total access is given by combining multiple licenses with state '3' * (partially licensed), only the brief response contains the information that the combined license covers * the complete journal, if so. // w w w .ja v a 2 s . c o m */ private void addElectronicDataTotalState(Element fullXML, String query) throws SAXException, IOException, JDOMException { Element briefData = getJOPDataFromRemoteServer(query, jopBriefURL); XPathExpression<Attribute> xPath = XPathFactory.instance().compile(xpathToElectronicDataState, Filters.attribute()); Attribute state = xPath.evaluateFirst(briefData); LOGGER.debug("electronic availability total state from brief xml response is " + state.getValue()); Element electronicData = XPathFactory.instance().compile(xpathToElectronicDataFull, Filters.element()) .evaluateFirst(fullXML); state.detach(); electronicData.setAttribute(state); }
From source file:us.xwhite.dvd.endpoint.RentalEndpoint.java
License:Apache License
public RentalEndpoint(RentalService rentalService) throws JDOMException, XPathFactoryConfigurationException, XPathExpressionException { this.rentalService = rentalService; Namespace namespace = Namespace.getNamespace("sakila", NAMESPACE_URI); XPathFactory xPathFactory = XPathFactory.instance(); this.storeId = xPathFactory.compile("//@storeId", Filters.attribute(), null, namespace); this.filmTitles = xPathFactory.compile("//@title", Filters.attribute(), null, namespace); }