Java Code Examples for org.jdom2.Element#getAttribute()

The following examples show how to use org.jdom2.Element#getAttribute() . 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: 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 2
Source File: MCRMODSMetadataShareAgent.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Recursivly checks <code>relatedItem</code> and parent &lt;mods:relatedItem&gt; elements for multiple {@link MCRObjectID}s.
 * @param relatedItem &lt;mods:relatedItem&gt;
 * @param idCollected of IDs collected so far
 * @throws MCRPersistenceException if {@link MCRObjectID} of <code>relatedItem</code> is in <code>idCollected</code>
 */
private void checkHierarchy(Element relatedItem, Set<MCRObjectID> idCollected) throws MCRPersistenceException {
    final Attribute href = relatedItem.getAttribute("href", MCRConstants.XLINK_NAMESPACE);
    if (href != null) {
        final String testId = href.getValue();
        LOGGER.debug("Checking relatedItem {}.", testId);
        if (MCRObjectID.isValid(testId)) {
            final MCRObjectID relatedItemId = MCRObjectID.getInstance(testId);
            LOGGER.debug("Checking if {} is in {}.", relatedItemId, idCollected);
            if (!idCollected.add(relatedItemId)) {
                throw new MCRPersistenceException(
                    "Hierarchy of mods:relatedItem contains ciruit by object " + relatedItemId);
            }
        }
    }
    final Element parentElement = relatedItem.getParentElement();
    if (parentElement.getName().equals("relatedItem")) {
        checkHierarchy(parentElement, idCollected);
    }
}
 
Example 3
Source File: LegacyFilterParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
protected List<Filter> parseParents(Element el) throws InvalidXMLException {
  List<Filter> parents = new ArrayList<Filter>();
  if (el.getAttribute("parents") == null) {
    return parents;
  }
  String[] parentNames = el.getAttributeValue("parents").split(" ");
  for (String name : parentNames) {
    Filter filter = this.filterContext.get(name);
    if (filter == null) {
      throw new InvalidXMLException("Parent '" + name + "' can not be found", el);
    } else {
      parents.add(filter);
    }
  }
  return parents;
}
 
Example 4
Source File: MCREditorOutValidator.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param metadata
 */
private void checkObjectMetadata(Element metadata) {
    if (metadata.getAttribute("lang") != null) {
        metadata.getAttribute("lang").setNamespace(XML_NAMESPACE);
    }

    List<Element> metadatalist = metadata.getChildren();
    Iterator<Element> metaIt = metadatalist.iterator();

    while (metaIt.hasNext()) {
        Element datatag = metaIt.next();
        if (!checkMetaTags(datatag)) {
            // e.g. datatag is empty
            LOGGER.debug("Removing element :{}", datatag.getName());
            metaIt.remove();
        }
    }
}
 
Example 5
Source File: ProximityAlarmModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public static ProximityAlarmDefinition parseDefinition(MapModuleContext context, Element elAlarm) throws InvalidXMLException {
    ProximityAlarmDefinition definition = new ProximityAlarmDefinition();
    FilterParser filterParser = context.needModule(FilterParser.class);
    definition.detectFilter = filterParser.parseProperty(elAlarm, "detect");
    definition.alertFilter = filterParser.property(elAlarm, "notify").optionalGet(() -> new InverseFilter(definition.detectFilter));
    definition.detectRegion = context.needModule(RegionParser.class).property(elAlarm, "region").required();
    definition.alertMessage = elAlarm.getAttributeValue("message"); // null = no message

    if(definition.alertMessage != null) {
        definition.alertMessage = ChatColor.translateAlternateColorCodes('`', definition.alertMessage);
    }
    Attribute attrFlareRadius = elAlarm.getAttribute("flare-radius");
    definition.flares = attrFlareRadius != null;
    if(definition.flares) {
        definition.flareRadius = XMLUtils.parseNumber(attrFlareRadius, Double.class);
    }

    return definition;
}
 
Example 6
Source File: ReaderJdomUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static Boolean getAttributeBoolean(Element element, String attribute) {
    if (element == null) return null;
    if (element.getAttribute(attribute) != null) {
        return Boolean.valueOf(getText(element.getAttribute(attribute)));
    }
    return null;
}
 
