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

The following examples show how to use org.jdom2.Element#getTextNormalize() . 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: MCRPIXPathMetadataService.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@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 File: XMLUtil.java    From jframe with 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
Source File: MCRAbstractMODSMetadataService.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Source File: FeatureDatasetCapabilitiesWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 6
Source File: FilterParser.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 7
Source File: FeatureCollectionConfig.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 9
Source File: FilterDefinitionParser.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 10
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
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 11
Source File: XMLUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getNormalizedNullableText(Element el) {
    String text = el.getTextNormalize();
    if(text == null || "".equals(text)) {
        return null;
    } else {
        return text;
    }
}
 
Example 12
Source File: FilterParser.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@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
Source File: XMLUtil.java    From jframe with 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 14
Source File: XMLUtils.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getNormalizedNullableText(Element el) {
  String text = el.getTextNormalize();
  if (text == null || "".equals(text)) {
    return null;
  } else {
    return text;
  }
}
 
Example 15
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 16
Source File: NcMLReader.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 17
Source File: CraftingModule.java    From PGM with GNU Affero General Public License v3.0 4 votes vote down vote up
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 18
Source File: InfoModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@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 19
Source File: CraftingModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: NcMLReaderNew.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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);
}