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

The following examples show how to use org.jdom2.Element#getTextNormalize() . These examples are extracted from open source projects. 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
@Override
public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase obj, String additional)
    throws MCRPersistentIdentifierException {
    String xpath = getProperties().get("Xpath");
    Document xml = obj.createXML();
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression<Element> xp = xpfac
        .compile(xpath, Filters.element(), null, MCRConstants.getStandardNamespaces());
    List<Element> evaluate = xp.evaluate(xml);
    if (evaluate.size() > 1) {
        throw new MCRPersistentIdentifierException(
            "Got " + evaluate.size() + " matches for " + obj.getId() + " with xpath " + xpath + "");
    }

    if (evaluate.size() == 0) {
        return Optional.empty();
    }

    Element identifierElement = evaluate.listIterator().next();
    String identifierString = identifierElement.getTextNormalize();

    Optional<MCRPersistentIdentifier> parsedIdentifierOptional = MCRPIManager.getInstance()
        .getParserForType(getProperties().get("Type")).parse(identifierString);
    return parsedIdentifierOptional.map(MCRPersistentIdentifier.class::cast);
}
 
Example 2
Source Project: jframe   File: XMLUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param children
 * @return String
 */
@SuppressWarnings("rawtypes")
public static String getChildrenText(List children) {
    StringBuffer sb = new StringBuffer();
    if (!children.isEmpty()) {
        Iterator it = children.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String name = e.getName();
            String value = e.getTextNormalize();
            List list = e.getChildren();
            sb.append("<" + name + ">");
            if (!list.isEmpty()) {
                sb.append(XMLUtil.getChildrenText(list));
            }
            sb.append(value);
            sb.append("</" + name + ">");
        }
    }

    return sb.toString();
}
 
Example 3
public static CalendarDateUnit getTimeUnit(Document doc) {
  Element root = doc.getRootElement();
  Element timeUnitE = root.getChild("TimeUnit");
  if (timeUnitE == null)
    return null;

  String cal = timeUnitE.getAttributeValue("calendar");
  String timeUnitS = timeUnitE.getTextNormalize();

  try {
    return CalendarDateUnit.of(cal, timeUnitS);
  } catch (Exception e) {
    log.error("Illegal date unit {} in FeatureDatasetCapabilitiesXML", timeUnitS);
    return null;
  }
}
 
Example 4
public static CalendarDateUnit getTimeUnit(Document doc) {
  Element root = doc.getRootElement();
  Element timeUnitE = root.getChild("TimeUnit");
  if (timeUnitE == null)
    return null;

  String cal = timeUnitE.getAttributeValue("calendar");
  String timeUnitS = timeUnitE.getTextNormalize();

  try {
    return CalendarDateUnit.of(cal, timeUnitS);
  } catch (Exception e) {
    log.error("Illegal date unit {} in FeatureDatasetCapabilitiesXML", timeUnitS);
    return null;
  }
}
 
Example 5
@MethodParser("class")
public PlayerClassFilter parseClass(Element el) throws InvalidXMLException {
  ClassModule classes = this.factory.getModule(ClassModule.class);
  if (classes == null) {
    throw new InvalidXMLException("No classes defined", el);
  } else {
    PlayerClass playerClass =
        StringUtils.bestFuzzyMatch(el.getTextNormalize(), classes.getPlayerClasses(), 0.9);

    if (playerClass == null) {
      throw new InvalidXMLException("Could not find player-class: " + el.getTextNormalize(), el);
    } else {
      return new PlayerClassFilter(playerClass);
    }
  }
}
 
Example 6
@Override
public Optional<MCRPersistentIdentifier> getIdentifier(MCRBase base, String additional)
    throws MCRPersistentIdentifierException {
    MCRObject object = checkObject(base);
    MCRMODSWrapper wrapper = new MCRMODSWrapper(object);

    final String xPath = getXPath();
    Element element = wrapper.getElement(xPath);
    if (element == null) {
        return Optional.empty();
    }

    String text = element.getTextNormalize();

    return MCRPIManager.getInstance().getParserForType(getIdentifierType())
        .parse(text)
        .map(MCRPersistentIdentifier.class::cast);
}
 
