org.jdom2.xpath.XPathExpression Java Examples

The following examples show how to use org.jdom2.xpath.XPathExpression. 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: MCRMetsSave.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Searches a file in a group, which matches a filename.
 *
 * @param mets the mets file to search
 * @param path the path to the alto file (e.g. "alto/alto_file.xml" when searching in DEFAULT_FILE_GROUP_USE or
 *             "image_file.jpg" when searchin in ALTO_FILE_GROUP_USE)
 * @param searchFileGroup
 * @return the id of the matching file or null if there is no matching file
 */
private static String searchFileInGroup(Document mets, String path, String searchFileGroup) {
    XPathExpression<Element> xpath;// first check all files in default file group
    String relatedFileExistPathString = String.format(Locale.ROOT,
        "mets:mets/mets:fileSec/mets:fileGrp[@USE='%s']/mets:file/mets:FLocat", searchFileGroup);
    xpath = XPathFactory.instance().compile(relatedFileExistPathString, Filters.element(), null,
        MCRConstants.METS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    List<Element> fileLocList = xpath.evaluate(mets);
    String matchId = null;

    // iterate over all files
    String cleanPath = getCleanPath(path);

    for (Element fileLoc : fileLocList) {
        Attribute hrefAttribute = fileLoc.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
        String hrefAttributeValue = hrefAttribute.getValue();
        String hrefPath = getCleanPath(removeExtension(hrefAttributeValue));

        if (hrefPath.equals(removeExtension(cleanPath))) {
            matchId = ((Element) fileLoc.getParent()).getAttributeValue("ID");
            break;
        }
    }
    return matchId;
}
 
Example #3
Source File: MCRPIXPathMetadataService.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional)
    throws MCRPersistentIdentifierException {
    String xpath = getProperties().get("Xpath");
    Document xml = obj.createXML();
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression<Element> xp = xpfac
        .compile(xpath, Filters.element(), null, MCRConstants.getStandardNamespaces());
    List<Element> evaluate = xp.evaluate(xml);
    if (evaluate.size() > 1) {
        throw new MCRPersistentIdentifierException(
            "Got " + evaluate.size() + " matches for " + obj.getId() + " with xpath " + xpath + "");
    }

    if (evaluate.size() == 0) {
        return Optional.empty();
    }

    Element identifierElement = evaluate.listIterator().next();
    String identifierString = identifierElement.getTextNormalize();

    Optional<MCRPersistentIdentifier> parsedIdentifierOptional = MCRPIManager.getInstance()
        .getParserForType(getProperties().get("Type")).parse(identifierString);
    return parsedIdentifierOptional.map(MCRPersistentIdentifier.class::cast);
}
 
Example #4
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 #5
Source File: MCRMetsIIIFModsMetadataExtractor.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<MCRIIIFMetadata> extractModsMetadata(Element xmlData) {
    Map<String, String> elementLabelMap = new HashMap<>();

    elementLabelMap.put("title", "mods:mods/mods:titleInfo/mods:title/text()");
    elementLabelMap.put("genre", "mods:mods/mods:genre/text()");
    // TODO: add some more metadata

    return elementLabelMap.entrySet().stream().map(entry -> {
        XPathExpression<Text> pathExpression = XPathFactory.instance().compile(entry.getValue(), Filters.text(),
            null, MCRConstants.MODS_NAMESPACE);
        List<Text> texts = pathExpression.evaluate(xmlData);
        if (texts.size() == 0) {
            return null;
        }
        return new MCRIIIFMetadata(entry.getKey(),
            texts.stream().map(Text::getText).collect(Collectors.joining(", ")));
    }).filter(Objects::nonNull)
        .collect(Collectors.toList());
}
 
Example #6
Source File: MCRRestAPIClassifications.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Output xml
 * @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();
}
 
