org.jdom2.xpath.XPathFactory Java Examples

The following examples show how to use org.jdom2.xpath.XPathFactory. 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: UscTteCollectionReader.java    From bluima with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(UimaContext context)
        throws ResourceInitializationException {
    inputDir = CORPORA_BASE + "USC_TTE_corpus";
    // inputDir = CORPORA_HOME + "src/test/resources/corpus/USC_TTE_corpus";
    docCnt = 1;
    super.initialize(context);
    try {
        File corpusDir = new File(inputDir);
        checkArgument(corpusDir.exists());
        // duplicating code from AbstractFileReader to add "xml" filtering
        fileIterator = DirectoryIterator.get(directoryIterator, corpusDir,
                "xml", false);
        builder = new SAXBuilder();
        xo = new XMLOutputter();
        xo.setFormat(Format.getRawFormat());
        sentenceXPath = XPathFactory.instance().compile("//S");
    } catch (Exception e) {
        throw new ResourceInitializationException(
                ResourceInitializationException.NO_RESOURCE_FOR_PARAMETERS,
                new Object[] { inputDir });
    }
}
 
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: 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 #4
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 #5
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 #6
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 #7
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 #8
Source File: MCRSimpleModelXMLConverterTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testToXML() throws Exception {
    Document document = MCRSimpleModelXMLConverter.toXML(metsSimpleModel);

    XPathFactory xPathFactory = XPathFactory.instance();
    String documentAsString = new XMLOutputter(Format.getPrettyFormat()).outputString(document);

    Arrays.asList(PATHS_TO_CHECK.split(";")).stream()
        .map((String xpath) -> xPathFactory.compile(xpath, Filters.fboolean(), Collections.emptyMap(),
            Namespace.getNamespace("mets", "http://www.loc.gov/METS/")))
        .forEachOrdered(xPath -> {
            Boolean evaluate = xPath.evaluateFirst(document);
            Assert.assertTrue(
                String.format("The xpath : %s is not true! %s %s", xPath, System.lineSeparator(), documentAsString),
                evaluate);
        });
}
 
Example #9
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 #10
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 #11
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 #12
Source File: MCREditorOutValidator.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * tries to generate a valid MCRObject as JDOM Document.
 *
 * @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;
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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;
}
 
Example #23
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 #24
Source File: ApiXmlSearchResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute search request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with back links.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeSearch(
    Map<String, String> properties,
    List<Page> list)
        throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

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

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

    // Retrieve watch list
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/watchlistraw/wr", 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);
      if (page.isArticle()) {
        watchlist.add(page);
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/watchlistraw",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading watch list", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example #26
Source File: ApiXmlCategoryMembersResult.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Execute category members request.
 * 
 * @param properties Properties defining request.
 * @param list List to be filled with category members.
 * @param categories Map of categories to be analyzed with their depth.
 * @param depth Current depth of the analysis.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeCategoryMembers(
    Map<String, String> properties,
    List<Page> list,
    Map<Page, Integer> categories, int depth) throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve category members
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/categorymembers/cm", 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"));
      if ((page.getNamespace() != null) &&
          (page.getNamespace().intValue() == Namespace.CATEGORY)) {
        categories.put(page, depth + 1);
      } else {
        if (!list.contains(page)) {
          list.add(page);
        }
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/categorymembers",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading category members 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: MCRClassificationMappingEventHandlerTest.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testMapping() throws SAXParseException, IOException, JDOMException, URISyntaxException {
    MCRSessionMgr.getCurrentSession().isTransactionActive();
    ClassLoader classLoader = getClass().getClassLoader();
    SAXBuilder saxBuilder = new SAXBuilder();

    loadCategory("diniPublType.xml");
    loadCategory("genre.xml");

    Document document = saxBuilder.build(classLoader.getResourceAsStream(TEST_DIRECTORY + "testMods.xml"));
    MCRObject mcro = new MCRObject();

    MCRMODSWrapper mw = new MCRMODSWrapper(mcro);
    mw.setMODS(document.getRootElement().detach());
    mw.setID("junit", 1);

    MCRClassificationMappingEventHandler mapper = new MCRClassificationMappingEventHandler();
    mapper.handleObjectUpdated(null, mcro);

    String expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'StudyThesis')]";
    XPathExpression<Element> expressionObject = XPathFactory.instance()
        .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);
    Document xml = mcro.createXML();
    Assert.assertNotNull("The mapped classification should be in the MyCoReObject now!",
        expressionObject.evaluateFirst(
            xml));

    expression = "//mods:classification[contains(@generator,'-mycore') and contains(@valueURI, 'masterThesis')]";
    expressionObject = XPathFactory.instance()
        .compile(expression, Filters.element(), null, MCRConstants.MODS_NAMESPACE, MCRConstants.XLINK_NAMESPACE);

    Assert.assertNull("The mapped classification of the child should not be contained in the MyCoReObject now!",
        expressionObject.evaluateFirst(xml));

    LOGGER.info(new XMLOutputter(Format.getPrettyFormat()).outputString(xml));
}
 
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: 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);
  }
}