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

The following examples show how to use org.jdom2.xpath.XPathExpression#evaluate() . 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: ConsistentDatesTest.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void checkWCSDates() throws JDOMException, IOException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "/wcs/cdmUnitTest/ncss/climatology/PF5_SST_Climatology_Monthly_1985_2001.nc?service=WCS&version=1.0.0&request=DescribeCoverage&coverage=sst");
  byte[] result = TestOnLocalServer.getContent(endpoint, 200, ContentType.xml);
  Reader in = new StringReader(new String(result, StandardCharsets.UTF_8));
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build(in);

  Namespace wcs = Namespace.getNamespace("wcs", doc.getRootElement().getNamespaceURI());
  Namespace gml = Namespace.getNamespace("gml", "http://www.opengis.net/gml");
  XPathExpression<Element> xpath =
      XPathFactory.instance().compile("//wcs:temporalDomain/gml:timePosition", Filters.element(), null, wcs, gml);
  List<Element> timePositionNodes = xpath.evaluate(doc);

  List<String> timePositionDateTime = new ArrayList<>();
  for (Element e : timePositionNodes) {
    System.out.printf("Date= %s%n", e.getText());
    CalendarDate cd = CalendarDate.parseISOformat(null, e.getText());
    timePositionDateTime.add(cd.toString());
  }

  assertEquals(expectedDatesAsDateTime, timePositionDateTime);
}
 
Example 2
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 3
Source File: XPathExtractor.java    From web-data-extractor with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> extractList(String data) {
    List<String> stringList = new LinkedList<>();
    try {
        Document doc = createDom(data);
        XPathExpression xp = createXpathExpression();
        List<Object> texts = xp.evaluate(doc);
        for (Object text : texts) {
            String result = wrap(text);
            stringList.add(result);
        }
    } catch (Exception e) {
        throw new ExtractException(e);
    }
    return stringList;
}
 
Example 4
Source File: ApiXmlPropertiesResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve information about page title normalization.
 * 
 * @param root Root element.
 * @param normalization Map containing information about title normalization (key=From, value=To).
 * @throws JDOMException Exception thrown due to the DOM.
 */
public void retrieveNormalization(
    Element root,
    Map<String, String> normalization) throws JDOMException {
  if (normalization == null) {
    return;
  }
  XPathExpression<Element> xpaNormalized = XPathFactory.instance().compile(
      "/api/query/normalized/n", Filters.element());
  List<Element> listNormalized = xpaNormalized.evaluate(root);
  if ((listNormalized == null) || (listNormalized.isEmpty())) {
    return;
  }
  Iterator<Element> itNormalized = listNormalized.iterator();
  while (itNormalized.hasNext()) {
    Element normalized = itNormalized.next();
    String from = normalized.getAttributeValue("from");
    String to = normalized.getAttributeValue("to");
    if ((from != null) && (to != null)) {
      normalization.put(from, to);
    }
  }
}
 
Example 5
Source File: ApiXmlRandomPagesResult.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Execute random pages request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with random pages.
 * @throws APIException Exception thrown by the API.
 */
