org.jdom2.Attribute Java Examples

The following examples show how to use org.jdom2.Attribute. 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: MCRChangeTrackerTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testBreakpoint() {
    Element root = new Element("root");
    Document doc = new Document(root);

    MCRChangeTracker tracker = new MCRChangeTracker();

    Element title = new Element("title");
    root.addContent(title);
    tracker.track(MCRAddedElement.added(title));

    tracker.track(MCRBreakpoint.setBreakpoint(root, "Test"));

    Attribute href = new Attribute("href", "foo", MCRConstants.XLINK_NAMESPACE);
    root.setAttribute(href);
    tracker.track(MCRAddedAttribute.added(href));

    tracker.track(MCRSetAttributeValue.setValue(href, "bar"));

    String label = tracker.undoLastBreakpoint(doc);
    assertEquals("Test", label);
    assertNull(root.getAttribute("href"));
    assertEquals(1, tracker.getChangeCounter());
}
 
Example #2
Source File: LegacyKitParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Kit parse(Element el) throws InvalidXMLException {
  Kit kit;
  Attribute attrName = el.getAttribute("name");

  if (attrName != null && maybeReference(el)) {
    kit = parseReference(new Node(el), attrName.getValue());
  } else {
    kit = parseDefinition(el);

    if (attrName != null) {
      try {
        kitContext.add(attrName.getValue(), kit);
      } catch (IllegalArgumentException e) {
        // Probably a duplicate name
        throw new InvalidXMLException(e.getMessage(), el);
      }
    } else {
      kitContext.add(kit);
    }
  }

  return kit;
}
 
Example #3
Source File: PointParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Parse any number of {@link PointProvider}s in attributes or children of the given names. */
public List<PointProvider> parseMultiProperty(
    Element el, PointProviderAttributes attributes, String... aliases)
    throws InvalidXMLException {
  attributes = parseAttributes(el, attributes);

  List<PointProvider> providers = new ArrayList<>();
  for (Attribute attr : XMLUtils.getAttributes(el, aliases)) {
    providers.add(
        new RegionPointProvider(
            validate(regionParser.parseReference(attr), new Node(attr)), attributes));
  }
  for (Element child : XMLUtils.getChildren(el, aliases)) {
    providers.add(
        new RegionPointProvider(
            validate(regionParser.parseChild(child), new Node(child)),
            parseAttributes(child, attributes)));
  }
  return providers;
}
 
Example #4
Source File: MCRNodeBuilderTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testBuildingAttributes() throws JaxenException, JDOMException {
    Attribute built = new MCRNodeBuilder().buildAttribute("@attribute", null, null);
    assertNotNull(built);
    assertEquals("attribute", built.getName());
    assertTrue(built.getValue().isEmpty());

    built = new MCRNodeBuilder().buildAttribute("@attribute", "value", null);
    assertNotNull(built);
    assertEquals("attribute", built.getName());
    assertEquals("value", built.getValue());

    Element parent = new Element("parent");
    built = new MCRNodeBuilder().buildAttribute("@attribute", null, parent);
    assertNotNull(built);
    assertEquals("attribute", built.getName());
    assertNotNull(built.getParent());
    assertEquals("parent", built.getParent().getName());
}
 
Example #5
Source File: Atom10Generator.java    From rome with Apache License 2.0 6 votes vote down vote up
protected Element generateTagLineElement(final Content tagline) {

        final Element taglineElement = new Element("subtitle", getFeedNamespace());

        final String type = tagline.getType();
        if (type != null) {
            final Attribute typeAttribute = new Attribute("type", type);
            taglineElement.setAttribute(typeAttribute);
        }

        final String value = tagline.getValue();
        if (value != null) {
            taglineElement.addContent(value);
        }

        return taglineElement;

    }
 