Example 7
private boolean readValue(Element pdsHashElement, String key, Namespace ns, boolean value) {
  if (pdsHashElement != null) {
    Element e = pdsHashElement.getChild(key, ns);
    if (e != null) {
      value = true; // no value means true
      String t = e.getTextNormalize();
      if ("true".equalsIgnoreCase(t))
        value = true;
      if ("false".equalsIgnoreCase(t))
        value = false;
    }
  }
  return value;
}
 
Example 8
/**
 * Read an NcML enumTypedef element.
 *
 * @param g put enumTypedef into this group
 * @param refg parent Group in referenced dataset
 * @param etdElem ncml enumTypedef element
 */
private void readEnumTypedef(Group g, Group refg, Element etdElem) {
  String name = etdElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML enumTypedef name is required (%s)%n", etdElem);
    return;
  }
  String typeS = etdElem.getAttributeValue("type");
  DataType baseType = (typeS == null) ? DataType.ENUM1 : DataType.getType(typeS);

  Map<Integer, String> map = new HashMap<>(100);
  for (Element e : etdElem.getChildren("enum", ncNS)) {
    String key = e.getAttributeValue("key");
    String value = e.getTextNormalize();
    if (key == null) {
      errlog.format("NcML enumTypedef enum key attribute is required (%s)%n", e);
      continue;
    }
    if (value == null) {
      errlog.format("NcML enumTypedef enum value is required (%s)%n", e);
      continue;
    }
    try {
      int keyi = Integer.parseInt(key);
      map.put(keyi, value);
    } catch (Exception e2) {
      errlog.format("NcML enumTypedef enum key attribute not an integer (%s)%n", e);
    }
  }

  EnumTypedef td = new EnumTypedef(name, map, baseType);
  g.addEnumeration(td);
}
 
Example 9
/**
 * Read an NcML enumTypedef element.
 *
 * @param g put enumTypedef into this group
 * @param etdElem ncml enumTypedef element
 */
private void readEnumTypedef(Group.Builder g, Element etdElem) {
  String name = etdElem.getAttributeValue("name");
  if (name == null) {
    errlog.format("NcML enumTypedef name is required (%s)%n", etdElem);
    return;
  }
  String typeS = etdElem.getAttributeValue("type");
  DataType baseType = (typeS == null) ? DataType.ENUM1 : DataType.getType(typeS);

  Map<Integer, String> map = new HashMap<>(100);
  for (Element e : etdElem.getChildren("enum", ncNS)) {
    String key = e.getAttributeValue("key");
    String value = e.getTextNormalize();
    if (key == null) {
      errlog.format("NcML enumTypedef enum key attribute is required (%s)%n", e);
      continue;
    }
    if (value == null) {
      errlog.format("NcML enumTypedef enum value is required (%s)%n", e);
      continue;
    }
    try {
      int keyi = Integer.parseInt(key);
      map.put(keyi, value);
    } catch (Exception e2) {
      errlog.format("NcML enumTypedef enum key attribute not an integer (%s)%n", e);
    }
  }

  EnumTypedef td = new EnumTypedef(name, map, baseType);
  g.addEnumTypedef(td);
}
 
Example 10
public static String getNormalizedNullableText(Element el) {
  String text = el.getTextNormalize();
  if (text == null || "".equals(text)) {
    return null;
  } else {
    return text;
  }
}
 
