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

The following examples show how to use org.jdom2.Element#getName() . 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: XMLUtils.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
public static MaterialMatcher parseMaterialMatcher(Element el) throws InvalidXMLException {
  Set<MaterialMatcher> matchers = new HashSet<>();

  for (Element elChild : el.getChildren()) {
    switch (elChild.getName()) {
      case "all-materials":
      case "all-items":
        return AllMaterialMatcher.INSTANCE;

      case "all-blocks":
        matchers.add(BlockMaterialMatcher.INSTANCE);
        break;

      case "material":
      case "item":
        matchers.add(parseMaterialPattern(elChild));
        break;

      default:
        throw new InvalidXMLException("Unknown material matcher tag", elChild);
    }
  }

  return CompoundMaterialMatcher.of(matchers);
}
 
Example 2
Source File: MCRMetaDefault.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method read the XML input stream part from a DOM part for the
 * metadata of the document.
 * 
 * @param element
 *            a relevant DOM element for the metadata
 * @exception MCRException
 *                if the subtag value is null or empty
 */
public void setFromDOM(Element element) throws MCRException {
    if (element == null) {
        return;
    }

    subtag = element.getName();

    MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue("lang", Namespace.XML_NAMESPACE))
        .ifPresent(tempLang -> lang = tempLang);
    MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue("type"))
        .ifPresent(tempType -> type = tempType);
    MCRUtils.filterTrimmedNotEmpty(element.getAttributeValue("inherited"))
        .map(Integer::parseInt)
        .ifPresent(tempInherited -> inherited = tempInherited);
}
 