Example #6
Source File: ConfigSupport.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Element findElementWithAttributeValue(Element element, String name, String attrName, String attrValue, Namespace... supportedNamespaces) {
    for (Namespace ns : supportedNamespaces) {
        if (element.getName().equals(name) && element.getNamespace().equals(ns)) {
            Attribute attribute = element.getAttribute(attrName);
            if (attribute != null && attrValue.equals(attribute.getValue())) {
                return element;
            }
        }
        for (Element ch : (List<Element>) element.getChildren()) {
            Element result = findElementWithAttributeValue(ch, name, attrName, attrValue, supportedNamespaces);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}
 
Example #7
Source File: MCRChangeTrackerTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #8
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 #9
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Считать атрибуты другой схемы
 *
 * @param element   элемент
 * @param namespace схема, атрибуты которой нужно считать
 * @param map       мапа, в которую считать атрибуты схемы
 */
@Override
public void otherAttributes(Element element, Namespace namespace, Map<String, String> map) {
    if (r) {
        for (Object o : element.getAttributes()) {
            Attribute attribute = (Attribute) o;
            if (attribute.getNamespace().equals(namespace)) {
                map.put(attribute.getName(), attribute.getValue());
            }
        }
    } else {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            element.setAttribute(new Attribute(entry.getKey(), entry.getValue(), namespace));
        }
    }
}
 
Example #10
Source File: OpenSearchModuleParser.java    From rome with Apache License 2.0 6 votes vote down vote up
/**
 * Use xml:base attributes at feed and entry level to resolve relative links
 */
private static String resolveURI(final URL baseURI, final Parent parent, String url) {
    url = url.equals(".") || url.equals("./") ? "" : url;
    if (isRelativeURI(url) && parent != null && parent instanceof Element) {
        final Attribute baseAtt = ((Element) parent).getAttribute("base", Namespace.XML_NAMESPACE);
        String xmlBase = baseAtt == null ? "" : baseAtt.getValue();
        if (!isRelativeURI(xmlBase) && !xmlBase.endsWith("/")) {
            xmlBase = xmlBase.substring(0, xmlBase.lastIndexOf("/") + 1);
        }
        return resolveURI(baseURI, parent.getParent(), xmlBase + url);
    } else if (isRelativeURI(url) && parent == null) {
        return baseURI + url;
    } else if (baseURI != null && url.startsWith("/")) {
        String hostURI = baseURI.getProtocol() + "://" + baseURI.getHost();
        if (baseURI.getPort() != baseURI.getDefaultPort()) {
            hostURI = hostURI + ":" + baseURI.getPort();
        }
        return hostURI + url;
    }
    return url;
}
 
Example #11
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
@Override
public <T extends Enum<T>> void attributeEnum(Element element, String name, Supplier<T> getter, Consumer<T> setter, Class<T> enumClass) {
    if (r) {
        Attribute attribute = element.getAttribute(name);
        if (attribute != null) {
            setter.accept(stringToEnum(process(attribute.getValue()), enumClass));
        }
    } else {
        if (getter.get() == null) return;
        if (IdAware.class.isAssignableFrom(enumClass)) {
            element.setAttribute(new Attribute(name, ((IdAware) getter.get()).getId()));
        } else {
            element.setAttribute(new Attribute(name, getter.get().name()));
        }
    }
}
 
Example #12
Source File: MCRNodeBuilderTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testBuildingValues() throws JaxenException, JDOMException {
    Attribute built = new MCRNodeBuilder().buildAttribute("@attribute='A \"test\"'", "ignore", null);
    assertNotNull(built);
    assertEquals("attribute", built.getName());
    assertEquals("A \"test\"", built.getValue());

    built = new MCRNodeBuilder().buildAttribute("@attribute=\"O'Brian\"", null, null);
    assertNotNull(built);
    assertEquals("attribute", built.getName());
    assertEquals("O'Brian", built.getValue());

    built = new MCRNodeBuilder().buildAttribute("@mime=\"text/plain\"", null, null);
    assertNotNull(built);
    assertEquals("mime", built.getName());
    assertEquals("text/plain", built.getValue());

    Element element = new MCRNodeBuilder().buildElement("name=\"O'Brian\"", null, null);
    assertNotNull(element);
    assertEquals("name", element.getName());
    assertEquals("O'Brian", element.getText());
}
 
Example #13
Source File: MCRXMLCleaner.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private boolean clean(Element element) {
    boolean changed = false;

    for (Iterator<Element> children = element.getChildren().iterator(); children.hasNext();) {
        Element child = children.next();
        if (clean(child)) {
            changed = true;
        }
        if (!isRelevant(child)) {
            changed = true;
            children.remove();
        }
    }

    for (Iterator<Attribute> attributes = element.getAttributes().iterator(); attributes.hasNext();) {
        Attribute attribute = attributes.next();
        if (!isRelevant(attribute)) {
            changed = true;
            attributes.remove();
        }
    }

    return changed;
}
 
Example #14
Source File: MCRNodeBuilder.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Resolves the first match for the given XPath and returns its value as a String 
 * 
 * @param xPath the XPath expression
 * @param parent the context element or document 
 * @return the value of the element or attribute as a String
 */
public String getValueOf(String xPath, Parent parent) {
    Object result = evaluateFirst(xPath, parent);

    if (result instanceof String) {
        return (String) result;
    } else if (result instanceof Element) {
        return ((Element) result).getText();
    } else if (result instanceof Attribute) {
        return ((Attribute) result).getValue();
    } else {
        return null;
    }
}
 
Example #15
Source File: ConfigUtil.java    From gocd with Apache License 2.0 5 votes vote down vote up
public String getAttribute(Element e, String attribute) {
    Attribute attr = e.getAttribute(attribute);
    if(attr == null) {
        throw bomb("Error finding attribute '" + attribute + "' in config: " + configFile + elementOutput(e));
    }
    return attr.getValue();
}
 
Example #16
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Pair<org.bukkit.attribute.Attribute, AttributeModifier> parseAttributeModifier(Element el) throws InvalidXMLException {
    return Pair.create(
        parseAttribute(new Node(el)),
        new AttributeModifier(
            "FromXML",
            parseNumber(Node.fromRequiredAttr(el, "amount"), Double.class),
            parseAttributeOperation(Node.fromAttr(el, "operation"), AttributeModifier.Operation.ADD_NUMBER)
        )
    );
}
 
Example #17
Source File: Node.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * If this Node is wrapping an Attribute, returns the same as {@link #getValue()}. If this Node is
 * wrapping an Element, returns {@link Element#getTextNormalize()}.
 */
public String getValueNormalize() {
  if (this.node instanceof Attribute) {
    return ((Attribute) this.node).getValue();
  } else {
    return ((Element) this.node).getTextNormalize();
  }
}
 
Example #18
Source File: LegacyRegionParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public Region parseReference(Attribute attr) throws InvalidXMLException {
  String name = attr.getValue();
  Region region = this.regionContext.get(name);
  if (region == null) {
    throw new InvalidXMLException("Unknown region '" + name + "'", attr);
  } else {
    return region;
  }
}
 
Example #19
Source File: RegionParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@MethodParser("translate")
public TranslatedRegion parseTranslate(Element el) throws InvalidXMLException {
  Attribute offsetAttribute = el.getAttribute("offset");
  if (offsetAttribute == null) {
    throw new InvalidXMLException("Translate region must have an offset", el);
  }
  Vector offset = XMLUtils.parseVector(offsetAttribute);
  return new TranslatedRegion(this.parseChildren(el), offset);
}
 
Example #20
Source File: GPXFileWriter.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void writeGPXFile(File target, String trackName, boolean extensions, Cursor cTrackPoints, Cursor cWayPoints, Context context)
        throws IOException {

    Document doc = new Document();
    Element gpx = new Element("gpx", NS);
    Namespace xsi = Namespace.getNamespace("xsi", XSI);
    gpx.addNamespaceDeclaration(xsi);
    Namespace bpt2 = Namespace.getNamespace("bpt2", BPT);
    gpx.addNamespaceDeclaration(bpt2);
    gpx.setAttribute("schemaLocation", XSD, xsi);
    gpx.setAttribute(new Attribute("version", "1.1"));
    gpx.setAttribute(new Attribute("creator", CREATOR));
    gpx.addContent(getWayPoints(extensions, cWayPoints, bpt2, context));
    gpx.addContent(getTrackpoints(trackName, extensions, cTrackPoints, bpt2, context));
    doc.setRootElement(gpx);

    FileWriter fw = null;
    try {
        fw = new FileWriter(target);
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        xout.output(doc, fw);
        fw.flush();
    } finally {
        if (fw != null)
            fw.close();
    }

    // http://www.topografix.com/gpx/1/1/gpx.xsd
    // xmllint --noout --schema gpx.xsd BackPackTrack.gpx
}
 
Example #21
Source File: SSE091Parser.java    From rome with Apache License 2.0 5 votes vote down vote up
private Date parseDateAttribute(final Element childElement, final String attrName, final Locale locale) {
    final Attribute dateAttribute = childElement.getAttribute(attrName);
    final Date date = null;
    if (dateAttribute != null) {
        // SSE spec requires the timezone to be 'GMT'
        // admittedly, this is a bit heavy-handed
        final String dateAttr = dateAttribute.getValue().trim();
        return DateParser.parseRFC822(dateAttr, locale);
    }
    return date;
}
 
Example #22
Source File: Database.java    From CardinalPGM with MIT License 5 votes vote down vote up
private Element getKey(Element element, String key) {
    for (Element child : element.getChildren("data")) {
        if (key.equals(child.getAttributeValue("key"))) return child;
    }
    Element newElement = new Element(("data")).setAttribute(new Attribute("key", key)).setAttribute("value", "");
    element.addContent(newElement);
    return newElement;
}
 
Example #23
Source File: ReaderJdomUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static String getAttributeString(Element element, String attribute) {
    if (element == null) return null;
    Attribute attr = element.getAttribute(attribute);
    if (attr != null) {
        return getText(attr);
    }
    return null;
}
 
Example #24
Source File: GPXFileWriter.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void writeGeonames(List<Geonames.Geoname> names, File target, Context context) throws IOException {
    Document doc = new Document();
    Element gpx = new Element("gpx", NS);
    Namespace xsi = Namespace.getNamespace("xsi", XSI);
    gpx.addNamespaceDeclaration(xsi);
    Namespace bpt2 = Namespace.getNamespace("bpt2", BPT);
    gpx.addNamespaceDeclaration(bpt2);
    gpx.setAttribute("schemaLocation", XSD, xsi);
    gpx.setAttribute(new Attribute("version", "1.1"));
    gpx.setAttribute(new Attribute("creator", CREATOR));

    Collection<Element> wpts = new ArrayList<>();
    for (Geonames.Geoname name : names) {
        Element wpt = new Element("wpt", NS);
        wpt.setAttribute(new Attribute("lat", Double.toString(name.location.getLatitude())));
        wpt.setAttribute(new Attribute("lon", Double.toString(name.location.getLongitude())));
        wpt.addContent(new Element("name", NS).addContent(name.name));
        wpts.add(wpt);
    }
    gpx.addContent(wpts);

    doc.setRootElement(gpx);

    FileWriter fw = null;
    try {
        fw = new FileWriter(target);
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        xout.output(doc, fw);
        fw.flush();
    } finally {
        if (fw != null)
            fw.close();
    }
}
 
Example #25
Source File: RegionParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Parse the given element as a wrapper for a single child region, which will be the union of the
 * region referenced by the region="..." attribute (if any) and all nested regions.
 */
public Region parseChildren(Element parent) throws InvalidXMLException {
  Attribute attrRegion = parent.getAttribute("region");
  Region reference = attrRegion == null ? null : this.parseReference(attrRegion);
  List<Region> regions = this.parseSubRegions(parent);

  if (reference != null) regions.add(reference);

  return Union.of(regions.toArray(new Region[0]));
}
 
Example #26
Source File: Node.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static int startLine(Object node) {
    if(node instanceof BoundedElement) {
        return ((BoundedElement) node).getStartLine();
    } else if(node instanceof Located) {
        return ((Located) node).getLine();
    } else if(node instanceof Attribute) {
        return startLine(((Attribute) node).getParent());
    } else {
        return 0;
    }
}
 
Example #27
Source File: Node.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getDescription() {
  if (node instanceof Element) {
    return describe((Element) node);
  } else {
    Attribute attr = (Attribute) node;
    return "'" + attr.getName() + "' attribute of " + describe(attr.getParent());
  }
}
 
Example #28
Source File: MCRBinding.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static String getValue(Object node) {
    if (node instanceof Element) {
        return ((Element) node).getTextTrim();
    } else {
        return ((Attribute) node).getValue();
    }
}
 
Example #29
Source File: MCRBinding.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void trackNodeCreated(Object node) {
    if (node instanceof Element) {
        Element element = (Element) node;
        MCRChangeTracker.removeChangeTracking(element);
        track(MCRAddedElement.added(element));
    } else {
        Attribute attribute = (Attribute) node;
        track(MCRAddedAttribute.added(attribute));
    }
}
 
Example #30
Source File: TeamModule.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public TeamFactory parseTeam(Attribute attr, MapFactory factory) throws InvalidXMLException {
  if (attr == null) {
    return null;
  }
  String name = attr.getValue();
  TeamFactory team = Teams.getTeam(name, factory);

  if (team == null) {
    throw new InvalidXMLException("unknown team '" + name + "'", attr);
  }
  return team;
}