Example #7
Source File: MCRRestAPIObjectsHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static void createXMLForSubdirectories(MCRPath mcrPath, Element currentElement, int currentDepth,
    int maxDepth) {
    if (currentDepth < maxDepth) {
        XPathExpression<Element> xp = XPathFactory.instance().compile("./children/child[@type='directory']",
            Filters.element());
        for (Element e : xp.evaluate(currentElement)) {
            String name = e.getChildTextNormalize("name");
            try {
                MCRPath pChild = (MCRPath) mcrPath.resolve(name);
                Document doc = MCRPathXML.getDirectoryXML(pChild);
                Element eChildren = doc.getRootElement().getChild("children");
                if (eChildren != null) {
                    e.addContent(eChildren.detach());
                    createXMLForSubdirectories(pChild, e, currentDepth + 1, maxDepth);
                }
            } catch (IOException ex) {
                //ignore
            }

        }
    }
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: ISBNRange.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Analyze RangeMessage.xml file for Ranges.
 * 
 * @param root Root of RangeMessage.xml file.
 * @param ranges Current list of ranges.
 * @param xpath XPath selector.
 * @throws JDOMException
 */
private static void analyzeRanges(Element root, List<Range> ranges, String xpath) throws JDOMException {
  XPathExpression<Element> xpa = XPathFactory.instance().compile(xpath, Filters.element());
  List<Element> results = xpa.evaluate(root);
  Iterator<Element> iter = results.iterator();
  while (iter.hasNext()) {
    Element node = iter.next();
    Element prefixNode = node.getChild("Prefix");
    String prefix = (prefixNode != null) ? prefixNode.getValue() : null;
    Element agencyNode = node.getChild("Agency");
    String agency = (agencyNode != null) ? agencyNode.getValue() : null;
    Range range = new Range(prefix, agency);
    analyzeRules(node, range);
    ranges.add(range);
  }
}
 
Example #16
Source File: ISBNRange.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/**
 * Analyze RangeMessage.xml file Rules.
 * 
 * @param node Current node.
 * @param rangeElement Range element.
 * @throws JDOMException
 */
private static void analyzeRules(Element node, Range rangeElement) throws JDOMException {
  XPathExpression<Element> xpa = XPathFactory.instance().compile(
      "./Rules/Rule", Filters.element());
  List<Element> results = xpa.evaluate(node);
  Iterator<Element> iter = results.iterator();
  while (iter.hasNext()) {
    Element ruleNode = iter.next();
    Element rangeNode = ruleNode.getChild("Range");
    String range = (rangeNode != null) ? rangeNode.getValue() : null;
    Element lengthNode = ruleNode.getChild("Length");
    String length = (lengthNode != null) ? lengthNode.getValue() : null;
    if ((range != null) && (length != null)) {
      String[] rangeElements = range.split("\\-");
      if ((rangeElements != null) && (rangeElements.length == 2)) {
        Rule rule = new Rule(rangeElements[0], rangeElements[1], Integer.parseInt(length));
        rangeElement.addRule(rule);
      }
    }
  }
}
 
Example #17
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 #18
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 #19
Source File: ConsistentDatesTest.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void checkNCSSDates() throws JDOMException, IOException {
  String endpoint = TestOnLocalServer.withHttpPath(
      "/ncss/grid/cdmUnitTest/ncss/climatology/PF5_SST_Climatology_Monthly_1985_2001.nc?var=sst&latitude=45&longitude=-20&temporal=all&accept=xml");
  byte[] result = TestOnLocalServer.getContent(endpoint, 200, ContentType.xml);
  String results = new String(result, StandardCharsets.UTF_8);
  if (show)
    System.out.printf("checkNCSSDates%n%s%n", results);
  Reader in = new StringReader(results);
  SAXBuilder sb = new SAXBuilder();
  Document doc = sb.build(in);

  XPathExpression<Element> xpath =
      XPathFactory.instance().compile("/stationFeatureCollection/stationFeature", Filters.element());
  List<Element> dataTimeNodes = xpath.evaluate(doc);

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

  assertEquals(expectedDatesAsDateTime, timePositionDateTime);
}
 
Example #20
Source File: ApiXmlPropertiesResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Update page information.
 * 
 * @param node Element for the page.
 * @param page Page.
 * @throws JDOMException Exception from due to the DOM.
 */
public void updatePageInformation(Element node, Page page) throws JDOMException {

  // Retrieve basic page information
  Attribute attrPageId = node.getAttribute("pageid");
  if (attrPageId != null) {
    page.setPageId(attrPageId.getValue());
  }
  Attribute attrTitle = node.getAttribute("title");
  if (attrTitle != null) {
    page.setTitle(attrTitle.getValue());
  }
  page.setStartTimestamp(node.getAttributeValue("starttimestamp"));
  Attribute attrRedirect = node.getAttribute("redirect");
  if (attrRedirect != null) {
    page.getRedirects().isRedirect(true);
  }
  Attribute attrMissing = node.getAttribute("missing");
  if (attrMissing != null) {
    page.setExisting(Boolean.FALSE);
  }

  // Retrieve protection information
  XPathExpression<Element> xpaProtection = XPathFactory.instance().compile(
      "protection/pr[@type=\"edit\"]", Filters.element());
  List<Element> protectionNodes = xpaProtection.evaluate(node);
  for (Element protectionNode : protectionNodes) {
    if ("edit".equals(protectionNode.getAttributeValue("type"))) {
      page.setEditProtectionLevel(protectionNode.getAttributeValue("level"));
    }
  }
}
 
Example #21
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 #22
Source File: ApiXmlTokensResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute tokens request.
 * 
 * @param properties Properties defining request.
 * @throws APIException Exception thrown by the API.
 */
@Override
public void executeTokens(
    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/tokens", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      String deleteToken = currentNode.getAttributeValue("deletetoken");
      if (deleteToken != null) {
        getWiki().getConnection().setDeleteToken(deleteToken);
      }
      String editToken = currentNode.getAttributeValue("edittoken");
      if (editToken != null) {
        getWiki().getConnection().setEditToken(editToken);
      }
    }
  } catch (JDOMException e) {
    log.error("Error retrieving tokens", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example #23
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 #24
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 #25
Source File: ApiXmlProtectedTitlesResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute protected titles request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with protected titles.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeProtectedTitles(
    Map<String, String> properties,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve embedding pages
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/protectedtitles/pt", Filters.element());
    List<Element> results = xpa.evaluate(root);
    Iterator<Element> iter = results.iterator();
    while (iter.hasNext()) {
      Element currentNode = iter.next();
      if ("infinity".equals(currentNode.getAttributeValue("expiry"))) {
        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/protectedtitles",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading protected titles list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example #26
Source File: ApiXmlEmbeddedInResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute embedded in request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with embedding pages.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeEmbeddedIn(
    Map<String, String> properties,
    List<Page> list) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve embedding pages
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/embeddedin/ei", 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);
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/embeddedin",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading embedded in list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example #27
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 #28
Source File: JDomParser.java    From tutorials with MIT License 5 votes vote down vote up
public Element getNodeById(String id) {
    try {
        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(file);
        String filter = "//*[@tutId='" + id + "']";
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
        List<Element> node = expr.evaluate(document);

        return node.get(0);
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #29
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 #30
Source File: XPathExtractor.java    From web-data-extractor with Apache License 2.0 5 votes vote down vote up
private XPathExpression createXpathExpression() {
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression xp = null;
    if (namespaces.isEmpty()) {
        xp = xpfac.compile(xpath, Filters.fpassthrough());
    } else {
        xp = xpfac.compile(xpath, Filters.fpassthrough(), new LinkedHashMap<String, Object>(), namespaces.toArray(new Namespace[namespaces.size()]));
    }
    return xp;
}