@Override
public void executeRandomList(
    Map<String, String> properties,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Get random list
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/random/page", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      Page page = DataManager.getPage(
          getWiki(), currentNode.getAttributeValue("title"), null, null, null);
      page.setNamespace(currentNode.getAttributeValue("ns"));
      page.setPageId(currentNode.getAttributeValue("pageid"));
      list.add(page);
    }
  } catch (JDOMException e) {
    log.error("Error loading random list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 6
Source File: ApiXmlCategoriesResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute categories request.
 * 
 * @param properties Properties defining request.
 * @param page Page.
 * @param list List to be filled with categories.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeCategories(
    Map<String, String> properties,
    Page page,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve back links
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page/categories/cl", Filters.element());
    List<Element> listCategories = xpa.evaluate(root);
    Iterator<Element> itCategory = listCategories.iterator();
    while (itCategory.hasNext()) {
      Element currentCategory = itCategory.next();
      String pageId = currentCategory.getAttributeValue("pageid");
      String ns = currentCategory.getAttributeValue("ns");
      String title = currentCategory.getAttributeValue("title");
      Page category = DataManager.getPage(
          getWiki(), title, null, null, null);
      category.setNamespace(ns);
      category.setPageId(pageId);
      if (currentCategory.getAttribute("missing") != null) {
        category.setExisting(Boolean.FALSE);
      }
      if (!list.contains(category)) {
        list.add(category);
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/categories",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading templates", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 7
Source File: ApiXmlQueryPageResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute query page request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with query pages.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeQueryPage(
    Map<String, String> properties,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve query pages
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/querypage/results/page", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      Page page = DataManager.getPage(
          getWiki(), currentNode.getAttributeValue("title"), null, null, null);
      page.setNamespace(currentNode.getAttributeValue("ns"));
      list.add(page);
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/querypage",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading query page list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 8
Source File: ApiXmlAllMessagesResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute messages request.
 * 
 * @param properties Properties defining request.
 * @param messages Map of messages to be filled with the results.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeMessages(
    Map<String, String> properties,
    Map<String, String> messages) 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());
    List<Element> listMessages = xpa.evaluate(root);
    Iterator<Element> itMessages = listMessages.iterator();
    while (itMessages.hasNext()) {
      Element message = itMessages.next();
      String name = message.getAttributeValue("name");
      String text = message.getText().trim();
      messages.put(name, text);
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/allmessages",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading messages", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 9
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 10
Source File: ApiXmlRedirectsResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute redirects request.
 * 
 * @param properties Properties defining request.
 * @param page Page.
 * @param list List to be filled with redirects to the page.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeRedirects(
    Map<String, String> properties,
    Page page,
    List<Page> list)
        throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve redirects
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page/redirects/rd", Filters.element());
    List<Element> listRedirects = xpa.evaluate(root);
    Iterator<Element> itRedirects = listRedirects.iterator();
    while (itRedirects.hasNext()) {
      Element currentRedirect = itRedirects.next();
      Page link = DataManager.getPage(
          getWiki(), currentRedirect.getAttributeValue("title"), null, null, null);
      link.setNamespace(currentRedirect.getAttributeValue("ns"));
      link.setPageId(currentRedirect.getAttributeValue("pageid"));
      link.getRedirects().add(page, null); // TODO: Check if fragment is available
      if (!list.contains(link)) {
        list.add(link);
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/redirects",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading redirects", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 11
Source File: MCRPIXPathMetadataService.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeIdentifier(MCRPersistentIdentifier 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);
}
 
Example 12
Source File: ApiXmlResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Manage query-continue in request.
 * 
 * @param root Root of the DOM tree.
 * @param queryContinue XPath query to the query-continue node.
 * @param properties Properties defining request.
 * @return True if request should be continued.
 */
protected boolean shouldContinue(
    Element root, String queryContinue,
    Map<String, String> properties) {
  if ((root == null) || (queryContinue == null)) {
    return false;
  }
  boolean result = false;
  XPathExpression<Element> xpa = XPathFactory.instance().compile(
      queryContinue, Filters.element());
  List<Element> results = xpa.evaluate(root);
  if ((results == null) || (results.isEmpty())) {
    xpa = XPathFactory.instance().compile(
        "/api/continue", Filters.element());
    results = xpa.evaluate(root);
  }
  if (results != null) {
    for (Object currentNode : results) {
      List attributes = ((Element) currentNode).getAttributes();
      if (attributes != null) {
        for (Object currentAttribute : attributes) {
          Attribute attribute = (Attribute) currentAttribute;
          properties.put(attribute.getName(), attribute.getValue());
          result = true;
        }
      }
    }
  }
  return result;
}
 
Example 13
Source File: MCRClassificationMappingEventHandler.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void createMapping(MCRObject obj) {
    MCRMetaElement mappings = obj.getMetadata().getMetadataElement("mappings");
    if (mappings != null) {
        oldMappings = mappings.clone();
        obj.getMetadata().removeMetadataElement("mappings");
    }

    Element currentClassElement = null;
    try {
        Document doc = new Document(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");
        }
    }
}
 
Example 14
Source File: ApiXmlAbuseLogResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute abuse log request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with abuse logs.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeAbuseLog(
    Map<String, String> properties,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve category members
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/abuselog/item", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      String title = currentNode.getAttributeValue("title");
      Page page = DataManager.getPage(getWiki(), title, null, null, null);
      list.add(page);
    }

    // Retrieve continue
    return false; // Not continuing
    /*return shouldContinue(
        root, "/api/query-continue/abuselog",
        properties);*/
  } catch (JDOMException e) {
    log.error("Error loading abuse filters list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 15
Source File: ApiXmlLinksResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Execute links request.
 * 
 * @param properties Properties defining request.
 * @param lists Map of lists to be filled with links.
 * @param normalization Map containing information about title normalization (key=From, value=To).
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeLinks(
    Map<String, String> properties,
    Map<String, List<Page>> lists,
    Map<String, String> normalization) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve normalization information
    retrieveNormalization(root, normalization);

    // Retrieve back links
    XPathExpression<Element> xpaPages = XPathFactory.instance().compile(
        "/api/query/pages/page", Filters.element());
    List<Element> listPages = xpaPages.evaluate(root);
    Iterator<Element> itPage = listPages.iterator();
    XPathExpression<Element> xpaLinks = XPathFactory.instance().compile(
        "links/pl", Filters.element());
    while (itPage.hasNext()) {
      Element pageNode = itPage.next();
      String pageTitle = pageNode.getAttributeValue("title");
      List<Page> links = lists.get(pageTitle);
      if (links == null) {
        links = new ArrayList<Page>();
        lists.put(pageTitle, links);
      }
      List<Element> listLinks = xpaLinks.evaluate(pageNode);
      Iterator<Element> itLinks = listLinks.iterator();
      while (itLinks.hasNext()) {
        Element linkNode = itLinks.next();
        Page link = DataManager.getPage(
            getWiki(), linkNode.getAttributeValue("title"), null, null, null);
        link.setNamespace(linkNode.getAttributeValue("ns"));
        links.add(link);
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/links",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading links", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 16
Source File: ApiXmlPagePropsResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Set disambiguation status of a list of pages.
 * 
 * @param properties Properties defining request.
 * @param pages List of pages for which disambiguation status needs to be set.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean setDiambiguationStatus(
    Map<String, String> properties,
    Collection<Page> pages) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Manage redirects and missing pages
    updateRedirect(root, pages);

    // Set disambiguation status
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    List<Page> tmpPages = new ArrayList<Page>();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      String title = currentNode.getAttributeValue("title");
      for (Page p : pages) {
        tmpPages.clear();
        Iterator<Page> it = p.getRedirects().getIteratorWithPage();
        while (it.hasNext()) {
          Page p2 = it.next();
          tmpPages.add(p2);
          if ((p2.getTitle() != null) &&
              (Page.areSameTitle(p2.getTitle(), title))) {
            Boolean disambig = Boolean.FALSE;
            Element pageProps = currentNode.getChild("pageprops");
            if ((pageProps != null) && (pageProps.getAttribute("disambiguation") != null)) {
              disambig = Boolean.TRUE;
            }
            for (Page p3 : tmpPages) {
              p3.setDisambiguationPage(disambig);
            }
          }
        }
      }
    }

    return false;
  } catch (JDOMException e) {
    log.error("Error updating disambiguation status", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 17
Source File: ApiXmlCategoriesResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Set disambiguation status of a list of pages.
 * 
 * @param properties Properties defining request.
 * @param pages List of pages for which disambiguation status needs to be set.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean setDiambiguationStatus(
    Map<String, String> properties,
    Collection<Page> pages) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Manage redirects and missing pages
    updateRedirect(root, pages);

    // Set disambiguation status
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    XPathExpression<Element> xpaCategory = XPathFactory.instance().compile(
        "categories/cl", Filters.element());
    List<Page> tmpPages = new ArrayList<Page>();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      String title = currentNode.getAttributeValue("title");
      for (Page p : pages) {
        tmpPages.clear();
        Iterator<Page> it = p.getRedirects().getIteratorWithPage();
        while (it.hasNext()) {
          Page p2 = it.next();
          tmpPages.add(p2);
          if ((p2.getTitle() != null) &&
              (Page.areSameTitle(p2.getTitle(), title))) {
            List<Element> listCategories = xpaCategory.evaluate(currentNode);
            boolean dab = false;
            for (Element category : listCategories) {
              if (!dab && (category.getAttribute("ns").getValue().equals("" + Namespace.CATEGORY))) {
                dab = true;
              }
            }
            if (dab) {
              for (Page p3 : tmpPages) {
                p3.setDisambiguationPage(Boolean.TRUE);
              }
            }
          }
        }
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/categories",
        properties);
  } catch (JDOMException e) {
    log.error("Error updating disambiguation status", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 18
Source File: MCRBatchEditorCommands.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
private static List<Element> getlevelElements(Document xml, String level) {
    String path = MCRConfiguration2.getStringOrThrow(CFG_PREFIX_BASE + level);
    XPathExpression<Element> xPath = XPathFactory.instance().compile(path, FE, null, NS);
    return xPath.evaluate(xml);
}
 
Example 19
Source File: ApiXmlTemplatesResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Set disambiguation status of a list of pages.
 * 
 * @param properties Properties defining request.
 * @param pages List of pages for which disambiguation status needs to be set.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean setDiambiguationStatus(
    Map<String, String> properties,
    Collection<Page> pages) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Manage redirects and missing pages
    updateRedirect(root, pages);

    // Set disambiguation status
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/pages/page", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    XPathExpression<Element> xpaTemplates = XPathFactory.instance().compile(
        "templates/tl", Filters.element());
    List<Page> tmpPages = new ArrayList<Page>();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      String title = currentNode.getAttributeValue("title");
      for (Page p : pages) {
        tmpPages.clear();
        Iterator<Page> it = p.getRedirects().getIteratorWithPage();
        while (it.hasNext()) {
          Page p2 = it.next();
          tmpPages.add(p2);
          if ((p2.getTitle() != null) &&
              (Page.areSameTitle(p2.getTitle(), title))) {
            List<Element> listTemplates = xpaTemplates.evaluate(currentNode);
            boolean hasTemplate = false;
            for (Element template : listTemplates) {
              if (!hasTemplate && ("" + Namespace.TEMPLATE).equals(template.getAttribute("ns").getValue())) {
                hasTemplate = true;
              }
            }
            if (hasTemplate) {
              for (Page p3 : tmpPages) {
                p3.setDisambiguationPage(Boolean.TRUE);
              }
            }
          }
        }
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/templates",
        properties);
  } catch (JDOMException e) {
    log.error("Error updating disambiguation status", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 20
Source File: ApiXmlUsersResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Execute user request.
 * 
 * @param properties Properties defining request.
 * @throws APIException Exception thrown by the API.
 */
@Override
public User executeUser(
    Map<String, String> properties)
        throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Get recent changes list
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/users/user", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      User user = new User(currentNode.getAttributeValue("name"));
      List<String> groups = new ArrayList<String>();
      XPathExpression<Element> xpaGroups = XPathFactory.instance().compile(
          "./groups/g", Filters.element());
      List<Element> resultGroups = xpaGroups.evaluate(currentNode);
      Iterator<Element> itGroups = resultGroups.iterator();
      while (itGroups.hasNext()) {
        groups.add(itGroups.next().getValue());
      }
      user.setGroups(groups);
      List<String> rights = new ArrayList<String>();
      XPathExpression<Element> xpaRights = XPathFactory.instance().compile(
          "./rights/r", Filters.element());
      List<Element> resultRights = xpaRights.evaluate(currentNode);
      Iterator<Element> itRights = resultRights.iterator();
      while (itRights.hasNext()) {
        rights.add(itRights.next().getValue());
      }
      user.setRights(rights);
      return user;
    }
  } catch (JDOMException e) {
    log.error("Error retrieving user information", e);
    throw new APIException("Error parsing XML", e);
  }
  return null;
}