Example 11
Source Project: jframe   File: XMLUtil.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map doXMLParse(String strxml) throws JDOMException,
        IOException {
    strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

    if (null == strxml || "".equals(strxml)) {
        return null;
    }

    Map m = new HashMap();

    InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(in);
    Element root = doc.getRootElement();
    List list = root.getChildren();
    Iterator it = list.iterator();
    while (it.hasNext()) {
        Element e = (Element) it.next();
        String k = e.getName();
        String v = "";
        List children = e.getChildren();
        if (children.isEmpty()) {
            v = e.getTextNormalize();
        } else {
            v = XMLUtil.getChildrenText(children);
        }

        m.put(k, v);
    }

    in.close();

    return m;
}
 
Example 12
@MethodParser("mob")
public EntityTypeFilter parseMob(Element el) throws InvalidXMLException {
  EntityTypeFilter matcher = this.parseEntity(el);
  if (!LivingEntity.class.isAssignableFrom(matcher.getEntityType())) {
    throw new InvalidXMLException("Unknown mob type: " + el.getTextNormalize(), el);
  }
  return matcher;
}
 
Example 13
public static String getNormalizedNullableText(Element el) {
    String text = el.getTextNormalize();
    if(text == null || "".equals(text)) {
        return null;
    } else {
        return text;
    }
}
 
Example 14
public static BaseComponent parseLocalizedText(Element el) throws InvalidXMLException {
    final Attribute translate = el.getAttribute("translate");
    if(translate != null) {
        return new TranslatableComponent(translate.getValue());
    } else {
        return new Component(el.getTextNormalize());
    }
}
 
Example 15
@MethodParser("class")
public PlayerClassFilter parseClass(Element el) throws InvalidXMLException {
    final PlayerClass playerClass = StringUtils.bestFuzzyMatch(el.getTextNormalize(), classModule.get().getPlayerClasses(), 0.9);
    if (playerClass == null) {
        throw new InvalidXMLException("Could not find player-class: " + el.getTextNormalize(), el);
    }

    return new PlayerClassFilter(playerClass);
}
 
Example 16
@MethodParser("mob")
public EntityTypeFilter parseMob(Element el) throws InvalidXMLException {
    EntityTypeFilter matcher = this.parseEntity(el);
    if(!LivingEntity.class.isAssignableFrom(matcher.getEntityType())) {
        throw new InvalidXMLException("Unknown mob type: " + el.getTextNormalize(), el);
    }
    return matcher;
}
 
Example 17
/**
 * Parse the values element
 *
 * @param s JDOM element to parse
 * @return Array with parsed values
 * @throws IllegalArgumentException if string values not parsable to specified data type
 */
private static ucar.ma2.Array readAttributeValues(Element s) throws IllegalArgumentException {
  String valString = s.getAttributeValue("value");

  // can also be element text
  if (valString == null) {
    valString = s.getTextNormalize();
  }

  // no value specified hmm technically this is not illegal !!
  if (valString == null) {
    throw new IllegalArgumentException("No value specified");
  }

  String type = s.getAttributeValue("type");
  DataType dtype = (type == null) ? DataType.STRING : DataType.getType(type);
  if (dtype == DataType.CHAR) {
    dtype = DataType.STRING;
  }

  // backwards compatibility with deprecated isUnsigned attribute
  String unS = s.getAttributeValue("isUnsigned");
  boolean isUnsignedSet = "true".equalsIgnoreCase(unS);
  if (isUnsignedSet && dtype.isIntegral() && !dtype.isUnsigned()) {
    dtype = dtype.withSignedness(DataType.Signedness.UNSIGNED);
  }

  String sep = s.getAttributeValue("separator");
  if ((sep == null) && (dtype == DataType.STRING)) {
    List<String> list = new ArrayList<>();
    list.add(valString);
    return Array.makeArray(dtype, list);
  }

  if (sep == null) {
    sep = " "; // default whitespace separated
  }

  List<String> stringValues = new ArrayList<>();
  StringTokenizer tokn = new StringTokenizer(valString, sep);
  while (tokn.hasMoreTokens()) {
    stringValues.add(tokn.nextToken());
  }

  return Array.makeArray(dtype, stringValues);
}
 
