Java 类org.jdom2.filter.Filters 实例源码

项目:qpp-conversion-tool    文件:ReportingParametersActDecoder.java   
/**
 * Acquires the reporting parameters within the xml and inserts into a given node
 *
 * @param element XML document that contains the reporting parameters act
 * @param thisNode Reporting parameter node
 */
private void setPerformanceTimeRangeOnNode(Element element, Node thisNode) {
    String performanceStartExprStr = getXpath(PERFORMANCE_START);
    String performanceEndExprStr = getXpath(PERFORMANCE_END);

    Consumer<? super Attribute> performanceStartConsumer =
            p -> {
                String start = p.getValue();
                thisNode.putValue(PERFORMANCE_START, start, false);
                //start is formatted as follows: yyyyMMddHHmmss
                thisNode.putValue(PERFORMANCE_YEAR, start.substring(0, 4));
            };
    Consumer<? super Attribute> performanceEndConsumer =
            p -> thisNode.putValue(PERFORMANCE_END, p.getValue(), false);

    setOnNode(element, performanceStartExprStr, performanceStartConsumer, Filters.attribute(), false);
    setOnNode(element, performanceEndExprStr, performanceEndConsumer, Filters.attribute(), false);
}
项目:qpp-conversion-tool    文件:JsonPathToXpathHelper.java   
public void executeAttributeTest(String jsonPath, String expectedValue) {
    String xPath = PathCorrelator.prepPath(jsonPath, wrapper);

    Attribute attribute = null;
    try {
        attribute = evaluateXpath(xPath, Filters.attribute());
    } catch (IOException | XmlException e) {
        fail(e.getMessage());
    }

    if (attribute == null) {
        System.out.println("no attribute for path: " + jsonPath
                + "\n xpath: " + xPath);
    }

    if (!expectedValue.equals(attribute.getValue())) {
        System.err.println("( " + jsonPath + " ) value ( " + expectedValue +
                " ) does not equal ( " + attribute.getValue() +
                " ) at \n( " + xPath + " ). \nPlease investigate.");
    }

    assertThat(attribute.getValue()).isNotNull();
}
项目:sumo    文件:SumoSafeReader.java   
/**
 * Return the mesaurements
 * 
 * @return
 */
public void readMesasurementFilesFromSafe() {
    XPathExpression<Element> expr = xFactory
            .compile(
                    "/xfdu:XFDU/dataObjectSection/dataObject[@repID='s1Level1ProductSchema']/byteStream/fileLocation",
                    Filters.element(), null, xfdu);

    List<Element> values = expr.evaluate(safe);
    this.measurements=new File[values.size()];

    File safefile = new File(safePath);
    String measurementPath = safefile.getParent() + "/measurement";

    for (int i = 0; i < values.size(); i++) {
        Element e = values.get(i);
        String href = e.getAttributeValue("href");
        if (href.startsWith("./"))
            href = href.substring(2);
        measurements[i] = new File(measurementPath + "/" + href);
        System.out.println(measurements[i]);
    }

}
项目:sumo    文件:SumoSafeReader.java   
/**
 * Read the generalProductInformation:
 * productType,instrumentConfigurationID,
 * missionDataTakeID,transmitterReceiverPolarisation
 * ,productTimelinessCategory,sliceProductFlag
 * 
 * @throws JAXBException
 * @throws SAXException
 */