Example 3
Source File: GameRulesModule.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public static GameRulesModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException {
    Map<GameRule, Boolean> gameRules = new HashMap<>();

    for (Element gameRulesElement : doc.getRootElement().getChildren("gamerules")) {
        for (Element gameRuleElement : gameRulesElement.getChildren()) {
            GameRule gameRule = GameRule.forName(gameRuleElement.getName());
            String value = gameRuleElement.getValue();

            if (gameRule == null) {
                throw new InvalidXMLException(gameRuleElement.getName() + " is not a valid gamerule", gameRuleElement);
            }
            if (value == null) {
                throw new InvalidXMLException("Missing value for gamerule " + gameRule.getValue(), gameRuleElement);
            } else if (!(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false"))) {
                throw new InvalidXMLException(gameRuleElement.getValue() + " is not a valid gamerule value", gameRuleElement);
            }
            if (gameRules.containsKey(gameRule)){
                throw new InvalidXMLException(gameRule.getValue() + " has already been specified", gameRuleElement);
            }

            gameRules.put(gameRule, Boolean.valueOf(value));
        }
    }
    return new GameRulesModule(gameRules);
}
 
Example 4
Source File: GameRulesModule.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public GameRulesModule parse(MapFactory factory, Logger logger, Document doc)
    throws InvalidXMLException {
  Map<String, String> gameRules = new HashMap<>();

  for (Element gameRulesElement : doc.getRootElement().getChildren("gamerules")) {
    for (Element gameRuleElement : gameRulesElement.getChildren()) {
      String rule = gameRuleElement.getName();
      String value = gameRuleElement.getValue();

      if (value == null) {
        throw new InvalidXMLException("Missing value for gamerule " + rule, gameRuleElement);
      } else if (gameRules.containsKey(rule)) {
        throw new InvalidXMLException(rule + " has already been specified", gameRuleElement);
      }

      gameRules.put(rule, value);
    }
  }
  return new GameRulesModule(gameRules);
}
 
Example 5
Source File: RdrSetParser.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Constructs a rule tree for each set of constraint rules in the rules file
 * i.e. pre & post constraint rule sets at the case and task levels
 * @param e the JDOM Element representation of the rule tree
 * @return true if the rules were loaded successfully
 */
private boolean getConstraintRules(Map<RuleType, RdrTreeSet> treeMap,
                                   Element e, boolean newSet) {
    for (Element eCon : e.getChildren()) {
        String conName = eCon.getName();
        Element ePre = eCon.getChild("pre");
        Element ePost = eCon.getChild("post");

        if (conName.equalsIgnoreCase("case")) {
            if (ePre != null) buildCaseLevelTree(treeMap,
                    RuleType.CasePreconstraint, ePre, newSet);
            if (ePost != null) buildCaseLevelTree(treeMap,
                    RuleType.CasePostconstraint, ePost, newSet);
        }
        else if (conName.equalsIgnoreCase("item")) {
            if (ePre != null) buildItemLevelTree(treeMap,
                    RuleType.ItemPreconstraint, ePre, newSet);
            if (ePost != null) buildItemLevelTree(treeMap,
                    RuleType.ItemPostconstraint, ePost, newSet);
        }
    }
    return true ;
}
 
Example 6
Source File: RSS091NetscapeParser.java    From rome with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isMyType(final Document document) {

    final Element rssRoot = document.getRootElement();
    final String name = rssRoot.getName();
    final Attribute version = rssRoot.getAttribute("version");
    final DocType docType = document.getDocType();

    return name.equals(ELEMENT_NAME) && version != null && version.getValue().equals(getRSSVersion()) && docType != null
            && ELEMENT_NAME.equals(docType.getElementName()) && PUBLIC_ID.equals(docType.getPublicID()) && SYSTEM_ID.equals(docType.getSystemID());

}
 
Example 7
Source File: MCRXMLHelper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static boolean equivalentName(Element e1, Element e2) {
    Namespace ns1 = e1.getNamespace();
    String localName1 = e1.getName();

    Namespace ns2 = e2.getNamespace();
    String localName2 = e2.getName();

    return ns1.equals(ns2) && localName1.equals(localName2);
}
 
Example 8
Source File: NameGenPanel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private RuleSet loadRuleSet(Element ruleSet) throws DataConversionException
{
	RuleSet rs = new RuleSet(allVars, ruleSet.getAttributeValue("title"), ruleSet.getAttributeValue("id"),
		ruleSet.getAttributeValue("usage"));
	java.util.List<?> elements = ruleSet.getChildren();
	ListIterator<?> elementsIterator = elements.listIterator();
	int num = 0;

	while (elementsIterator.hasNext())
	{
		Element child = (Element) elementsIterator.next();
		String elementName = child.getName();

		if (elementName.equals("CATEGORY"))
		{
			loadCategory(child, rs);
		}
		else if (elementName.equals("RULE"))
		{
			rs.add(loadRule(child, rs.getId() + num));
		}

		num++;
	}

	return rs;
}
 
Example 9
Source File: RdrEvaluator.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Element appendDataTypes(WorkItemRecord wir, Element data) {
    List<YParameter> inputParams = _client.getTaskInputParams(wir);
    for (Element varElement : data.getChildren()) {
        String varName = varElement.getName();
        for (YParameter param : inputParams) {
            if (param.getName().equals(varName)) {
                varElement.setAttribute("type", param.getDataTypeNameUnprefixed());
                break;
            }
        }
    }
    return data;
}
 
Example 10
Source File: GlobalItemParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public ItemStack parseRequiredItem(Element parent) throws InvalidXMLException {
    final Element el = XMLUtils.getRequiredUniqueChild(parent);
    switch(el.getName()) {
        case "item": return parseItem(el, false);
        case "head": return parseItem(el, Material.SKULL_ITEM, (short) 3);
        case "book": return parseItem(el, Material.WRITTEN_BOOK);
    }
    throw new InvalidXMLException("Item expected", el);
}
 
Example 11
Source File: RSS090Generator.java    From rome with Apache License 2.0 5 votes vote down vote up
protected void checkLength(final Element parent, final String childName, final int minLen, final int maxLen) throws FeedException {
    final Element child = parent.getChild(childName, getFeedNamespace());
    if (child != null) {
        if (minLen > 0 && child.getText().length() < minLen) {
            throw new FeedException("Invalid " + getType() + " feed, " + parent.getName() + " " + childName + "short of " + minLen + " length");
        }
        if (maxLen > -1 && child.getText().length() > maxLen) {
            throw new FeedException("Invalid " + getType() + " feed, " + parent.getName() + " " + childName + "exceeds " + maxLen + " length");
        }
    }
}
 
Example 12
Source File: SSE091Parser.java    From rome with Apache License 2.0 5 votes vote down vote up
@Override
public Module parse(final Element element, final Locale locale) {
    SSEModule sseModule = null;
    final String name = element.getName();

    if (name.equals("rss")) {
        sseModule = parseSharing(element, locale);
    } else if (name.equals("item")) {
        sseModule = parseSync(element, locale);
    }
    return sseModule;
}
 
Example 13
Source File: ElementIOFactoryByMap.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Override
public R produce(Element element) {
    R engine = names.get(element.getName());
    if (engine == null) {
        throw new EngineNotFoundException(element.getName());
    }
    return engine;
}
 
Example 14
Source File: MCREditorOutValidator.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static String checkMetaObjectWithLangNotEmpty(Element datasubtag,
    Class<? extends MCRMetaInterface> metaClass) {
    String text = datasubtag.getTextTrim();
    if (text == null || text.length() == 0) {
        return "Element " + datasubtag.getName() + " has no text.";
    }
    return checkMetaObjectWithLang(datasubtag, metaClass);
}
 
Example 15
Source File: DataSchemaBuilder.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new element with the same name and attributes as the old one
 * @param element the elment to clone
 * @param defNS the default namespace
 * @return the cloned element
 */
private Element cloneElement(Element element, Namespace defNS) {
    Element cloned = new Element(element.getName(), defNS);
    cloned.setAttributes(cloneAttributes(element, defNS));

    // clone appinfo children literally
    Element parent = element.getParentElement();
    if (parent != null && parent.getName().equals("appinfo")) {
        cloned.setText(element.getText());
    }
    return cloned;
}
 
Example 16
Source File: NameGenPanel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String loadList(Element list) throws DataConversionException
{
	pcgen.core.doomsdaybook.DDList dataList = new pcgen.core.doomsdaybook.DDList(allVars,
		list.getAttributeValue("title"), list.getAttributeValue("id"));
	java.util.List<?> elements = list.getChildren();

	for (final Object element : elements)
	{
		Element child = (Element) element;
		String elementName = child.getName();

		if (elementName.equals("VALUE"))
		{
			WeightedDataValue dv =
					new WeightedDataValue(child.getText(), child.getAttribute("weight").getIntValue());
			List<?> subElements = child.getChildren("SUBVALUE");

			for (final Object subElement1 : subElements)
			{
				Element subElement = (Element) subElement1;
				dv.addSubValue(subElement.getAttributeValue("type"), subElement.getText());
			}

			dataList.add(dv);
		}
	}

	allVars.addDataElement(dataList);

	return dataList.getId();
}
 
Example 17
Source File: Marshaller.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static TaskInformation unmarshalTaskInformation(String taskInfoAsXML) {
    YParametersSchema paramsForTaskNCase = new YParametersSchema();
    YAttributeMap attributemap = new YAttributeMap();

    Element taskInfo = JDOMUtil.stringToElement(taskInfoAsXML);

    // if the string was encased in response tags, go down one level
    if (taskInfoAsXML.startsWith("<response>")) {
        taskInfo = taskInfo.getChild("taskInfo");
    }
    String taskID = taskInfo.getChildText("taskID");
    String taskName = taskInfo.getChildText("taskName");
    String taskDocumentation = taskInfo.getChildText("taskDocumentation");
    String decompositionID = taskInfo.getChildText("decompositionID");
    Element yawlService = taskInfo.getChild("yawlService");

    Element specElem = taskInfo.getChild("specification");
    String specIdentifier = specElem.getChildText("identifier");
    String specVersion = specElem.getChildText("version");
    String specURI = specElem.getChildText("uri");
    YSpecificationID specificationID = new YSpecificationID(specIdentifier, specVersion, specURI);

    Element attributes = taskInfo.getChild("attributes");
    if (attributes != null) {
        for (Element attribute : attributes.getChildren()) {
            attributemap.put(attribute.getName(),
                    attributes.getChildText(attribute.getName()));
        }
    }

    Element params = taskInfo.getChild("params");
    for (Element paramElem : params.getChildren()) {
        if ("formalInputParam".equals(paramElem.getName())) {
            paramsForTaskNCase.setFormalInputParam(paramElem.getText());
            continue;
        }
        YParameter param = new YParameter(null, paramElem.getName());
        YDecompositionParser.parseParameter(
                paramElem,
                param,
                null,
                false);
        if (param.isInput()) {
            paramsForTaskNCase.setInputParam(param);
        } else {
            paramsForTaskNCase.setOutputParam(param);
        }
        String paramOrdering = paramElem.getChildText("ordering");
        if (paramOrdering != null) {
            int order = Integer.parseInt(paramOrdering);
            param.setOrdering(order);
        }
    }

    TaskInformation taskInformation = new TaskInformation(
            paramsForTaskNCase,
            taskID,
            specificationID,
            taskName,
            taskDocumentation,
            decompositionID);

    taskInformation.setAttributes(attributemap);

    return taskInformation;
}
 
Example 18
Source File: MCRXPathBuilder.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Builds a local XPath fragment as combined namespace prefix, local element name and position predicate
 */
public static String buildChildPath(Element element) {
    return getNamespacePrefix(element) + element.getName() + buildPositionPredicate(element);
}
 
Example 19
Source File: RdrSetParser.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Map<RuleType, RdrTreeSet> parse(Document doc, boolean newSet) {
    if (doc == null) return Collections.emptyMap();  // no such file or unsuccessful load
    Map<RuleType, RdrTreeSet> treeMap = new HashMap<RuleType, RdrTreeSet>();
    try {
        Element root = doc.getRootElement();      // spec

        // extract the rule nodes for each exception type
        for (Element e : root.getChildren()) {       // these are exception type tags
            String exName = e.getName();
            if (exName.equalsIgnoreCase("selection")) {
                buildItemLevelTree(treeMap, RuleType.ItemSelection, e, newSet);
            }
            else if (exName.equalsIgnoreCase("abort")) {
                buildItemLevelTree(treeMap, RuleType.ItemAbort, e, newSet);
            }
            else if (exName.equalsIgnoreCase("timeout")) {
                buildItemLevelTree(treeMap, RuleType.ItemTimeout, e, newSet);
            }
            else if (exName.equalsIgnoreCase("resourceUnavailable")) {
                buildItemLevelTree(treeMap, RuleType.ItemResourceUnavailable, e, newSet);
            }
            else if (exName.equalsIgnoreCase("violation")) {
                buildItemLevelTree(treeMap, RuleType.ItemConstraintViolation, e, newSet);
            }
            else if (exName.equalsIgnoreCase("external")) {
                getExternalRules(treeMap, e, newSet) ;
            }
            else if (exName.equalsIgnoreCase("constraints")) {
                getConstraintRules(treeMap, e, newSet) ;
            }

            // if 'task' is a child of 'root', this is a version one rules file
            // so treat it as though it contains selection rules only
            else if (exName.equalsIgnoreCase("task")) {
                buildItemLevelTree(treeMap, RuleType.ItemSelection, root, newSet);
            }
        }
        return treeMap;
    }
    catch (Exception ex) {
        LogManager.getLogger(RdrSetLoader.class).error(
                "Exception retrieving rule nodes from rules file", ex);
        return Collections.emptyMap();
    }
}
 
Example 20
Source File: CraftingModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public @Nullable CraftingModule parse(MapFactory factory, Logger logger, Document doc)
    throws InvalidXMLException {
  Set<Recipe> customRecipes = new HashSet<>();
  Set<SingleMaterialMatcher> disabledRecipes = new HashSet<>();

  for (Element elCrafting : doc.getRootElement().getChildren("crafting")) {
    for (Element elDisable : elCrafting.getChildren("disable")) {
      disabledRecipes.add(XMLUtils.parseMaterialPattern(elDisable));
    }

    for (Element elRecipe : XMLUtils.getChildren(elCrafting, "shapeless", "shaped", "smelt")) {
      Recipe recipe;
      switch (elRecipe.getName()) {
        case "shapeless":
          recipe = parseShapelessRecipe(factory, elRecipe);
          break;

        case "shaped":
          recipe = parseShapedRecipe(factory, elRecipe);
          break;

        case "smelt":
          recipe = parseSmeltingRecipe(factory, elRecipe);
          break;

        default:
          throw new IllegalStateException();
      }

      customRecipes.add(recipe);
      if (XMLUtils.parseBoolean(elRecipe.getAttribute("override"), false)) {
        // Disable specific world + data
        disabledRecipes.add(new SingleMaterialMatcher(recipe.getResult().getData()));
      } else if (XMLUtils.parseBoolean(elRecipe.getAttribute("override-all"), false)) {
        // Disable all of this world
        disabledRecipes.add(new SingleMaterialMatcher(recipe.getResult().getType()));
      }
    }
  }

  return customRecipes.isEmpty() && disabledRecipes.isEmpty()
      ? null
      : new CraftingModule(customRecipes, disabledRecipes);
}