Example 18
public Recipe parseShapedRecipe(MapFactory factory, Element elRecipe)
    throws InvalidXMLException {
  ShapedRecipe recipe = new ShapedRecipe(parseRecipeResult(factory, elRecipe));

  Element elShape = XMLUtils.getRequiredUniqueChild(elRecipe, "shape");
  List<String> rows = new ArrayList<>(3);

  for (Element elRow : elShape.getChildren("row")) {
    String row = elRow.getTextNormalize();

    if (rows.size() >= 3) {
      throw new InvalidXMLException(
          "Shape must have no more than 3 rows (" + row + ")", elShape);
    }

    if (rows.isEmpty()) {
      if (row.length() > 3) {
        throw new InvalidXMLException(
            "Shape must have no more than 3 columns (" + row + ")", elShape);
      }
    } else if (row.length() != rows.get(0).length()) {
      throw new InvalidXMLException("All rows must be the same width", elShape);
    }

    rows.add(row);
  }

  if (rows.isEmpty()) {
    throw new InvalidXMLException("Shape must have at least one row", elShape);
  }

  recipe.shape(rows.toArray(new String[rows.size()]));
  Set<Character> keys =
      recipe
          .getIngredientMap()
          .keySet(); // All shape symbols are present and mapped to null at this point

  for (Element elIngredient : elRecipe.getChildren("ingredient")) {
    SingleMaterialMatcher item = XMLUtils.parseMaterialPattern(elIngredient);
    Attribute attrSymbol = XMLUtils.getRequiredAttribute(elIngredient, "symbol");
    String symbol = attrSymbol.getValue();

    if (symbol.length() != 1) {
      throw new InvalidXMLException(
          "Ingredient key must be a single character from the recipe shape", attrSymbol);
    }

    char key = symbol.charAt(0);
    if (!keys.contains(key)) {
      throw new InvalidXMLException(
          "Ingredient key '" + key + "' does not appear in the recipe shape", attrSymbol);
    }

    if (item.dataMatters()) {
      recipe.setIngredient(key, item.getMaterialData());
    } else {
      recipe.setIngredient(key, item.getMaterial());
    }
  }

  if (recipe.getIngredientMap().isEmpty()) {
    throw new InvalidXMLException(
        "Crafting recipe must have at least one ingredient", elRecipe);
  }

  return recipe;
}
 