public void readGeneralProductInformation() throws JAXBException,
        SAXException {
    String xPathGenProdInfo = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData/*[name()='generalProductInformation']";
    String xPathStandAloneInfo = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData/s1sarl1:standAloneProductInformation']";

    XPathExpression<Element> expr = xFactory.compile(xPathGenProdInfo,
            Filters.element(), null, xfdu);
    List<Element> value = expr.evaluate(safe);
    if (value == null || value.isEmpty()) {
        expr = xFactory.compile(xPathStandAloneInfo, Filters.element(),
                null, s1sarl1, xfdu);
        value = expr.evaluate(safe);
    }

    List<Element> informationsNode = value.get(0).getChildren();
    productInformation = new ProductInformation();

    for (Element e : informationsNode) {
        String name = e.getName();
        String val = e.getValue();
        productInformation.putValueInfo(name, val);
    }

}
项目:sumo    文件:SumoSafeReader.java   
/**
 * Read the acquisition period
 * 
 * @throws JAXBException
 * @throws SAXException
 */
public void readAcquisitionPeriod() throws JAXBException, SAXException {
    acquPeriod = new AcquisitionPeriod();

    String xPathStartTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:startTime']";
    String xPathStopTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:stopTime']";

    XPathExpression<Element> expr = xFactory.compile(xPathStartTime,
            Filters.element(), null, xfdu, safeNs);
    Element e = expr.evaluateFirst(safe);

    if (e != null)
        acquPeriod.setStartTime(e.getValue());

    expr = xFactory.compile(xPathStopTime, Filters.element(), null, xfdu,
            safeNs);
    e = expr.evaluateFirst(safe);
    if (e != null)
        acquPeriod.setStopTime(e.getValue());
}
项目:sumo    文件:SumoXPathSafeReader.java   
public void readMesasurementFilesFromSafe() {
    XPathExpression<Element> expr = xFactory
            .compile(
                    "/xfdu:XFDU/dataObjectSection/dataObject[@repID='s1Level1ProductSchema']/byteStream/fileLocation",
                    Filters.element(), null, xfdu);

    List<Element> values = expr.evaluate(safe);
    this.measurements=new File[values.size()];

    String measurementPath = safefile.getParent() + "/measurement";

    for (int i = 0; i < values.size(); i++) {
        Element e = values.get(i);
        String href = e.getAttributeValue("href");
        if (href.startsWith("./"))
            href = href.substring(2);
        measurements[i] = new File(measurementPath + "/" + href);
        System.out.println(measurements[i]);
    }

}
项目:sumo    文件:SumoXPathSafeReader.java   
public void readGeneralProductInformation() throws JAXBException,
        SAXException {
    String xPathGenProdInfo = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData/*[name()='generalProductInformation']";
    String xPathStandAloneInfo = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData/s1sarl1:standAloneProductInformation";

    XPathExpression<Element> expr = xFactory.compile(xPathGenProdInfo,
            Filters.element(), null, xfdu);
    List<Element> value = expr.evaluate(safe);
    if (value == null || value.isEmpty()) {
        expr = xFactory.compile(xPathStandAloneInfo, Filters.element(),
                null, s1sarl1, xfdu);
        value = expr.evaluate(safe);
    }

    List<Element> informationsNode = value.get(0).getChildren();
    productInformation = new ProductInformation();

    for (Element e : informationsNode) {
        String name = e.getName();
        String val = e.getValue();
        productInformation.putValueInfo(name, val);
    }

}
项目:sumo    文件:SumoXPathSafeReader.java   
public void readAcquisitionPeriod() throws JAXBException, SAXException {
    acquPeriod = new AcquisitionPeriod();

    String xPathStartTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:startTime']";
    String xPathStopTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:stopTime']";

    XPathExpression<Element> expr = xFactory.compile(xPathStartTime,
            Filters.element(), null, xfdu, safeNs);
    Element e = expr.evaluateFirst(safe);

    if (e != null)
        acquPeriod.setStartTime(e.getValue());

    expr = xFactory.compile(xPathStopTime, Filters.element(), null, xfdu,
            safeNs);
    e = expr.evaluateFirst(safe);
    if (e != null)
        acquPeriod.setStopTime(e.getValue());
}
项目:bibliometrics    文件:ScopusConnector.java   
public Set<Element> getPublicationsForAuthor(PublicationAuthor author)
        throws IOException, JDOMException, SAXException {
    if (!author.getScopusAuthorID().isEmpty()) {
        Set<Element> publications = new HashSet<>();
        String queryURL = API_URL + "/author/AUTHOR_ID:" + author.getScopusAuthorID()
                + "?start=0&count=200&view=DOCUMENTS&apikey=" + API_KEY;
        XPathExpression<Element> xPath = XPathFactory.instance().compile(pathToDocumentIdentifier,
                Filters.element());
        List<Element> identifierElements = xPath
                .evaluate(getResponse(queryURL).asXML().detachRootElement().clone());
        for (Element idElement : identifierElements) {
            publications.add(getPublicationByID(idElement.getValue()));
        }
        return publications;
    } else
        return null;
}
项目:bibliometrics    文件:ScopusConnector.java   
public Element getCitationInformation(String scopusID)
        throws IOException, JDOMException, SAXException {
    // build API URL
    String queryURL = API_URL + "/abstract/citation-count?scopus_id=" + scopusID + "&apikey=" + API_KEY
            + "&httpAccept=application%2Fxml";
    XPathExpression<Element> xPathCount = XPathFactory.instance().compile(pathToCitationCount, Filters.element());
    XPathExpression<Element> xPathLink = XPathFactory.instance().compile(pathToCitationLink, Filters.element());
    XPathExpression<Element> xPathArticleLink = XPathFactory.instance().compile(pathToArticleLink, Filters.element());
    Element response = getResponse(queryURL).asXML().detachRootElement().clone();
    String citationCount = xPathCount.evaluateFirst(response).getValue();
    String citationLink = xPathLink.evaluateFirst(response).getAttributeValue("href");
    String articleLink = xPathArticleLink.evaluateFirst(response).getAttributeValue("href");
    Element citationInformation = new Element("citationInformation");
    citationInformation.addContent(new Element("count").setText(citationCount));
    citationInformation.addContent(new Element("citationLink").setText(citationLink));
    citationInformation.addContent(new Element("articleLink").setText(articleLink));
    return citationInformation;
}
项目:goobi-viewer-indexer    文件:JDomXP.java   
/**
 * Evaluates the given XPath expression to a list of attributes.
 * 
 * @param expr XPath expression to evaluate.
 * @param parent If not null, the expression is evaluated relative to this element.
 * @return {@link ArrayList} or null
 * @throws FatalIndexerException 
 * @should return all values
 */
public List<Attribute> evaluateToAttributes(String expr, Object parent) throws FatalIndexerException {
    List<Attribute> retList = new ArrayList<>();
    if (parent == null) {
        parent = doc;
    }
    List<Object> list = evaluate(expr, parent, Filters.attribute());
    if (list == null) {
        return null;
    }
    for (Object object : list) {
        if (object instanceof Attribute) {
            Attribute attr = (Attribute) object;
            retList.add(attr);
        }
    }
    return retList;
}
项目:goobi-viewer-indexer    文件:JDomXP.java   
/**
 * Evaluates the given XPath expression to a single string.
 *
 * @param expr XPath expression to evaluate.
 * @param parent If not null, the expression is evaluated relative to this element.
 * @return {@link String} or null
 * @throws FatalIndexerException 
 * @should return value correctly
 */
public String evaluateToString(String expr, Object parent) throws FatalIndexerException {
    if (parent == null) {
        parent = doc;
    }
    // JDOM2 requires '/text()' for string evaluation
    if (expr != null && !expr.endsWith("/text()")) {
        expr += "/text()";
    }
    List<Object> list = evaluate(expr, parent, Filters.text());
    if (list == null || list.isEmpty()) {
        return null;
    }
    if (objectToString(list.get(0)) != null) {
        return objectToString(list.get(0));
    }
    return "";
}
项目:goobi-viewer-indexer    文件:JDomXP.java   
/**
 * Evaluates the given XPath expression to a list of strings.
 * 
 * @param expr XPath expression to evaluate.
 * @param parent If not null, the expression is evaluated relative to this element.
 * @return {@link ArrayList} or null
 * @throws FatalIndexerException 
 * @should return all values
 */
public List<String> evaluateToStringList(String expr, Object parent) throws FatalIndexerException {
    if (parent == null) {
        parent = doc;
    }

    List<Object> list = evaluate(expr, parent, Filters.fpassthrough());
    if (list == null) {
        return null;
    }

    List<String> retList = new ArrayList<>();
    for (Object object : list) {
        retList.add(objectToString(object));
    }
    return retList;
}
项目:goobi-viewer-indexer    文件:JDomXP.java   
/**
 * Evaluates given XPath expression to the first found CDATA element.
 * 
 * @param expr
 * @param parent
 * @return
 * @throws FatalIndexerException 
 * @should return value correctly
 */
public String evaluateToCdata(String expr, Object parent) throws FatalIndexerException {
    if (parent == null) {
        parent = doc;
    }
    // JDOM2 requires '/text()' for string evaluation
    if (expr != null && !expr.endsWith("/text()")) {
        expr += "/text()";
    }
    List<Object> list = evaluate(expr, parent, Filters.cdata());
    if (list == null || list.isEmpty()) {
        return null;
    }
    if (objectToString(list.get(0)) != null) {
        return objectToString(list.get(0));
    }
    return "";
}
项目:atf-toolbox-java    文件:XMLDataDriver.java   
@Override
public TestCaseData load() {
    TestCaseData tcData = new TestCaseData();

    XPathFactory xFactory = XPathFactory.instance();

    Element testCase = xFactory.compile("//testcase[@name='" + name + "']", Filters.element()).evaluateFirst(xmlDocument);

    List<Element> scenarios = testCase.getChildren();

    for (Element scenario : scenarios) {
        List<Element> parameters = scenario.getChildren();
        ScenarioData testScenario = new ScenarioData(scenario.getName(), testCase.getName());

        for (Element parameter : parameters) {
            testScenario.putScenarioData(parameter.getName(), parameter.getValue());
        }

        tcData.addScenarioData(testScenario);
    }

    return tcData;
}
项目:mycore    文件:MCRBinding.java   
private void bind(String xPath, boolean buildIfNotExists, String initialValue) throws JaxenException {
    this.xPath = xPath;

    Map<String, Object> variables = buildXPathVariables();

    XPathExpression<Object> xPathExpr = XPathFactory.instance().compile(xPath, Filters.fpassthrough(), variables,
        MCRConstants.getStandardNamespaces());

    boundNodes.addAll(xPathExpr.evaluate(parent.getBoundNodes()));

    for (Object boundNode : boundNodes)
        if (!(boundNode instanceof Element || boundNode instanceof Attribute || boundNode instanceof Document))
            throw new RuntimeException(
                "XPath MUST only bind either element, attribute or document nodes: " + xPath);

    LOGGER.debug("Bind to {} selected {} node(s)", xPath, boundNodes.size());

    if (boundNodes.isEmpty() && buildIfNotExists) {
        MCRNodeBuilder builder = new MCRNodeBuilder(variables);
        Object built = builder.buildNode(xPath, initialValue, (Parent) (parent.getBoundNode()));
        LOGGER.debug("Bind to {} generated node {}", xPath, MCRXPathBuilder.buildXPath(built));
        boundNodes.add(built);
        trackNodeCreated(builder.getFirstNodeBuilt());
    }
}
项目:mycore    文件:MCRChangeTrackerTest.java   
@Test
public void testRemoveChangeTracking() throws JaxenException, JDOMException {
    String template = "document[titles[title][title[2]]][authors/author[first='John'][last='Doe']]";
    Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null));

    MCRChangeTracker tracker = new MCRChangeTracker();

    Element titles = (Element) (new MCRBinding("document/titles", true, new MCRBinding(doc)).getBoundNode());
    Element title = new Element("title").setAttribute("type", "alternative");
    titles.addContent(2, title);
    tracker.track(MCRAddedElement.added(title));

    Attribute lang = new Attribute("lang", "de");
    doc.getRootElement().setAttribute(lang);
    tracker.track(MCRAddedAttribute.added(lang));

    Element author = (Element) (new MCRBinding("document/authors/author", true, new MCRBinding(doc))
        .getBoundNode());
    tracker.track(MCRRemoveElement.remove(author));

    doc = MCRChangeTracker.removeChangeTracking(doc);
    assertFalse(doc.getDescendants(Filters.processinginstruction()).iterator().hasNext());
}
项目:mycore    文件:MCRMODSLinkedMetadataTest.java   
@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());
}
项目:mycore    文件:MCRMetsIIIFModsMetadataExtractor.java   
@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());
}
项目:mycore    文件:MCRMetsSave.java   
/**
 * 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
    path = 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(path))) {
            matchId = ((Element) fileLoc.getParent()).getAttributeValue("ID");
            break;
        }
    }
    return matchId;
}
项目:mycore    文件:MCRSimpleModelXMLConverterTest.java   
@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);
        });
}
项目:mycore    文件:MCRURNObjectXPathMetadataManager.java   
@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<Text> xp = xpfac.compile(xpath, Filters.text());
    List<Text> 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();
    }

    Text identifierText = evaluate.listIterator().next();
    String identifierString = identifierText.getTextNormalize();

    Optional<MCRDNBURN> parsedIdentifierOptional = PARSER.parse(identifierString);
    return parsedIdentifierOptional.map(MCRPersistentIdentifier.class::cast);
}
项目:mycore    文件:MCRRestAPIClassifications.java   
/**
 * 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();
}
项目:mycore    文件:MCRRestAPIObjectsHelper.java   
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
            }

        }
    }
}
项目:mycore    文件:MCRLayoutUtilities.java   
/**
 * 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();
}
项目:mycore    文件:MCREditorOutValidator.java   
/**
 * 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;
}
项目:mycore    文件:MCRXSLInfoServlet.java   
private void listTemplates() {
    List<Element> list = xsl.getChildren("template", MCRConstants.XSL_NAMESPACE);
    IteratorIterable<Element> callTemplateElements = xsl
        .getDescendants(Filters.element("call-template", MCRConstants.XSL_NAMESPACE));
    LinkedList<Element> templates = new LinkedList<>(list);
    HashSet<String> callNames = new HashSet<>();
    for (Element callTemplate : callTemplateElements) {
        String name = callTemplate.getAttributeValue("name");
        if (callNames.add(name)) {
            templates.add(callTemplate);
        }
    }
    for (Element template : templates) {
        Element copy = template.clone();
        copy.removeContent();
        this.templates.add(copy);
    }
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void singleTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/oneObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(1, userFieldTags.size());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void multiTransform()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/multiplObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    //        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //        xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycoreobject", Filters.element()).evaluate(resultXML);
    assertEquals(3, mycoreojectTags.size());

    List<Element> userFieldTags = XPathFactory.instance()
        .compile("/solr-document-container/source/user", Filters.element()).evaluate(resultXML);
    assertEquals(3, userFieldTags.size());
}
项目:mycore    文件:MCRMycoreObjectSolrXSLTest.java   
@Test
public void derivates()
    throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException {
    String testFilePath = "/" + getClass().getSimpleName() + "/xml/derivateObj.xml";
    InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath);

    //        JDOMResult jdomResult = xslTransformation(testXMLAsStream, "/" + getClass().getSimpleName() + "/xsl/mcr2solrOld.xsl");
    JDOMResult jdomResult = xslTransformation(testXMLAsStream);

    Document resultXML = jdomResult.getDocument();

    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    xmlOutputter.output(resultXML, System.out);

    List<Element> mycoreojectTags = XPathFactory.instance()
        .compile("/solr-document-container/source/mycorederivate", Filters.element()).evaluate(resultXML);
    assertEquals(1, mycoreojectTags.size());
}
项目:contestparser    文件:HolidayEndpoint.java   
@Autowired
public HolidayEndpoint(HumanResourceService humanResourceService)
        throws JDOMException, XPathFactoryConfigurationException,
        XPathExpressionException {
    this.humanResourceService = humanResourceService;

    Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);

    XPathFactory xPathFactory = XPathFactory.instance();

    this.startDateExpression = xPathFactory.compile("//hr:StartDate",
            Filters.element(), null, namespace);
    this.endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(),
            null, namespace);
    this.nameExpression = xPathFactory.compile(
            "concat(//hr:FirstName,' ',//hr:LastName)", Filters.fstring(), null,
            namespace);
}
项目:DeadReckoning    文件:CarPark.java   
private static String getName(Document doc) {

        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Attribute> exprAttribute = xFactory.compile(
                "/osm/relation" + "[member]" + "[tag/@k='name' and tag/@v]"
                        + "[tag/@k='type' and tag/@v='site']"
                        + "[tag/@k='site' and tag/@v='parking']"
                        + "/tag[@k='name']/@v", Filters.attribute());
        Attribute nameAttribute = exprAttribute.evaluateFirst(doc);
        if (nameAttribute == null) {
            exprAttribute = xFactory
                    .compile(
                            "/osm/way[tag/@k='amenity' and tag/@v='parking']/tag[@k='name']/@v",
                            Filters.attribute());
            nameAttribute = exprAttribute.evaluateFirst(doc);
        }
        String name = nameAttribute.getValue();
        return name;

    }
项目:DeadReckoning    文件:CarPark.java   
private static Map<Integer, GeoNode> getNodes(Document doc) {
    Map<Integer, GeoNode> nList = new HashMap<Integer, GeoNode>();

    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> exprElement = xFactory.compile(
            "/osm/node[@id and @lat and @lon]", Filters.element());
    List<Element> nodesEle = exprElement.evaluate(doc);
    for (Element nele : nodesEle) {

        GeoNode n = null;
        try {
            int id = nele.getAttribute("id").getIntValue();
            double lat = nele.getAttribute("lat").getDoubleValue();
            double lon = nele.getAttribute("lon").getDoubleValue();
            n = new GeoNode(id, lat, lon, 0);
        } catch (DataConversionException e) {
            e.printStackTrace();
        }
        nList.put(n.id, n);
    }

    return nList;
}
项目:DeadReckoning    文件:CarParkGraph.java   
public static Map<Integer, GeoNode> getNodes(Document doc) {
    Map<Integer, GeoNode> nList = new HashMap<Integer, GeoNode>();

    XPathFactory xFactory = XPathFactory.instance();
    XPathExpression<Element> exprElement = xFactory.compile(
            "/osm/node[@id and @lat and @lon]", Filters.element());
    List<Element> nodesEle = exprElement.evaluate(doc);
    for (Element nele : nodesEle) {

        GeoNode n = null;
        try {
            int id = nele.getAttribute("id").getIntValue();
            double lat = nele.getAttribute("lat").getDoubleValue();
            double lon = nele.getAttribute("lon").getDoubleValue();
            n = new GeoNode(id, lat, lon, 0);
        } catch (DataConversionException e) {
            e.printStackTrace();
        }
        nList.put(n.id, n);
    }

    return nList;
}
项目:DeadReckoning    文件:Reader.java   
public Reader(File file, String name) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data[@" + Data.NAMETAG + "='" + name + "']",
                Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:DeadReckoning    文件:Reader.java   
public Reader(File file) {
    SAXBuilder builder = new SAXBuilder();
    try {

        doc = (Document) builder.build(file);
        Element root = doc.getRootElement();

        // use the default implementation
        XPathFactory xFactory = XPathFactory.instance();
        // System.out.println(xFactory.getClass());

        // select all data for motion sensor
        XPathExpression<Element> expr = xFactory.compile(
                "/SensorData/data", Filters.element());

        it = expr.evaluate(doc).iterator();

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}
项目:wot_gateways    文件:DatapointLocator.java   
/**
 * List all datapoints of a functionality
 * 
 * @param p_functionality
 *            The name of the group to perform the action on. For example in
 *            the url kitchen_light.ground.home.com the functionality would
 *            be kitchen_light
 * @param p_location
 *            The middle dns name of the url without the top level domain.
 *            For example in the url kitchen_light.ground.home.com the
 *            location would be ground.home
 * @return An ArrayList of datapoints descriptions
 */
