Java Code Examples for org.jdom2.xpath.XPathExpression#evaluateFirst()

The following examples show how to use org.jdom2.xpath.XPathExpression#evaluateFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiXmlExpandResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Execute expand templates request.
 * 
 * @param properties Properties defining request.
 * @return Expanded text.
 * @throws APIException Exception thrown by the API.
 */
@Override
public String executeExpandTemplates(
    Map<String, String> properties)
        throws APIException {
  try {
    XPathExpression<Element> xpaText = XPathFactory.instance().compile(
        "/api/expandtemplates/wikitext", Filters.element());
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);
    Element text = xpaText.evaluateFirst(root);
    return (text != null) ? text.getText() : null;
  } catch (JDOMException e) {
    log.error("Error expanding templates", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 2
Source File: MCRMODSLinkedMetadataTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example 3
Source File: ApiXmlParseResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Execute parse request.
 * 
 * @param properties Properties defining request.
 * @return Parsed text.
 * @throws APIException Exception thrown by the API.
 */
@Override
public String executeParse(
    Map<String, String> properties)
        throws APIException {
  try {
    XPathExpression<Element> xpaText = XPathFactory.instance().compile(
        "/api/parse/text", Filters.element());
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);
    Element text = xpaText.evaluateFirst(root);
    return (text != null) ? text.getText() : null;
  } catch (JDOMException e) {
    log.error("Error expanding templates", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 4
Source File: ApiXmlAllMessagesResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Execute message request.
 * 
 * @param properties Properties defining request.
 * @return Message.
 * @throws APIException Exception thrown by the API.
 */
@Override
public String executeMessage(
    Map<String, String> properties)
        throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve general information
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/allmessages/message", Filters.element());
    Element generalNode = xpa.evaluateFirst(root);
    if (generalNode != null) {
      return generalNode.getValue();
    }

    return null;
  } catch (JDOMException e) {
    log.error("Error loading messages", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 5
Source File: MCRAclEditorResource.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected InputStream transform(String xmlFile) throws Exception {
    InputStream guiXML = getClass().getResourceAsStream(xmlFile);
    if (guiXML == null) {
        throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).build());
    }
    SAXBuilder saxBuilder = new SAXBuilder();
    Document webPage = saxBuilder.build(guiXML);
    XPathExpression<Object> xpath = XPathFactory.instance().compile(
        "/MyCoReWebPage/section/div[@id='mycore-acl-editor2']");
    Object node = xpath.evaluateFirst(webPage);
    MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
    String lang = mcrSession.getCurrentLanguage();
    if (node != null) {
        Element mainDiv = (Element) node;
        mainDiv.setAttribute("lang", lang);
        String bsPath = MCRConfiguration2.getString("MCR.bootstrap.path").orElse("");
        if (!"".equals(bsPath)) {
            bsPath = MCRFrontendUtil.getBaseURL() + bsPath;
            Element item = new Element("link").setAttribute("href", bsPath).setAttribute("rel", "stylesheet")
                .setAttribute("type", "text/css");
            mainDiv.addContent(0, item);
        }
    }
    MCRContent content = MCRJerseyUtil.transform(webPage, request);
    return content.getInputStream();
}
 
Example 6
Source File: MCRLayoutUtilities.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns all labels of the ancestor axis for the given item within
 * navigation.xml
 *
 * @param item a navigation item
 * @return Label as String, like "labelRoot &gt; labelChild &gt;
 *         labelChildOfChild"
 */
public static String getAncestorLabels(Element item) {
    StringBuilder label = new StringBuilder();
    String lang = MCRSessionMgr.getCurrentSession().getCurrentLanguage().trim();
    XPathExpression<Element> xpath;
    Element ic = null;
    xpath = XPATH_FACTORY.compile("//.[@href='" + getWebpageID(item) + "']", Filters.element());
    ic = xpath.evaluateFirst(getNavi());
    while (ic.getName().equals("item")) {
        ic = ic.getParentElement();
        String webpageID = getWebpageID(ic);
        Element labelEl = null;
        xpath = XPATH_FACTORY.compile("//.[@href='" + webpageID + "']/label[@xml:lang='" + lang + "']",
            Filters.element());
        labelEl = xpath.evaluateFirst(getNavi());
        if (labelEl != null) {
            if (label.length() == 0) {
                label = new StringBuilder(labelEl.getTextTrim());
            } else {
                label.insert(0, labelEl.getTextTrim() + " > ");
            }
        }
    }
    return label.toString();
}
 
Example 7
Source File: TestWmsServer.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCapabilites() throws IOException, JDOMException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "/wms/scanCdmUnitTests/conventions/coards/sst.mnmean.nc?service=WMS&version=1.3.0&request=GetCapabilities");
  byte[] result = TestOnLocalServer.getContent(endpoint, 200, ContentType.xmlwms);
  Reader in = new StringReader(new String(result, StandardCharsets.UTF_8));
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build(in);

  XPathExpression<Element> xpath = XPathFactory.instance().compile("//wms:Capability/wms:Layer/wms:Layer/wms:Layer",
      Filters.element(), null, NS_WMS);
  List<Element> elements = xpath.evaluate(doc);
  assertEquals(1, elements.size());

  XPathExpression<Element> xpath2 = XPathFactory.instance()
      .compile("//wms:Capability/wms:Layer/wms:Layer/wms:Layer/wms:Name", Filters.element(), null, NS_WMS);
  Element emt = xpath2.evaluateFirst(doc);
  assertEquals("sst", emt.getTextTrim());
}
 
Example 8
Source File: MCRLayoutUtilities.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a Element presentation of an item[@href=$webpageID]
 *
 * @param webpageID
 * @return Element
 */
private static Element getItem(String webpageID) {
    Element item = itemStore.get(webpageID);
    if (item == null) {
        XPathExpression<Element> xpath = XPATH_FACTORY.compile("//.[@href='" + webpageID + "']", Filters.element());
        item = xpath.evaluateFirst(getNavi());
        itemStore.put(webpageID, item);
    }
    return item;
}
 
Example 9
Source File: MediaWikiAPI.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * @param pages Pages.
 * @param root Root element.
 * @param query XPath query to retrieve the contents 
 * @throws APIException Exception thrown by the API.
 */
private void constructContents(List<Page> pages, Element root, String query)
    throws APIException {
  if (pages == null) {
    throw new APIException("Pages is null");
  }

  XPathExpression<Element> xpaPage = XPathFactory.instance().compile(
      query, Filters.element());
  XPathExpression<Element> xpaRev = XPathFactory.instance().compile(
      "./revisions/rev", Filters.element());
  XPathExpression<Element> xpaSlot = XPathFactory.instance().compile(
      "./slots/slot", Filters.element());
  List<Element> resultPages = xpaPage.evaluate(root);
  Iterator<Element> iterPages = resultPages.iterator();
  while (iterPages.hasNext()) {
    Element currentPage = iterPages.next();
    String title = currentPage.getAttributeValue("title");

    for (Page page : pages) {
      if (Page.areSameTitle(page.getTitle(), title)) {
        Element currentRev = xpaRev.evaluateFirst(currentPage);
        Element currentSlot = xpaSlot.evaluateFirst(xpaRev);
        String contents = (currentSlot != null) ? currentSlot.getText() : currentRev.getText();
        page.setContents(contents);
      }
    }
  }
}
 
Example 10
Source File: ApiXmlLoginResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
   * Analyze login answer.
   * 
   * @param root Root element in MediaWiki answer.
   * @return Result of the login.
   * @throws APIException Exception thrown by the API.
   */
  private LoginResult constructLogin(Element root)
      throws APIException {
//    try {
      XPathExpression<Element> xpa = XPathFactory.instance().compile(
          "/api/login", Filters.element());
      Element node = xpa.evaluateFirst(root);
      if (node != null) {
        String result = node.getAttributeValue("result");
        if ("Success".equalsIgnoreCase(result)) {
          getWiki().getConnection().setLgInformation(
              node.getAttributeValue("lgtoken"),
              node.getAttributeValue("lgusername"),
              node.getAttributeValue("lguserid"));
          return LoginResult.createCorrectLogin();
        } else if (EnumLoginResult.NEED_TOKEN.getCode().equalsIgnoreCase(result)) {
          return LoginResult.createNeedTokenLogin(node.getAttributeValue("token"));
        }
        String details = node.getAttributeValue("details");
        if (details == null) {
          details = node.getAttributeValue("reason");
        }
        return LoginResult.createErrorLogin(
            result, details, node.getAttributeValue("wait"));
      }
//    } catch (JDOMException e) {
//      log.error("Error login", e);
//      throw new APIException("Error parsing XML result", e);
//    }
    return LoginResult.createErrorLogin(null, null, null);
  }
 
Example 11
Source File: XPathExtractor.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
@Override
public String extract(String data) {
    String result = "";
    try {
        Document doc = createDom(data);
        XPathExpression xp = createXpathExpression();
        Object text = xp.evaluateFirst(doc);
        result = wrap(text);
    } catch (Exception e) {
        throw new ExtractException(e);
    }
    return result;
}
 
Example 12
Source File: MCRXPathEvaluator.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public Object evaluateFirst(String xPathExpression) {
    try {
        XPathExpression<Object> xPath = XPATH_FACTORY.compile(xPathExpression, Filters.fpassthrough(), variables,
            MCRConstants.getStandardNamespaces());
        return xPath.evaluateFirst(context);
    } catch (Exception ex) {
        LOGGER.warn("unable to evaluate XPath: {}", xPathExpression);
        LOGGER.warn("XPath factory used is {} {}", XPATH_FACTORY.getClass().getCanonicalName(),
            MCRConfiguration2.getString("MCR.XPathFactory.Class").orElse(null));
        LOGGER.warn(ex);
        return null;
    }
}
 
Example 13
Source File: MCRDerivate.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads all files and urns from the derivate.
 * 
 * @return A {@link Map} which contains the files as key and the urns as value.
 * If no URN assigned the map will be empty.
 */
public Map<String, String> getUrnMap() {
    Map<String, String> fileUrnMap = new HashMap<>();

    XPathExpression<Element> filesetPath = XPathFactory.instance().compile("./mycorederivate/derivate/fileset",
        Filters.element());

    Element result = filesetPath.evaluateFirst(this.createXML());
    if (result == null) {
        return fileUrnMap;
    }
    String urn = result.getAttributeValue("urn");

    if (urn != null) {
        XPathExpression<Element> filePath = XPathFactory
            .instance()
            .compile("./mycorederivate/derivate/fileset[@urn='" + urn + "']/file", Filters.element());
        List<Element> files = filePath.evaluate(this.createXML());

        for (Element currentFileElement : files) {
            String currentUrn = currentFileElement.getChildText("urn");
            String currentFile = currentFileElement.getAttributeValue("name");
            fileUrnMap.put(currentFile, currentUrn);
        }
    }
    return fileUrnMap;
}
 
Example 14
Source File: MCRMetsSave.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the physicalStructMap of a mets document
 *
 * @param mets the mets document
 * @return the physicalStructmap of the mets document
 */
private static Element getPhysicalStructmap(Document mets) {
    XPathExpression<Element> xpath;
    xpath = XPathFactory.instance().compile(
        "mets:mets/mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']", Filters.element(),
        null, MCRConstants.METS_NAMESPACE);
    return xpath.evaluateFirst(mets);
}
 
Example 15
Source File: MCRMetsSave.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the StructLink of a mets document
 *
 * @param mets the mets document
 * @return the StructLink of a mets document
 */
private static Element getStructLink(Document mets) {
    XPathExpression<Element> xpath;
    xpath = XPathFactory.instance().compile("mets:mets/mets:structLink", Filters.element(), null,
        MCRConstants.METS_NAMESPACE);
    return xpath.evaluateFirst(mets);
}
 
Example 16
Source File: MCRMetsSave.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Build the default smLink. The PhysicalSubDiv is simply linked to the root chapter of the mets document.
 *
 * @param mets the mets document
 * @param div  the PhysicalSubDiv which should be linked
 * @return the default smLink
 */
private static SmLink getDefaultSmLink(Document mets, PhysicalSubDiv div) {
    XPathExpression<Attribute> attributeXpath;
    attributeXpath = XPathFactory.instance().compile("mets:mets/mets:structMap[@TYPE='LOGICAL']/mets:div/@ID",
        Filters.attribute(), null, MCRConstants.METS_NAMESPACE);
    Attribute idAttribute = attributeXpath.evaluateFirst(mets);
    String rootID = idAttribute.getValue();
    return new SmLink(rootID, div.getId());
}
 
Example 17
Source File: MCRMetsSave.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static Element getPhysicalFile(Document mets, String matchId) {
    XPathExpression<Element> xpath;
    String physicalFileExistsXpathString = String
        .format(
            Locale.ROOT,
            "mets:mets/mets:structMap[@TYPE='PHYSICAL']/mets:div[@TYPE='physSequence']" +
                "/mets:div[mets:fptr/@FILEID='%s']",
            matchId);
    xpath = XPathFactory.instance().compile(physicalFileExistsXpathString, Filters.element(), null,
        MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);

    return xpath.evaluateFirst(mets);
}
 
Example 18
Source File: MCRMoveToRelatedItemIfExists.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
Element getRelatedItemIfExists(Element parent) {
    XPathExpression<Element> xPath = XPathFactory.instance().compile(xPathOfRelatedItem, Filters.element(), null,
        MCRConstants.getStandardNamespaces());
    Element fixedParent = xPath.evaluateFirst(parent);
    return fixedParent != null ? fixedParent : parent;
}
 
Example 19
Source File: MediaWikiAPI.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * @param page Page.
 * @param root Root element.
 * @param query XPath query to retrieve the contents 
 * @throws APIException Exception thrown by the API.
 */
private boolean constructContents(Page page, Element root, String query)
    throws APIException {
  if (page == null) {
    throw new APIException("Page is null");
  }
  boolean redirect = false;

  XPathExpression<Element> xpaPage = XPathFactory.instance().compile(
      query, Filters.element());
  Element node = xpaPage.evaluateFirst(root);
  if (node != null) {
    page.setNamespace(node.getAttributeValue("ns"));
    if (node.getAttribute("redirect") != null) {
      redirect = true;
      page.getRedirects().isRedirect(true);
    }
    if (node.getAttribute("missing") != null) {
      page.setExisting(Boolean.FALSE);
    }
    page.setPageId(node.getAttributeValue("pageid"));
    page.setStartTimestamp(node.getAttributeValue("starttimestamp"));
  }
  XPathExpression<Element> xpa = XPathFactory.instance().compile(
      query + "/revisions/rev", Filters.element());
  node = xpa.evaluateFirst(root);
  if (node != null) {
    XPathExpression<Element> xpaSlot = XPathFactory.instance().compile(
        "slots/slot", Filters.element());
    Element nodeSlot = xpaSlot.evaluateFirst(node);
    page.setContents(nodeSlot != null ? nodeSlot.getText() : node.getText());
    page.setExisting(Boolean.TRUE);
    page.setRevisionId(node.getAttributeValue("revid"));
    page.setContentsTimestamp(node.getAttributeValue("timestamp"));
  }
  xpa = XPathFactory.instance().compile(query + "/protection/pr", Filters.element());
  for (Element prNode : xpa.evaluate(root)) {
    if ("edit".equals(prNode.getAttributeValue("type"))) {
      page.setEditProtectionLevel(prNode.getAttributeValue("level"));
    }
  }

  return redirect;
}
 
Example 20
Source File: MCRGenreTransformer.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private static Element getHostGenre(Element mods) {
    XPathExpression<Element> expr = XPathFactory.instance().compile("mods:relatedItem[@type='host']/mods:genre",
        Filters.element(), null, MCRConstants.getStandardNamespaces());
    return expr.evaluateFirst(mods);
}