Example 19
@Override
public InfoModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException {
    Element root = doc.getRootElement();

    String name = Node.fromRequiredChildOrAttr(root, "name").getValueNormalize();
    SemanticVersion version = XMLUtils.parseSemanticVersion(Node.fromRequiredChildOrAttr(root, "version"));
    MapDoc.Phase phase = XMLUtils.parseEnum(Node.fromLastChildOrAttr(root, "phase"), MapDoc.Phase.class, "phase", MapDoc.Phase.PRODUCTION);
    MapDoc.Edition edition = XMLUtils.parseEnum(Node.fromLastChildOrAttr(root, "edition"), MapDoc.Edition.class, "edition", MapDoc.Edition.STANDARD);

    // Allow multiple <objective> elements, so include files can provide defaults
    final BaseComponent objective = XMLUtils.parseLocalizedText(Node.fromRequiredLastChildOrAttr(root, "objective"));

    String slug = root.getChildTextNormalize("slug");
    BaseComponent game = XMLUtils.parseFormattedText(root, "game");

    MapDoc.Genre genre = XMLUtils.parseEnum(Node.fromNullable(root.getChild("genre")), MapDoc.Genre.class, "genre", MapDoc.Genre.OTHER);

    final TreeSet<MapDoc.Gamemode> gamemodes = new TreeSet<>();
    for(Element elGamemode : root.getChildren("gamemode")) {
        gamemodes.add(XMLUtils.parseEnum(elGamemode, MapDoc.Gamemode.class));
    }

    List<Contributor> authors = readContributorList(root, "authors", "author");

    if(game == null) {
        Element blitz = root.getChild("blitz");
        if(blitz != null) {
            Element title = blitz.getChild("title");
            if(title != null) {
                if(context.getProto().isNoOlderThan(ProtoVersions.REMOVE_BLITZ_TITLE)) {
                    throw new InvalidXMLException("<title> inside <blitz> is no longer supported, use <map game=\"...\">", title);
                }
                game = new Component(title.getTextNormalize());
            }
        }
    }

    List<Contributor> contributors = readContributorList(root, "contributors", "contributor");

    List<String> rules = new ArrayList<String>();
    for(Element parent : root.getChildren("rules")) {
        for(Element rule : parent.getChildren("rule")) {
            rules.add(rule.getTextNormalize());
        }
    }

    Difficulty difficulty = XMLUtils.parseEnum(Node.fromLastChildOrAttr(root, "difficulty"), Difficulty.class, "difficulty");

    Environment dimension = XMLUtils.parseEnum(Node.fromLastChildOrAttr(root, "dimension"), Environment.class, "dimension", Environment.NORMAL);

    boolean friendlyFire = XMLUtils.parseBoolean(Node.fromLastChildOrAttr(root, "friendly-fire", "friendlyfire"), false);

    return new InfoModule(new MapInfo(context.getProto(), slug, name, version, edition, phase, game, genre, ImmutableSet.copyOf(gamemodes), objective, authors, contributors, rules, difficulty, dimension, friendlyFire));
}
 
Example 20
public Recipe parseShapedRecipe(MapModuleContext context, Element elRecipe) throws InvalidXMLException {
    ShapedRecipe recipe = new ShapedRecipe(parseRecipeResult(context, elRecipe));

    Element elShape = XMLUtils.getRequiredUniqueChild(elRecipe, "shape");
    List<String> rows = new ArrayList<>(3);

    for(Element elRow : elShape.getChildren("row")) {
        String row = elRow.getTextNormalize();

        if(rows.size() >= 3) {
            throw new InvalidXMLException("Shape must have no more than 3 rows (" + row + ")", elShape);
        }

        if(rows.isEmpty()) {
            if(row.length() > 3) {
                throw new InvalidXMLException("Shape must have no more than 3 columns (" + row + ")", elShape);
            }
        } else if(row.length() != rows.get(0).length()) {
            throw new InvalidXMLException("All rows must be the same width", elShape);
        }

        rows.add(row);
    }

    if(rows.isEmpty()) {
        throw new InvalidXMLException("Shape must have at least one row", elShape);
    }

    recipe.shape(rows.toArray(new String[rows.size()]));
    Set<Character> keys = recipe.getIngredientMap().keySet(); // All shape symbols are present and mapped to null at this point

    for(Element elIngredient : elRecipe.getChildren("ingredient")) {
        MaterialPattern item = XMLUtils.parseMaterialPattern(elIngredient);
        Attribute attrSymbol = XMLUtils.getRequiredAttribute(elIngredient, "symbol");
        String symbol = attrSymbol.getValue();

        if(symbol.length() != 1) {
            throw new InvalidXMLException("Ingredient key must be a single character from the recipe shape", attrSymbol);
        }

        char key = symbol.charAt(0);
        if(!keys.contains(key)) {
            throw new InvalidXMLException("Ingredient key '" + key + "' does not appear in the recipe shape", attrSymbol);
        }

        if(item.dataMatters()) {
            recipe.setIngredient(key, item.getMaterialData());
        } else {
            recipe.setIngredient(key, item.getMaterial());
        }
    }

    if(recipe.getIngredientMap().isEmpty()) {
        throw new InvalidXMLException("Crafting recipe must have at least one ingredient", elRecipe);
    }

    return recipe;
}