public ArrayList<DatapointDescription> listDatapoints(
        String p_functionality, String p_location) {
    ArrayList<DatapointDescription> l_dps = new ArrayList<DatapointDescription>();
    // Create the xpath expression to find the datapoint
    XPathExpression<Element> l_xpath = XPathFactory
            .instance()
            .compile(
                    "/datapoints/datapoint[lower-case(@location)='"
                            + p_location.toLowerCase()
                            + "' and translate(lower-case(@name), 'àäâéèêëüûùôöò', 'aaaeeeeuuuooo')='"
                            + p_functionality.toLowerCase() + "']",
                    Filters.element());
    List<Element> l_elements = l_xpath.evaluate(m_Document);
    for (int i = 0; i < l_elements.size(); i++) {
        l_dps.add(new DatapointDescription(l_elements.get(i)
                .getAttributeValue("actionName"), l_elements.get(i)
                .getAttributeValue("dptID"), l_elements.get(i)
                .getAttributeValue("actionDesc"), l_elements.get(i)
                .getAttributeValue("dptDesc"), Integer.parseInt(l_elements
                .get(i).getAttributeValue("dptBitsSize"))));
    }

    return l_dps;
}
项目:jodtemplate    文件:FormatTagsPreprocessor.java   
@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) {
    final IteratorIterable<Element> apElements = document.getDescendants(Filters.element(PPTXDocument.P_ELEMENT,
            getNamespace()));
    final List<Element> apElementsList = new ArrayList<>();
    while (apElements.hasNext()) {
        apElementsList.add(apElements.next());
    }
    for (Element ap : apElementsList) {
        final List<Element> apChildrenList = ap.getChildren();
        if (apChildrenList.size() != 0) {
            final List<Element> arabrElementsListResult = processArAndABrElements(apChildrenList, configuration
                    .getParserFactory().createParser());
            int firstArElementIndex = ap.indexOf(ap.getChild(PPTXDocument.R_ELEMENT, getNamespace()));
            if (firstArElementIndex < 0) {
                firstArElementIndex = 0;
            }
            ap.removeChildren(PPTXDocument.R_ELEMENT, getNamespace());
            ap.removeChildren(PPTXDocument.BR_ELEMENT, getNamespace());
            ap.addContent(firstArElementIndex, arabrElementsListResult);
        }
    }
    return document;
}
项目:jodtemplate    文件:StylePostprocessor.java   
@Override
public Document process(final Map<String, Object> context, final Document document, final Slide slide,
        final Resources resources, final Configuration configuration) throws JODTemplateException {
    final IteratorIterable<Element> atElements = document.getDescendants(Filters.element(PPTXDocument.T_ELEMENT,
            getNamespace()));
    final List<Element> atElementsList = new ArrayList<>();
    while (atElements.hasNext()) {
        atElementsList.add(atElements.next());
    }
    for (Element at : atElementsList) {
        if (at.getContentSize() != 0) {
            final Content content = at.getContent(0);
            if (content instanceof Comment) {
                final Comment comment = (Comment) content;
                processComment(comment, at, slide, configuration);
            }
        }
    }
    return document;
}
项目:marmotta    文件:XPathFunction.java   
private LinkedList<String> doFilter(String in, Set<String> xpaths) throws IOException {
    LinkedList<String> result = new LinkedList<String>();
    try {
        Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(new StringReader(in));
        XMLOutputter out = new XMLOutputter();

        for (String xp : xpaths) {
            XPathExpression<Content> xpath = XPathFactory.instance().compile(xp, Filters.content());
            for (Content node : xpath.evaluate(doc)) {
                if(node instanceof Element) {
                    result.add(out.outputString((Element) node));
                } else if(node instanceof Text) {
                    result.add(out.outputString((Text) node));
                }
            }
        }
        return result;
    } catch (JDOMException xpe) {
        throw new IllegalArgumentException("error while processing xpath expressions: '" + xpaths + "'", xpe);
    }
}