/** * Create a JDOM document from an XML string. * * @param string * @param encoding * @return * @throws IOException * @throws JDOMException * @should build document correctly */ public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException { if (encoding == null) { encoding = DEFAULT_ENCODING; } byte[] byteArray = null; try { byteArray = string.getBytes(encoding); } catch (UnsupportedEncodingException e) { } ByteArrayInputStream baos = new ByteArrayInputStream(byteArray); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(baos); return document; }
/** * Create a JDOM document from an XML string. * * @param string * @return * @throws IOException * @throws JDOMException * @should build document correctly */ public static Document getDocumentFromString(String string, String encoding) throws JDOMException, IOException { if (string == null) { throw new IllegalArgumentException("string may not be null"); } if (encoding == null) { encoding = "UTF-8"; } byte[] byteArray = null; try { byteArray = string.getBytes(encoding); } catch (UnsupportedEncodingException e) { } ByteArrayInputStream baos = new ByteArrayInputStream(byteArray); // Reader reader = new StringReader(hOCRText); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(baos); return document; }
public void exportXML(ArrayList<Pokemon> pokemons,String tipo){ try { Element pokemon = new Element("pokemon"); Document doc = new Document(pokemon); for(Pokemon p:pokemons) { Element poke = new Element("pokemon"); poke.addContent(new Element("nombre").setText(p.getName())); poke.addContent(new Element("peso").setText(String.valueOf(p.getWeight()))); poke.addContent(new Element("altura").setText(String.valueOf(p.getHeight()))); poke.addContent(new Element("base_experience").setText(String.valueOf(p.getBaseExperience()))); doc.getRootElement().addContent(poke); } XMLOutputter output = new XMLOutputter(); output.setFormat(Format.getPrettyFormat()); output.output(doc, new FileWriter("pokemons-tipo-"+tipo+".xml")); }catch(Exception e) { System.out.println("Ocurri� alg�n error"); } }
public void parseXml(String fileName){ SAXBuilder builder = new SAXBuilder(); File file = new File(fileName); try { Document document = (Document) builder.build(file); Element rootNode = document.getRootElement(); List list = rootNode.getChildren("author"); for (int i = 0; i < list.size(); i++) { Element node = (Element) list.get(i); System.out.println("First Name : " + node.getChildText("firstname")); System.out.println("Last Name : " + node.getChildText("lastname")); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } }
@Override public SpawnModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { final SpawnParser parser = spawnParser.get(); List<Spawn> spawns = Lists.newArrayList(); List<Kit> playerKits = new ArrayList<>(); for(Element spawnsEl : doc.getRootElement().getChildren("spawns")) { spawns.addAll(parser.parseChildren(spawnsEl, new SpawnAttributes())); final Kit playerKit = context.needModule(KitParser.class).property(spawnsEl, "player-kit").optional(null); if(playerKit != null) { playerKits.add(playerKit); } } if(parser.getDefaultSpawn() == null) { throw new InvalidXMLException("map must have a single default spawn", doc); } return new SpawnModule(parser.getDefaultSpawn(), spawns, playerKits, parseRespawnOptions(context, logger, doc)); }
public static MobsModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { FilterParser filterParser = context.needModule(FilterParser.class); Element mobsEl = doc.getRootElement().getChild("mobs"); Filter mobsFilter = StaticFilter.DENY; if(mobsEl != null) { if(context.getProto().isNoOlderThan(ProtoVersions.FILTER_FEATURES)) { mobsFilter = filterParser.parseProperty(mobsEl, "filter"); } else { Element filterEl = XMLUtils.getUniqueChild(mobsEl, "filter"); if(filterEl != null) { mobsFilter = filterParser.parseElement(filterEl); } } } return new MobsModule(mobsFilter); }
public static ItemDestroyModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { final Set<MaterialPattern> patterns = new HashSet<>(); for(Node itemRemoveNode : Node.fromChildren(doc.getRootElement(), "item-remove", "itemremove")) { for(Node itemNode : Node.fromChildren(itemRemoveNode.asElement(), "item")) { final MaterialPattern pattern = XMLUtils.parseMaterialPattern(itemNode); patterns.add(pattern); if(pattern.matches(Material.POTION)) { // TODO: remove this after we update the maps patterns.add(new MaterialPattern(Material.SPLASH_POTION)); } } } if(patterns.isEmpty()) { return null; } else { return new ItemDestroyModule(patterns); } }
public Document readRootDocument(Path file) throws InvalidXMLException { checkNotNull(file, "file"); this.includeStack.clear(); Document result = this.readDocument(file); this.includeStack.clear(); if(source.globalIncludes()) { for(Path globalInclude : mapConfiguration.globalIncludes()) { final Path includePath = findIncludeFile(null, globalInclude, null); if(includePath != null) { result.getRootElement().addContent(0, readIncludedDocument(includePath, null)); } } } return result; }
@Override public @Nullable TeamModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { final List<TeamFactory> teams = teamsProvider.get(); if(teams.isEmpty()) return null; final Map<String, TeamFactory> byName = new HashMap<>(); for(TeamFactory team : teams) { final String name = team.getDefaultName(); final TeamFactory dupe = byName.put(name, team); if(dupe != null) { String msg = "Duplicate team name '" + name + "'"; final Element dupeNode = context.features().definitionNode(dupe); if(dupeNode != null) { msg += " (other team defined by " + Node.of(dupeNode).describeWithLocation() + ")"; } throw new InvalidXMLException(msg, context.features().definitionNode(team)); } } Optional<Boolean> requireEven = Optional.empty(); for(Element elTeam : XMLUtils.flattenElements(doc.getRootElement(), "teams", "team")) { requireEven = Optionals.first(XMLUtils.parseBoolean(elTeam, "even").optional(), requireEven); } return new TeamModule(teams, requireEven); }
@Override public PickupModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { KitParser kitParser = context.needModule(KitParser.class); FilterParser filterParser = context.needModule(FilterParser.class); RegionParser regionParser = context.needModule(RegionParser.class); for(Element el : XMLUtils.flattenElements(doc.getRootElement(), "pickups", "pickup")) { String name = el.getAttributeValue("name"); EntityType appearance = XMLUtils.parseEnum(Node.fromAttr(el, "appearance"), EntityType.class, "entity type", EntityType.ENDER_CRYSTAL); if(appearance != EntityType.ENDER_CRYSTAL) { throw new InvalidXMLException("Only ender crystal appearances are supported right now", el); } Filter visible = filterParser.property(el, "spawn-filter").optional(StaticFilter.ALLOW); Filter pickup = filterParser.property(el, "pickup-filter").optional(StaticFilter.ALLOW); Region region = regionParser.property(el, "region").validate(RandomPointsValidation.INSTANCE).required(); Kit kit = kitParser.property(el, "kit").optional(KitNode.EMPTY); Duration refresh = XMLUtils.parseDuration(Node.fromAttr(el, "respawn-time"), Duration.ofSeconds(3)); Duration cooldown = XMLUtils.parseDuration(Node.fromAttr(el, "pickup-time"), Duration.ofSeconds(3)); boolean effects = XMLUtils.parseBoolean(Node.fromAttr(el, "effects"), true); boolean sounds = XMLUtils.parseBoolean(Node.fromAttr(el, "sounds"), true); context.features().define(el, new PickupDefinitionImpl(name, appearance, visible, pickup, region, kit, refresh, cooldown, effects, sounds)); } return null; }
/** * Extracts page width and height attributes from the given ABBYY XML file and converts the document to ALTO. * * @param file * @return * @throws FileNotFoundException * @throws IOException * @throws JDOMException * @throws XMLStreamException * @throws FatalIndexerException * @should convert to ALTO correctly * @should throw IOException given wrong document format */ public static Map<String, Object> readAbbyyToAlto(File file) throws FileNotFoundException, IOException, XMLStreamException, FatalIndexerException { logger.trace("readAbbyy: {}", file.getAbsolutePath()); if (!FileFormat.ABBYYXML.equals(JDomXP.determineFileFormat(file))) { throw new IOException(file.getAbsolutePath() + " is not a valid ABBYY XML document."); } Map<String, Object> ret = new HashMap<>(); // Convert to ALTO Element alto = new ConvertAbbyyToAltoStaX().convert(file, new Date(file.lastModified())); if (alto != null) { Document altoDoc = new Document(); altoDoc.setRootElement(alto); ret = readAltoDoc(altoDoc, file.getAbsolutePath()); logger.debug("Converted ABBYY XML to ALTO: {}", file.getName()); } return ret; }
private static boolean checkSolrSchemaName(Document doc) { if (doc != null) { Element eleRoot = doc.getRootElement(); if (eleRoot != null) { String schemaName = eleRoot.getAttributeValue("name"); if (StringUtils.isNotEmpty(schemaName)) { try { if (schemaName.length() > SCHEMA_VERSION_PREFIX.length() && Integer.parseInt(schemaName.substring(SCHEMA_VERSION_PREFIX .length())) >= SolrIndexerDaemon.MIN_SCHEMA_VERSION) { return true; } } catch (NumberFormatException e) { logger.error("Schema version must contain a number."); } logger.error("Solr schema is not up to date; required: {}{}, found: {}", SCHEMA_VERSION_PREFIX, MIN_SCHEMA_VERSION, schemaName); } } } else { logger.error("Could not read the Solr schema name."); } return false; }
@Override public @Nullable ProjectileModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { final ItemParser itemParser = context.needModule(ItemParser.class); FilterParser filterParser = context.needModule(FilterParser.class); for(Element projectileElement : XMLUtils.flattenElements(doc.getRootElement(), "projectiles", "projectile")) { String name = projectileElement.getAttributeValue("name"); Double damage = XMLUtils.parseNumber(projectileElement.getAttribute("damage"), Double.class, (Double) null); double velocity = XMLUtils.parseNumber(Node.fromChildOrAttr(projectileElement, "velocity"), Double.class, 1.0); ClickAction clickAction = XMLUtils.parseEnum(Node.fromAttr(projectileElement, "click"), ClickAction.class, "click action", ClickAction.BOTH); Class<? extends Entity> entity = XMLUtils.parseEntityTypeAttribute(projectileElement, "projectile", Arrow.class); List<PotionEffect> potionKit = itemParser.parsePotionEffects(projectileElement); Filter destroyFilter = filterParser.parseOptionalProperty(projectileElement, "destroy-filter").orElse(null); Duration coolDown = XMLUtils.parseDuration(projectileElement.getAttribute("cooldown")); boolean throwable = XMLUtils.parseBoolean(projectileElement.getAttribute("throwable"), true); context.features().define(projectileElement, new ProjectileDefinitionImpl(name, damage, velocity, clickAction, entity, potionKit, destroyFilter, coolDown, throwable)); } return null; }
public static KillRewardModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { ImmutableList.Builder<KillReward> rewards = ImmutableList.builder(); final ItemParser itemParser = context.needModule(ItemParser.class); final Optional<ItemModifyModule> itemModifier = context.module(ItemModifyModule.class); // Must allow top-level children for legacy support for(Element elKillReward : XMLUtils.flattenElements(doc.getRootElement(), ImmutableSet.of("kill-rewards"), ImmutableSet.of("kill-reward", "killreward"), 0)) { ImmutableList.Builder<ItemStack> items = ImmutableList.builder(); for(Element itemEl : elKillReward.getChildren("item")) { final ItemStack item = itemParser.parseItem(itemEl, false); itemModifier.ifPresent(imm -> imm.applyRules(item)); items.add(item.immutableCopy()); } Filter filter = context.needModule(FilterParser.class).property(elKillReward, "filter").optional(StaticFilter.ALLOW); Kit kit = context.needModule(KitParser.class).property(elKillReward, "kit").optional(KitNode.EMPTY); rewards.add(new KillReward(items.build(), filter, kit)); } ImmutableList<KillReward> list = rewards.build(); if(list.isEmpty()) { return null; } else { return new KillRewardModule(list); } }
@Override public @Nullable ItemModifyModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { List<ItemRule> rules = new ArrayList<>(); for(Element elRule : XMLUtils.flattenElements(doc.getRootElement(), "item-mods", "rule")) { MaterialMatcher items = XMLUtils.parseMaterialMatcher(XMLUtils.getRequiredUniqueChild(elRule, "match")); // Always use a PotionMeta so the rule can have potion effects, though it will only apply those to potion items final Element elModify = XMLUtils.getRequiredUniqueChild(elRule, "modify"); final PotionMeta meta = (PotionMeta) Bukkit.getItemFactory().getItemMeta(Material.POTION); context.needModule(ItemParser.class).parseItemMeta(elModify, meta); final boolean defaultAttributes = XMLUtils.parseBoolean(elModify.getAttribute("default-attributes"), false); ItemRule rule = new ItemRule(items, meta, defaultAttributes); rules.add(rule); } return rules.isEmpty() ? null : new ItemModifyModule(rules); }
public void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest req = job.getRequest(); String path = job.getRequest().getPathInfo().substring(1); LOGGER.info(path); boolean b = tryLogin(path.substring(0, 6), path.substring(6), false); if (b) { org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject(); if (currentUser.hasRole("client")) { String hash = req.getUserPrincipal().getName(); File reportFile = new File(resultsDir + "/" + hash.substring(0, 6), "report.xml"); SAXBuilder builder = new SAXBuilder(); Document document = builder.build(reportFile); getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(document)); } } }
private Document xmlFromDOICrossRef(String doi) throws Exception { //send request to API MCRContent crossRefExport = crossRefConnection.getPublicationByDOI(doi); //transform JSON-response to XML MCRStringContent xml = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content")); //transform xml to mods MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("CrossRef2mods.xsl"); MCRContent mods = transformer.transform(xml); return mods.asXML(); }
private int getNumberOfPublications(String queryURL) throws JDOMException, IOException, SAXException { //build API URL //get response as XML-file Document response = getResponse(queryURL).asXML(); int numberOfPublications =0; //read and return total number of publications from XML-file try { numberOfPublications = Integer.parseInt(response.getRootElement().getChild("result").getAttributeValue("numFound")); } catch (Exception e) { LOGGER.info("found no documents in repository"); } return numberOfPublications; }
private Document exportPreferences(boolean globalSettings, Set<String> accounts) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); SettingsExporter.exportPreferences(RuntimeEnvironment.application, outputStream, globalSettings, accounts); Document document = parseXML(outputStream.toByteArray()); outputStream.close(); return document; }
/** * @param response * @param string * @throws IOException */ private static void wrongSchema(HttpServletResponse response, String parameter) throws IOException { Element searchRetrieveResponse = new Element("searchRetrieveResponse", SRU_NAMESPACE); Element version = new Element("version", SRU_NAMESPACE); version.setText("1.2"); searchRetrieveResponse.addContent(version); Element diagnostic = new Element("diagnostic", SRU_NAMESPACE); searchRetrieveResponse.addContent(diagnostic); Element uri = new Element("uri", DIAG_NAMESPACE); uri.setText("info:srw/diagnostic/1/66"); diagnostic.addContent(uri); Element details = new Element("details", DIAG_NAMESPACE); details.setText(" Unknown schema for retrieval"); diagnostic.addContent(details); Element message = new Element("message", DIAG_NAMESPACE); message.setText("Unknown schema for retrieval / " + parameter); diagnostic.addContent(message); Document doc = new Document(); doc.setRootElement(searchRetrieveResponse); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); XMLOutputter xmlOut = new XMLOutputter(format); xmlOut.output(doc, response.getOutputStream()); }
private static void missingArgument(HttpServletResponse response, String parameter) throws IOException { Element searchRetrieveResponse = new Element("searchRetrieveResponse", SRU_NAMESPACE); Element version = new Element("version", SRU_NAMESPACE); version.setText("1.2"); searchRetrieveResponse.addContent(version); Element diagnostic = new Element("diagnostic", SRU_NAMESPACE); searchRetrieveResponse.addContent(diagnostic); Element uri = new Element("uri", DIAG_NAMESPACE); uri.setText("info:srw/diagnostic/1/7"); diagnostic.addContent(uri); Element details = new Element("details", DIAG_NAMESPACE); details.setText("Mandatory parameter not supplied"); diagnostic.addContent(details); Element message = new Element("message", DIAG_NAMESPACE); message.setText("Mandatory parameter not supplied / " + parameter); diagnostic.addContent(message); Document doc = new Document(); doc.setRootElement(searchRetrieveResponse); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); XMLOutputter xmlOut = new XMLOutputter(format); xmlOut.output(doc, response.getOutputStream()); }
private static void unsupportedOperation(HttpServletResponse response, String parameter) throws IOException { Element searchRetrieveResponse = new Element("searchRetrieveResponse", SRU_NAMESPACE); Element version = new Element("version", SRU_NAMESPACE); version.setText("1.2"); searchRetrieveResponse.addContent(version); Element diagnostic = new Element("diagnostic", SRU_NAMESPACE); searchRetrieveResponse.addContent(diagnostic); Element uri = new Element("uri", DIAG_NAMESPACE); uri.setText("info:srw/diagnostic/1/4"); diagnostic.addContent(uri); Element details = new Element("details", DIAG_NAMESPACE); details.setText("Unsupported operation"); diagnostic.addContent(details); Element message = new Element("message", DIAG_NAMESPACE); message.setText("Unsupported operation / " + parameter); diagnostic.addContent(message); Document doc = new Document(); doc.setRootElement(searchRetrieveResponse); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); XMLOutputter xmlOut = new XMLOutputter(format); xmlOut.output(doc, response.getOutputStream()); }
private void parseXml(Buffer buffer, Future<Void> future) { String xmlFeed = buffer.toString("UTF-8"); final SAXBuilder sax = new SAXBuilder(); try { Document doc = sax.build(new InputSource(new StringReader(xmlFeed))); List<JsonObject> entries = RssUtils.toJson(doc); vertx.eventBus().publish((CommonConstants.VERTX_EVENT_BUS_HE_RSS_JDG_PUT), new JsonArray(entries)); future.complete(); } catch (JDOMException | IOException e) { future.fail(new RuntimeException("Exception caught when building SAX Document", e)); } }
public static List<JsonObject> toJson(Document doc) { List<JsonObject> entries = new ArrayList<JsonObject>(); List<Element> list = doc.getRootElement().getChild(CHANNEL).getChildren(ITEM); for (Element el : list) { JsonObject obj = new JsonObject(); obj.put(GUID, el.getChildText(GUID)); obj.put(TITLE, el.getChildText(TITLE)); obj.put(PUBLISH_DATE, el.getChildText(PUBLISH_DATE)); obj.put(ROAD, el.getChildText(ROAD)); obj.put(REGION, el.getChildText(REGION)); obj.put(COUNTY, el.getChildText(COUNTY)); JsonArray categories = new JsonArray(); for (Element cat : el.getChildren(CATEGORY)) { categories.add(new JsonObject().put(CATEGORY, cat.getText())); } obj.put(CATEGORIES, categories); obj.put(DESCRIPTION, el.getChildText(DESCRIPTION)); entries.add(obj); } return entries; }
public static final synchronized Document load(AdvancedFile file) { try { return load(file.createInputStream()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static final synchronized Document load(String jar_path) { try { return load(XMLUtil.class.getResourceAsStream(jar_path)); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static final synchronized Document load(InputStream inputStream) { try { return saxBuilder.build(inputStream); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static final synchronized boolean save(Document document, Format format, AdvancedFile file) { try { return save(document, format, file.createOutputstream(false)); } catch (Exception ex) { ex.printStackTrace(); return false; } }
public static final synchronized boolean save(Document document, Format format, OutputStream outputStream) { try { xmlOutput.setFormat(format); xmlOutput.output(document, outputStream); outputStream.close(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } }
public final XMLEditor load(Document document) { path.clear(); if (document == null) { this.rootElement = null; } else { this.rootElement = document.detachRootElement(); addFirst(this.rootElement); } this.document = document; return this; }
public final XMLEditor load(Document document, Element rootElement) { this.document = document; this.rootElement = rootElement; path.clear(); addFirst(this.rootElement); return this; }
/** * @see JDomXP#readXmlFile(String) * @verifies build document correctly */ @Test public void readXmlFile_shouldBuildDocumentCorrectly() throws Exception { Document doc = JDomXP.readXmlFile("resources/test/indexerconfig_solr_test.xml"); Assert.assertNotNull(doc); Assert.assertNotNull(doc.getRootElement()); }
@Override public @Nullable FreeForAllModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { Element elPlayers = doc.getRootElement().getChild("players"); if(context.hasModule(TeamModule.class)) { if(elPlayers != null) throw new InvalidXMLException("Cannot combine <players> and <teams>", elPlayers); return null; } else { int minPlayers = Config.minimumPlayers(); int maxPlayers = Bukkit.getMaxPlayers(); int maxOverfill = maxPlayers; org.bukkit.scoreboard.Team.OptionStatus nameTagVisibility = org.bukkit.scoreboard.Team.OptionStatus.ALWAYS; boolean colors = false; if(elPlayers != null) { minPlayers = XMLUtils.parseNumber(elPlayers.getAttribute("min"), Integer.class, minPlayers); maxPlayers = XMLUtils.parseNumber(elPlayers.getAttribute("max"), Integer.class, maxPlayers); maxOverfill = XMLUtils.parseNumber(elPlayers.getAttribute("max-overfill"), Integer.class, maxOverfill); nameTagVisibility = XMLUtils.parseNameTagVisibility(elPlayers, "show-name-tags").optional(nameTagVisibility); colors = XMLUtils.parseBoolean(elPlayers.getAttribute("colors"), colors); } if(minPlayers > maxPlayers) { throw new InvalidXMLException("min players (" + minPlayers + ") cannot be greater than max players (" + maxPlayers + ")", elPlayers); } return new FreeForAllModule(new FreeForAllOptions(minPlayers, maxPlayers, maxOverfill, nameTagVisibility, colors)); } }
@Override public void postParse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { context.features().all(EventRule.class).forEach(rethrowConsumer(rule -> { if(rule.lendKit() && !rule.kit().isRemovable()) { throw new InvalidXMLException("Specified lend-kit is not removable", context.features().definitionNode(rule)); } })); }
/** * @see JDomXP#splitLidoFile(File) * @verifies return empty list for non-exsting files */ @Test public void splitLidoFile_shouldReturnEmptyListForNonexstingFiles() throws Exception { File file = new File("no.xml"); Assert.assertFalse(file.isFile()); List<Document> docs = JDomXP.splitLidoFile(file); Assert.assertEquals(0, docs.size()); }
@Override public void postParse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { // TODO: Make this feasible and remove null checks in the spawn module //for(Spawn spawn : spawns) { // if(spawn.pointProvider.canFail()) { // throw new InvalidXMLException("Spawn is not guaranteed to provide a spawning location", context.features().getNode(spawn)); // } //} }
public static MaxBuildHeightModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { Element maxBuildHeightEl = XMLUtils.getUniqueChild(doc.getRootElement(), "maxbuildheight"); if(maxBuildHeightEl == null) { return null; } else { return new MaxBuildHeightModule(XMLUtils.parseNumber(maxBuildHeightEl, Integer.class)); } }
public static DiscardPotionBottlesModule parse(MapModuleContext context, Logger logger, Document doc) { Element el = doc.getRootElement().getChild("keep-potion-bottles"); if(el == null) { return new DiscardPotionBottlesModule(); } return null; }
public static ModifyBowProjectileModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { boolean changed = false; Class<? extends Entity> projectile = Arrow.class; float velocityMod = 1; Set<PotionEffect> potionEffects = new HashSet<>(); for(Element parent : doc.getRootElement().getChildren("modifybowprojectile")) { if(context.getProto().isNoOlderThan(ProtoVersions.FILTER_FEATURES)) { throw new InvalidXMLException("Module is discontinued as of " + ProtoVersions.FILTER_FEATURES.toString(), doc.getRootElement().getChild("modifybowprojectile")); } Element projectileElement = parent.getChild("projectile"); if(projectileElement != null) { projectile = XMLUtils.parseEntityType(projectileElement); changed = true; } Element velocityModElement = parent.getChild("velocityMod"); if(velocityModElement != null) { velocityMod = XMLUtils.parseNumber(velocityModElement, Float.class); changed = true; } for(Element elEffect : XMLUtils.getChildren(parent, "effect", "potion")) { potionEffects.add(XMLUtils.parsePotionEffect(elEffect)); changed = true; } } return !changed ? null : new ModifyBowProjectileModule(projectile, velocityMod, potionEffects); }
public static FriendlyFireRefundModule parse(MapModuleContext context, Logger logger, Document doc) throws InvalidXMLException { boolean on = XMLUtils.parseBoolean(Node.fromLastChildOrAttr(doc.getRootElement(), "friendly-fire-refund", "friendlyfirerefund"), true); if(on) { return new FriendlyFireRefundModule(); } else { return null; } }