Example 7
Source File: ReaderJdomUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static <T extends Enum<T>> T getAttributeEnum(Element element, String attribute, Class<T> enumClass) {
    if (element.getAttribute(attribute) != null) {
        String value = getText(element.getAttribute(attribute));
        return stringToEnum(value, enumClass);
    }
    return null;
}
 
Example 8
Source File: NmasResponseSet.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ChallengeSet parseNmasUserResponseXML( final String str )
        throws IOException, JDOMException, ChaiValidationException
{
    final List<Challenge> returnList = new ArrayList<Challenge>();

    final Reader xmlreader = new StringReader( str );
    final SAXBuilder builder = new SAXBuilder();
    final Document doc = builder.build( xmlreader );

    final Element rootElement = doc.getRootElement();
    final int minRandom = StringHelper.convertStrToInt( rootElement.getAttributeValue( "RandomQuestions" ), 0 );

    final String guidValue;
    {
        final Attribute guidAttribute = rootElement.getAttribute( "GUID" );
        guidValue = guidAttribute == null ? null : guidAttribute.getValue();
    }

    for ( Iterator iter = doc.getDescendants( new ElementFilter( "Challenge" ) ); iter.hasNext(); )
    {
        final Element loopQ = ( Element ) iter.next();
        final int maxLength = StringHelper.convertStrToInt( loopQ.getAttributeValue( "MaxLength" ), 255 );
        final int minLength = StringHelper.convertStrToInt( loopQ.getAttributeValue( "MinLength" ), 2 );
        final String defineStrValue = loopQ.getAttributeValue( "Define" );
        final boolean adminDefined = "Admin".equalsIgnoreCase( defineStrValue );
        final String typeStrValue = loopQ.getAttributeValue( "Type" );
        final boolean required = "Required".equalsIgnoreCase( typeStrValue );
        final String challengeText = loopQ.getText();

        final Challenge challenge = new ChaiChallenge( required, challengeText, minLength, maxLength, adminDefined, 0, false );
        returnList.add( challenge );
    }

    return new ChaiChallengeSet( returnList, minRandom, null, guidValue );
}
 
Example 9
Source File: MCREditorOutValidator.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static String checkMetaObjectWithLinks(Element datasubtag, Class<? extends MCRMetaInterface> metaClass) {
    if (datasubtag.getAttributeValue("href") == null
        && datasubtag.getAttributeValue("href", XLINK_NAMESPACE) == null) {
        return datasubtag.getName() + " has no href attribute defined";
    }
    if (datasubtag.getAttribute("xtype") != null) {
        datasubtag.getAttribute("xtype").setNamespace(XLINK_NAMESPACE).setName("type");
    } else if (datasubtag.getAttribute("type") != null
        && datasubtag.getAttribute("type", XLINK_NAMESPACE) == null) {
        datasubtag.getAttribute("type").setNamespace(XLINK_NAMESPACE);
        LOGGER.warn("namespace add for xlink:type attribute in {}", datasubtag.getName());
    }
    if (datasubtag.getAttribute("href") != null) {
        datasubtag.getAttribute("href").setNamespace(XLINK_NAMESPACE);
        LOGGER.warn("namespace add for xlink:href attribute in {}", datasubtag.getName());
    }

    if (datasubtag.getAttribute("title") != null) {
        datasubtag.getAttribute("title").setNamespace(XLINK_NAMESPACE);
        LOGGER.warn("namespace add for xlink:title attribute in {}", datasubtag.getName());
    }

    if (datasubtag.getAttribute("label") != null) {
        datasubtag.getAttribute("label").setNamespace(XLINK_NAMESPACE);
        LOGGER.warn("namespace add for xlink:label attribute in {}", datasubtag.getName());
    }
    return checkMetaObject(datasubtag, metaClass, false);
}
 
Example 10
Source File: ConfigSupport.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static Map<String, Element> mapByAttributeName(List<Element> elements, String attrName) {
    LinkedHashMap<String, Element> rc = new LinkedHashMap<String, Element>();
    for (Element element : elements) {
        Attribute attribute = element.getAttribute(attrName);
        if (attribute != null) {
            rc.put(attribute.getValue(), element);
        }
    }
    return rc;
}
 
Example 11
Source File: PKDBF2Answer.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
public PKDBF2Answer fromXml( final Element element, final boolean caseInsensitive, final String challengeText )
{
    final String answerValue = element.getText();

    if ( answerValue == null || answerValue.length() < 1 )
    {
        throw new IllegalArgumentException( "missing answer value" );
    }

    final String salt = element.getAttribute( ChaiResponseSet.XML_ATTRIBUTE_SALT ) == null
            ? ""
            : element.getAttribute( ChaiResponseSet.XML_ATTRIBUTE_SALT ).getValue();
    final String hashCount = element.getAttribute( ChaiResponseSet.XML_ATTRIBUTE_HASH_COUNT ) == null
            ? "1"
            : element.getAttribute( ChaiResponseSet.XML_ATTRIBUTE_HASH_COUNT ).getValue();
    final String formatTypeStr = element.getAttributeValue( ChaiResponseSet.XML_ATTRIBUTE_CONTENT_FORMAT );
    final FormatType formatTypeEnum = FormatType.valueOf( formatTypeStr );
    int saltCount = 1;
    try
    {
        saltCount = Integer.parseInt( hashCount );
    }
    catch ( NumberFormatException e )
    {
        /* noop */
    }
    return new PKDBF2Answer( formatTypeEnum, answerValue, salt, saltCount, caseInsensitive );
}
 
Example 12
Source File: KitParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public ItemStack parseItem(Element el, boolean allowAir) throws InvalidXMLException {
  if (el == null) return null;

  org.jdom2.Attribute attrMaterial = el.getAttribute("material");
  String name = attrMaterial != null ? attrMaterial.getValue() : el.getValue();
  Material type = Materials.parseMaterial(name);
  if (type == null || (type == Material.AIR && !allowAir)) {
    throw new InvalidXMLException("Invalid material type '" + name + "'", el);
  }

  return parseItem(el, type);
}
 
Example 13
Source File: MCRLayoutUtilities.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected org.w3c.dom.Element printElement(FormatStack fstack, NamespaceStack nstack,
    org.w3c.dom.Document basedoc, Element element) {
    Attribute href = element.getAttribute("href");
    return (href == null || itemAccess(PERMISSION_READ, element, true)) ? super.printElement(fstack, nstack,
        basedoc, element) : null;
}
 
Example 14
Source File: ReaderJdomUtil.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
public static Integer getAttributeInteger(Element element, String attribute) {
    if (element == null) return null;
    if (element.getAttribute(attribute) != null) {
        try {
            return Integer.valueOf(getText(element.getAttribute(attribute)).trim());
        } catch (NumberFormatException e) {
            throw new MetadataReaderException(e);
        }
    }
    return null;
}
 
Example 15
Source File: IOProcessorImpl.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void attributeInteger(Element element, String name, Supplier<Integer> getter, Consumer<Integer> setter) {
    if (r) {
        Attribute attribute = element.getAttribute(name);
        if (attribute != null) {
            setter.accept(Integer.valueOf(process(attribute.getValue())));
        }
    } else {
        if (getter.get() == null) return;
        element.setAttribute(new Attribute(name, getter.get().toString()));
    }
}
 
Example 16
Source File: ExtractionTest.java    From emissary with Apache License 2.0 4 votes vote down vote up
protected void checkStringValue(Element meta, String data, String tname) {
    String key = meta.getChildTextTrim("name");
    String value = meta.getChildText("value");
    String matchMode = "equals";
    Attribute mm = meta.getAttribute("matchMode");

    if (value == null) {
        return; // checking the value is optional
    }

    if (mm != null) {
        matchMode = mm.getValue();
    }

    if (matchMode.equals("equals")) {
        assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not equal '" + value + "'",
                value, data);
    } else if (matchMode.equals("index")) {
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not index '" + value + "'",
                data.indexOf(value) > -1);
    } else if (matchMode.equals("match")) {
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
                data.matches(value));
    } else if (matchMode.equals("base64")) {
        // decode value as a base64 encoded byte[] array and use the string
        // representation of the byte array for comparison to the incoming value
        value = new String(DatatypeConverter.parseBase64Binary(value));
        assertEquals(meta.getName() + " element '" + key + "' problem in " + tname + " value '" + data + "' does not match '" + value + "'",
                value, data);
    } else if ("collection".equalsIgnoreCase(matchMode)) {
        Attribute separatorAttribute = meta.getAttribute("collectionSeparator");
        String separator = null != separatorAttribute ? separatorAttribute.getValue() : ","; // comma is default
        // separator
        Collection<String> expectedValues = Arrays.asList(value.split(separator));
        Collection<String> actualValues = Arrays.asList(data.split(separator));
        assertTrue(meta.getName() + " element '" + key + "' problem in " + tname + " did not have equal collection, value ' " + data
                + "' does not equal '" + value + "' split by separator '" + separator + "'",
                CollectionUtils.isEqualCollection(expectedValues, actualValues));

    } else {
        fail("Problematic matchMode specified for test '" + matchMode + "' on " + key + " in element " + meta.getName());
    }
}
 
Example 17
Source File: ContentModuleParser.java    From rome with Apache License 2.0 4 votes vote down vote up
@Override
public com.rometools.rome.feed.module.Module parse(final Element element, final Locale locale) {
    boolean foundSomething = false;
    final ContentModule cm = new ContentModuleImpl();
    final List<Element> encodeds = element.getChildren("encoded", CONTENT_NS);
    final ArrayList<String> contentStrings = new ArrayList<String>();
    final ArrayList<String> encodedStrings = new ArrayList<String>();

    if (!encodeds.isEmpty()) {
        foundSomething = true;

        for (int i = 0; i < encodeds.size(); i++) {
            final Element encodedElement = encodeds.get(i);
            encodedStrings.add(encodedElement.getText());
            contentStrings.add(encodedElement.getText());
        }
    }

    final ArrayList<ContentItem> contentItems = new ArrayList<ContentItem>();
    final List<Element> items = element.getChildren("items", CONTENT_NS);

    for (int i = 0; i < items.size(); i++) {
        foundSomething = true;

        final List<Element> lis = items.get(i).getChild("Bag", RDF_NS).getChildren("li", RDF_NS);

        for (int j = 0; j < lis.size(); j++) {
            final ContentItem ci = new ContentItem();
            final Element li = lis.get(j);
            final Element item = li.getChild("item", CONTENT_NS);
            final Element format = item.getChild("format", CONTENT_NS);
            final Element encoding = item.getChild("encoding", CONTENT_NS);
            final Element value = item.getChild("value", RDF_NS);

            if (value != null) {
                if (value.getAttributeValue("parseType", RDF_NS) != null) {
                    ci.setContentValueParseType(value.getAttributeValue("parseType", RDF_NS));
                }

                if (ci.getContentValueParseType() != null && ci.getContentValueParseType().equals("Literal")) {
                    ci.setContentValue(getXmlInnerText(value));
                    contentStrings.add(getXmlInnerText(value));
                    ci.setContentValueNamespaces(value.getAdditionalNamespaces());
                } else {
                    ci.setContentValue(value.getText());
                    contentStrings.add(value.getText());
                }

                ci.setContentValueDOM(value.clone().getContent());
            }

            if (format != null) {
                ci.setContentFormat(format.getAttribute("resource", RDF_NS).getValue());
            }

            if (encoding != null) {
                ci.setContentEncoding(encoding.getAttribute("resource", RDF_NS).getValue());
            }

            if (item != null) {
                final Attribute about = item.getAttribute("about", RDF_NS);

                if (about != null) {
                    ci.setContentAbout(about.getValue());
                }
            }

            contentItems.add(ci);
        }
    }

    cm.setEncodeds(encodedStrings);
    cm.setContentItems(contentItems);
    cm.setContents(contentStrings);

    return foundSomething ? cm : null;
}
 
Example 18
Source File: YTask.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected boolean isPopulatedEmptyTypeFlag(String expression) {
    Element elem = getElementForXQuery(_net.getInternalDataDocument(), expression);
    return (elem != null) && (elem.getAttribute("__emptyComplexTypeFlag__") != null);
}
 
Example 19
Source File: ApiXmlBacklinksResult.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Execute back links request.
 * 
 * @param properties Properties defining request.
 * @param page Page.
 * @param list List of pages to be filled with the back links.
 * @return True if request should be continued.
 * @throws APIException Exception thrown by the API.
 */
@Override
public boolean executeBacklinks(
    Map<String, String> properties,
    Page page,
    List<Page> list)
        throws APIException {
  try {
    Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS);

    // Retrieve back links
    XPathExpression<Element> xpa = XPathFactory.instance().compile(
        "/api/query/backlinks/bl", Filters.element());
    List<Element> listBacklinks = xpa.evaluate(root);
    Iterator<Element> itBacklink = listBacklinks.iterator();
    XPathExpression<Element> xpaRedirLinks = XPathFactory.instance().compile(
        "redirlinks/bl", Filters.element());
    while (itBacklink.hasNext()) {
      Element currentBacklink = itBacklink.next();
      Page link = DataManager.getPage(
          getWiki(), currentBacklink.getAttributeValue("title"), null, null, null);
      link.setNamespace(currentBacklink.getAttributeValue("ns"));
      link.setPageId(currentBacklink.getAttributeValue("pageid"));
      if (currentBacklink.getAttribute("redirect") != null) {
        link.getRedirects().add(page, null); // TODO: Check if fragment is available
      }
      if (!list.contains(link)) {
        list.add(link);
      }

      // Links through redirects
      List<Element> listRedirLinks = xpaRedirLinks.evaluate(currentBacklink);
      if (listRedirLinks != null) {
        List<Page> linkList = new ArrayList<Page>();
        Iterator<Element> itRedirLink = listRedirLinks.iterator();
        while (itRedirLink.hasNext()) {
          currentBacklink = itRedirLink.next();
          Page link2 = DataManager.getPage(
              getWiki(), currentBacklink.getAttributeValue("title"), null, null, null);
          link2.setNamespace(currentBacklink.getAttributeValue("ns"));
          link2.setPageId(currentBacklink.getAttributeValue("pageid"));
          if (!list.contains(link2)) {
            list.add(link2);
          }
          if (!linkList.contains(link2)) {
            linkList.add(link2);
          }
        }
        link.setRelatedPages(Page.RelatedPages.BACKLINKS, linkList);
      }
    }

    // Retrieve continue
    return shouldContinue(
        root, "/api/query-continue/backlinks",
        properties);
  } catch (JDOMException e) {
    log.error("Error loading back links", e);
    throw new APIException("Error parsing XML", e);
  }
}
 
Example 20
Source File: GlobalItemParser.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public ItemStack parseItem(Element el, Material type, short damage) throws InvalidXMLException {
    int amount = XMLUtils.parseNumber(el.getAttribute("amount"), Integer.class, 1);

    // If the item is a potion with non-zero damage, and there is
    // no modern potion ID, decode the legacy damage value.
    final Potion legacyPotion;
    if(type == Material.POTION && damage > 0 && el.getAttribute("potion") == null) {
        try {
            legacyPotion = Potion.fromDamage(damage);
        } catch(IllegalArgumentException e) {
            throw new InvalidXMLException("Invalid legacy potion damage value " + damage + ": " + e.getMessage(), el, e);
        }

        // If the legacy splash bit is set, convert to a splash potion
        if(legacyPotion.isSplash()) {
            type = Material.SPLASH_POTION;
            legacyPotion.setSplash(false);
        }

        // Potions always have damage 0
        damage = 0;
    } else {
        legacyPotion = null;
    }

    ItemStack itemStack = new ItemStack(type, amount, damage);
    if(itemStack.getType() != type) {
        throw new InvalidXMLException("Invalid item/block", el);
    }

    final ItemMeta meta = itemStack.getItemMeta();
    if(meta != null) { // This happens if the item is "air"
        parseItemMeta(el, meta);

        // If we decoded a legacy potion, apply it now, but only if there are no custom effects.
        // This emulates the old behavior of custom effects overriding default effects.
        if(legacyPotion != null) {
            final PotionMeta potionMeta = (PotionMeta) meta;
            if(!potionMeta.hasCustomEffects()) {
                potionMeta.setBasePotionData(new PotionData(legacyPotion.getType(),
                                                            legacyPotion.hasExtendedDuration(),
                                                            legacyPotion.getLevel() == 2));
            }
        }

        itemStack.setItemMeta(meta);
    }

    return itemStack;
}