/** * Acquires the reporting parameters within the xml and inserts into a given node * * @param element XML document that contains the reporting parameters act * @param thisNode Reporting parameter node */ private void setPerformanceTimeRangeOnNode(Element element, Node thisNode) { String performanceStartExprStr = getXpath(PERFORMANCE_START); String performanceEndExprStr = getXpath(PERFORMANCE_END); Consumer<? super Attribute> performanceStartConsumer = p -> { String start = p.getValue(); thisNode.putValue(PERFORMANCE_START, start, false); //start is formatted as follows: yyyyMMddHHmmss thisNode.putValue(PERFORMANCE_YEAR, start.substring(0, 4)); }; Consumer<? super Attribute> performanceEndConsumer = p -> thisNode.putValue(PERFORMANCE_END, p.getValue(), false); setOnNode(element, performanceStartExprStr, performanceStartConsumer, Filters.attribute(), false); setOnNode(element, performanceEndExprStr, performanceEndConsumer, Filters.attribute(), false); }
public void executeAttributeTest(String jsonPath, String expectedValue) { String xPath = PathCorrelator.prepPath(jsonPath, wrapper); Attribute attribute = null; try { attribute = evaluateXpath(xPath, Filters.attribute()); } catch (IOException | XmlException e) { fail(e.getMessage()); } if (attribute == null) { System.out.println("no attribute for path: " + jsonPath + "\n xpath: " + xPath); } if (!expectedValue.equals(attribute.getValue())) { System.err.println("( " + jsonPath + " ) value ( " + expectedValue + " ) does not equal ( " + attribute.getValue() + " ) at \n( " + xPath + " ). \nPlease investigate."); } assertThat(attribute.getValue()).isNotNull(); }
public static Attribute getRequiredAttribute(Element el, String name, String...aliases) throws InvalidXMLException { aliases = ArrayUtils.append(aliases, name); Attribute attr = null; for(String alias : aliases) { Attribute a = el.getAttribute(alias); if(a != null) { if(attr == null) { attr = a; } else { throw new InvalidXMLException("attributes '" + attr.getName() + "' and '" + alias + "' are aliases for the same thing, and cannot be combined", el); } } } if(attr == null) { throw new InvalidXMLException("attribute '" + name + "' is required", el); } return attr; }
/** * Parse a piece of formatted text, which can be either plain text with legacy * formatting codes, or JSON chat components. */ public static BaseComponent parseFormattedText(@Nullable Node node, BaseComponent def) throws InvalidXMLException { if(node == null) return def; // <blah translate="x"/> is shorthand for <blah>{"translate":"x"}</blah> if(node.isElement()) { final Attribute translate = node.asElement().getAttribute("translate"); if(translate != null) { return new TranslatableComponent(translate.getValue()); } } String text = node.getValueNormalize(); if(looksLikeJson(text)) { try { return Components.concat(ComponentSerializer.parse(node.getValue())); } catch(JsonParseException e) { throw new InvalidXMLException(e.getMessage(), node, e); } } else { return Components.concat(TextComponent.fromLegacyText(BukkitUtils.colorize(text))); } }
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; }
public ClonedElement(Element el) { super(el.getName(), el.getNamespace()); setParent(el.getParent()); final BoundedElement bounded = (BoundedElement) el; setLine(bounded.getLine()); setColumn(bounded.getColumn()); setStartLine(bounded.getStartLine()); setEndLine(bounded.getEndLine()); this.indexInParent = bounded.indexInParent(); setContent(el.cloneContent()); for(Attribute attribute : el.getAttributes()) { setAttribute(attribute.clone()); } }
/** * Evaluates the given XPath expression to a list of attributes. * * @param expr XPath expression to evaluate. * @param parent If not null, the expression is evaluated relative to this element. * @return {@link ArrayList} or null * @throws FatalIndexerException * @should return all values */ public List<Attribute> evaluateToAttributes(String expr, Object parent) throws FatalIndexerException { List<Attribute> retList = new ArrayList<>(); if (parent == null) { parent = doc; } List<Object> list = evaluate(expr, parent, Filters.attribute()); if (list == null) { return null; } for (Object object : list) { if (object instanceof Attribute) { Attribute attr = (Attribute) object; retList.add(attr); } } return retList; }
/** * Returns the string value of the given XML node object, depending on its type. * * @param object * @return String */ public static String objectToString(Object object) { if (object instanceof Element) { return ((Element) object).getText(); } else if (object instanceof Attribute) { return ((Attribute) object).getValue(); } else if (object instanceof Text) { return ((Text) object).getText(); } else if (object instanceof CDATA) { return ((CDATA) object).getText(); } else if (object instanceof Comment) { return ((Comment) object).getText(); } else if (object instanceof Double) { return String.valueOf(object); } else if (object instanceof Boolean) { return String.valueOf(object); } else if (object instanceof String) { return (String) object; } else if (object != null) { logger.error("Unknown object type: {}", object.getClass().getName()); return null; } else { return null; } }
/** * Parses a JDom2 Object into a string * @param e * Object (Element, Text, Document or Attribute) * @return String * @author sholzer (11.05.2015) */ public String parseString(Object e) { XMLOutputter element2String = new XMLOutputter(); if (e instanceof Element) { return element2String.outputString((Element) e); } if (e instanceof Text) { return element2String.outputString((Text) e); } if (e instanceof Document) { return element2String.outputString((Document) e); } if (e instanceof org.jdom2.Attribute) { Attribute a = (org.jdom2.Attribute) e; return a.getName() + "=\"" + a.getValue() + "\""; } return e.toString(); }
private boolean clean(Element element) { boolean changed = false; for (Iterator<Element> children = element.getChildren().iterator(); children.hasNext();) { Element child = children.next(); if (clean(child)) changed = true; if (!isRelevant(child)) { changed = true; children.remove(); } } for (Iterator<Attribute> attributes = element.getAttributes().iterator(); attributes.hasNext();) { Attribute attribute = attributes.next(); if (!isRelevant(attribute)) { changed = true; attributes.remove(); } } return changed; }
private static int parseDuration(Element xml) { Attribute attribute = xml.getAttribute("duration"); if (attribute != null) { Time time = XMLTime.parse(attribute, Time.SECOND); if (!time.isForever()) { try { return Math.toIntExact(time.toTicks()); } catch (ArithmeticException ignored) { } } return Integer.MAX_VALUE; } return 20; }
@Override public void process(XMLPreProcessor xml, Entry entry, Element map) throws Throwable { Attribute typeAttribute = entry.getElement().getAttribute("type"); Type type = Type.LOCAL; // default value if (typeAttribute != null) { Type parsedType = Type.valueOf(XMLParser.parseEnumValue(typeAttribute.getValue())); if (parsedType != null) { type = parsedType; } } String path = entry.getElement().getTextNormalize(); if (path.isEmpty()) { return; } Element include = type.process(this.plugin, entry.getElement(), path); if (include == null) { return; } for (Element rootChild : include.getChildren()) { this.attachElement(map, rootChild); } }
@Test public void testCompleteUndo() throws JaxenException, JDOMException { String template = "document[titles[title][title[2]]][authors/author[first='John'][last='Doe']]"; Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null)); Document before = doc.clone(); MCRChangeTracker tracker = new MCRChangeTracker(); Element titles = (Element) (new MCRBinding("document/titles", true, new MCRBinding(doc)).getBoundNode()); Element title = new Element("title").setAttribute("type", "alternative"); titles.addContent(2, title); tracker.track(MCRAddedElement.added(title)); Attribute lang = new Attribute("lang", "de"); doc.getRootElement().setAttribute(lang); tracker.track(MCRAddedAttribute.added(lang)); Element author = (Element) (new MCRBinding("document/authors/author", true, new MCRBinding(doc)) .getBoundNode()); tracker.track(MCRRemoveElement.remove(author)); tracker.undoChanges(doc); assertTrue(MCRXMLHelper.deepEqual(before, doc)); }
@Test public void testRemoveChangeTracking() throws JaxenException, JDOMException { String template = "document[titles[title][title[2]]][authors/author[first='John'][last='Doe']]"; Document doc = new Document(new MCRNodeBuilder().buildElement(template, null, null)); MCRChangeTracker tracker = new MCRChangeTracker(); Element titles = (Element) (new MCRBinding("document/titles", true, new MCRBinding(doc)).getBoundNode()); Element title = new Element("title").setAttribute("type", "alternative"); titles.addContent(2, title); tracker.track(MCRAddedElement.added(title)); Attribute lang = new Attribute("lang", "de"); doc.getRootElement().setAttribute(lang); tracker.track(MCRAddedAttribute.added(lang)); Element author = (Element) (new MCRBinding("document/authors/author", true, new MCRBinding(doc)) .getBoundNode()); tracker.track(MCRRemoveElement.remove(author)); doc = MCRChangeTracker.removeChangeTracking(doc); assertFalse(doc.getDescendants(Filters.processinginstruction()).iterator().hasNext()); }
@Test public void testNestedChanges() { Element root = new Element("root"); Document doc = new Document(root); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = new Element("title"); root.addContent(title); tracker.track(MCRAddedElement.added(title)); Attribute id = new Attribute("type", "main"); title.setAttribute(id); tracker.track(MCRAddedAttribute.added(id)); Element part = new Element("part"); title.addContent(part); tracker.track(MCRAddedElement.added(part)); tracker.track(MCRRemoveElement.remove(part)); tracker.track(MCRRemoveAttribute.remove(id)); tracker.track(MCRRemoveElement.remove(title)); tracker.undoChanges(doc); }
@Test public void testBreakpoint() { Element root = new Element("root"); Document doc = new Document(root); MCRChangeTracker tracker = new MCRChangeTracker(); Element title = new Element("title"); root.addContent(title); tracker.track(MCRAddedElement.added(title)); tracker.track(MCRBreakpoint.setBreakpoint(root, "Test")); Attribute href = new Attribute("href", "foo", MCRConstants.XLINK_NAMESPACE); root.setAttribute(href); tracker.track(MCRAddedAttribute.added(href)); tracker.track(MCRSetAttributeValue.setValue(href, "bar")); String label = tracker.undoLastBreakpoint(doc); assertEquals("Test", label); assertNull(root.getAttribute("href")); assertEquals(1, tracker.getChangeCounter()); }
public static List<Material> parseArray(Attribute attribute, Material def) { List<Material> results = new ArrayList<>(); if (attribute != null) { List<String> rawList = parseArray(attribute.getValue()); for (String raw : rawList) { if (raw.isEmpty()) { continue; } Material material = Material.matchMaterial(parseEnumValue(raw)); if (material != null) { results.add(material); } } } else if (def != null) { results.add(def); } return results; }
/** * tries to generate a valid MCRObject as JDOM Document. * * @return MCRObject */ public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException { MCRObject obj; // load the JDOM object XPathFactory.instance() .compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute()) .evaluate(input) .forEach(Attribute::detach); try { byte[] xml = new MCRJDOMContent(input).asByteArray(); obj = new MCRObject(xml, true); } catch (SAXParseException e) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); LOGGER.warn("Failure while parsing document:\n{}", xout.outputString(input)); throw e; } Date curTime = new Date(); obj.getService().setDate("modifydate", curTime); // return the XML tree input = obj.createXML(); return input; }
@Test public void testXPath() { Element root = new Element("root"); Element title1 = new Element("title"); Element title2 = new Element("title"); Element author = new Element("contributor"); Attribute role = new Attribute("role", "author"); Attribute lang = new Attribute("lang", "de", Namespace.XML_NAMESPACE); author.setAttribute(role); author.setAttribute(lang); root.addContent(title1); root.addContent(author); root.addContent(title2); new Document(root); assertEquals("/root", MCRXPathBuilder.buildXPath(root)); assertEquals("/root/contributor", MCRXPathBuilder.buildXPath(author)); assertEquals("/root/title", MCRXPathBuilder.buildXPath(title1)); assertEquals("/root/title[2]", MCRXPathBuilder.buildXPath(title2)); assertEquals("/root/contributor/@role", MCRXPathBuilder.buildXPath(role)); assertEquals("/root/contributor/@xml:lang", MCRXPathBuilder.buildXPath(lang)); root.detach(); assertEquals("root", MCRXPathBuilder.buildXPath(root)); assertEquals("root/contributor", MCRXPathBuilder.buildXPath(author)); }
@Test public void testBuildingAttributes() throws JaxenException, JDOMException { Attribute built = new MCRNodeBuilder().buildAttribute("@attribute", null, null); assertNotNull(built); assertEquals("attribute", built.getName()); assertTrue(built.getValue().isEmpty()); built = new MCRNodeBuilder().buildAttribute("@attribute", "value", null); assertNotNull(built); assertEquals("attribute", built.getName()); assertEquals("value", built.getValue()); Element parent = new Element("parent"); built = new MCRNodeBuilder().buildAttribute("@attribute", null, parent); assertNotNull(built); assertEquals("attribute", built.getName()); assertNotNull(built.getParent()); assertEquals("parent", built.getParent().getName()); }
@Test public void testBuildingValues() throws JaxenException, JDOMException { Attribute built = new MCRNodeBuilder().buildAttribute("@attribute='A \"test\"'", "ignore", null); assertNotNull(built); assertEquals("attribute", built.getName()); assertEquals("A \"test\"", built.getValue()); built = new MCRNodeBuilder().buildAttribute("@attribute=\"O'Brian\"", null, null); assertNotNull(built); assertEquals("attribute", built.getName()); assertEquals("O'Brian", built.getValue()); built = new MCRNodeBuilder().buildAttribute("@mime=\"text/plain\"", null, null); assertNotNull(built); assertEquals("mime", built.getName()); assertEquals("text/plain", built.getValue()); Element element = new MCRNodeBuilder().buildElement("name=\"O'Brian\"", null, null); assertNotNull(element); assertEquals("name", element.getName()); assertEquals("O'Brian", element.getText()); }
private void attachElement(Element apply, Element from) { // attributes for (Attribute attribute : from.getAttributes()) { if (apply.getAttribute(attribute.getName()) == null) { apply.setAttribute(attribute); } } // text if (!from.getText().isEmpty()) { apply.setText(from.getText()); } // children for (Element element : from.getChildren()) { this.attachElement(apply, element.detach()); } }
@Test public void testExpressionsToIgnore() throws JaxenException, JDOMException { Element built = new MCRNodeBuilder().buildElement("element[2]", null, null); assertNotNull(built); assertEquals("element", built.getName()); built = new MCRNodeBuilder().buildElement("element[contains(.,'foo')]", null, null); assertNotNull(built); assertEquals("element", built.getName()); built = new MCRNodeBuilder().buildElement("foo|bar", null, null); assertNull(built); Attribute attribute = new MCRNodeBuilder().buildAttribute("@lang[preceding::*/foo='bar']", "value", null); assertNotNull(attribute); assertEquals("lang", attribute.getName()); assertEquals("value", attribute.getValue()); built = new MCRNodeBuilder().buildElement("parent/child/following::node/foo='bar'", null, null); assertNotNull(built); assertEquals("child", built.getName()); assertNotNull(built.getParentElement()); assertEquals("parent", built.getParentElement().getName()); assertEquals(0, built.getChildren().size()); assertEquals("", built.getText()); }
private Element generateCategoryElement(final Category cat) { final Namespace namespace = getFeedNamespace(); final Element catElement = new Element("category", namespace); final String term = cat.getTerm(); if (term != null) { final Attribute termAttribute = new Attribute("term", term); catElement.setAttribute(termAttribute); } final String label = cat.getLabel(); if (label != null) { final Attribute labelAttribute = new Attribute("label", label); catElement.setAttribute(labelAttribute); } final String scheme = cat.getScheme(); if (scheme != null) { final Attribute schemeAttribute = new Attribute("scheme", scheme); catElement.setAttribute(schemeAttribute); } return catElement; }
private Element generateGeneratorElement(final Generator generator) { final Element generatorElement = new Element("generator", getFeedNamespace()); final String url = generator.getUrl(); if (url != null) { final Attribute urlAttribute = new Attribute("uri", url); generatorElement.setAttribute(urlAttribute); } final String version2 = generator.getVersion(); if (version2 != null) { final Attribute versionAttribute = new Attribute("version", version2); generatorElement.setAttribute(versionAttribute); } final String value = generator.getValue(); if (value != null) { generatorElement.addContent(value); } return generatorElement; }
@Override public void setDefaultMaxGameId() { Element queueElement = plugin.getSettings().getData().getChild("queue"); if (queueElement == null) { return; } Attribute attribute = queueElement.getAttribute("restart-after"); if (attribute == null) { return; } try { this.setMaxGameId(attribute.getIntValue()); } catch (DataConversionException ignored) { } }
public static Generator parse(Element xml, ArcadePlugin plugin, ArcadeMap map) throws MapParserException { if (xml == null) { return null; } GeneratorType type = GeneratorType.forName(xml.getTextNormalize()); if (type == null) { return null; } Properties properties = new Properties(); for (Attribute attribute : xml.getAttributes()) { properties.setProperty(attribute.getName(), attribute.getValue()); } return (Generator) type.create(plugin, map, properties); }
private long parseSeed(Element parent) throws MapParserException { if (parent != null) { try { Element xml = parent.getChild("generator"); if (xml != null) { Attribute seed = xml.getAttribute("seed"); if (seed != null) { return seed.getLongValue(); } } } catch (DataConversionException ignored) { } } return ArcadeMap.DEFAULT_SEED; }
public static BookMeta parseBook(Element xml, BookMeta source) { Element book = xml.getChild("book"); if (book != null) { Attribute author = book.getAttribute("author"); if (author != null) { source.setAuthor(parseMessage(author.getValue())); } Attribute title = book.getAttribute("title"); if (title != null) { source.setTitle(parseMessage(title.getValue())); } for (Element page : book.getChildren("page")) { source.addPage(parseMessage(page.getTextNormalize())); } } return source; }
public static EnchantmentStorageMeta parseEnchantmentStorage(Element xml, EnchantmentStorageMeta source) { Element book = xml.getChild("enchanted-book"); if (book != null) { for (Element enchantment : book.getChildren("enchantment")) { Enchantment type = Enchantment.getByName(XMLParser.parseEnumValue(enchantment.getTextNormalize())); int level = 1; try { Attribute levelAttribute = enchantment.getAttribute("level"); if (levelAttribute != null) { level = levelAttribute.getIntValue(); } } catch (DataConversionException ignored) { } source.addStoredEnchant(type, level, false); } } return source; }
private static Map<Enchantment, Integer> parseEnchantments(Element xml) { Map<Enchantment, Integer> enchantments = new HashMap<>(); Element element = xml.getChild("enchantments"); if (element != null) { for (Element enchantment : element.getChildren("enchantment")) { Enchantment type = Enchantment.getByName(XMLParser.parseEnumValue(enchantment.getTextNormalize())); int level = 1; try { Attribute levelAttribute = enchantment.getAttribute("level"); if (levelAttribute != null) { level = levelAttribute.getIntValue(); } } catch (DataConversionException ignored) { } enchantments.put(type, level); } } return enchantments; }
private Region parseFilters(Element xml, Region region) { if (this.filters == null) { return region; } for (RegionEventType event : RegionEventType.values()) { Attribute attribute = xml.getAttribute(event.getAttribute()); if (attribute == null) { continue; } FilterSet filter = this.filters.getFilter(attribute.getValue()); if (filter == null) { continue; } region.setFilter(event, filter); } return region; }
/** * Dig up the stratifier's id and assign it to thisNode * @param element DOM element * @param thisNode current node */ private void setStratifierId(Element element, Node thisNode) { String expressionStr = getXpath(STRATIFIER_ID); Consumer<? super Attribute> consumer = attr -> { String code = attr.getValue(); thisNode.putValue(STRATIFIER_ID, code, false); }; setOnNode(element, expressionStr, consumer, Filters.attribute(), false); }
/** * Looks up the entity Id from the element if the program name is CPC+ * <id root="2.16.840.1.113883.3.249.5.1" extension="AR000000" * * @param element Xml fragment being parsed. * @param thisNode The output internal representation of the document */ private void setEntityIdOnNode(Element element, Node thisNode) { if (Program.isCpc(thisNode)) { Consumer<Attribute> consumer = id -> thisNode.putValue(ENTITY_ID, id.getValue(), false); setOnNode(element, getXpath(ENTITY_ID), consumer, Filters.attribute(), false); } }
/** * Will decode the program name from the xml * * @param element Xml fragment being parsed. * @param thisNode The output internal representation of the document */ private void setProgramNameOnNode(Element element, Node thisNode) { Consumer<? super Attribute> consumer = p -> { String[] nameEntityPair = getProgramNameEntityPair(p.getValue()); thisNode.putValue(PROGRAM_NAME, nameEntityPair[0], false); thisNode.putValue(ENTITY_TYPE, nameEntityPair[1], false); }; setOnNode(element, getXpath(PROGRAM_NAME), consumer, Filters.attribute(), false); context.setProgram(Program.extractProgram(thisNode)); }
/** * Will decode the NPI from the xml * * @param element Xml fragment being parsed. * @param thisNode The output internal representation of the document */ private void setNationalProviderIdOnNode(Element element, Node thisNode) { Consumer<? super Attribute> consumer = p -> thisNode.putValue(NATIONAL_PROVIDER_IDENTIFIER, p.getValue()); setOnNode(element, getXpath(NATIONAL_PROVIDER_IDENTIFIER), consumer, Filters.attribute(), true); }
/** * Will decode the TPI from the xml * * @param element Xml fragment being parsed. * @param thisNode The output internal representation of the document */ private void setTaxProviderTaxIdOnNode(Element element, Node thisNode) { Consumer<? super Attribute> consumer = p -> thisNode.putValue(TAX_PAYER_IDENTIFICATION_NUMBER, p.getValue()); setOnNode(element, getXpath(TAX_PAYER_IDENTIFICATION_NUMBER), consumer, Filters.attribute(), true); }
/** * Locate measure code value in element and set on node. * * @param element Object that holds the XML representation of measure id * @param thisNode Holder for decoded data */ private void setMeasure(Element element, Node thisNode) { String expressionStr = getXpath(MEASURE_TYPE); Consumer<? super Attribute> consumer = attr -> { String code = attr.getValue(); if (MEASURES.contains(code)) { thisNode.putValue(MEASURE_TYPE, code, false); } }; setOnNode(element, expressionStr, consumer, Filters.attribute(), false); }
/** * Locate measure sub-population GUUID from the element and set on node. * * @param element Object that holds the XML representation of measure id * @param thisNode Holder for decoded data */ private void setPopulationId(Element element, Node thisNode) { String expressionStr = getXpath(MEASURE_POPULATION); Consumer<? super Attribute> consumer = attr -> thisNode.putValue(MEASURE_POPULATION, attr.getValue(), false); setOnNode(element, expressionStr, consumer, Filters.attribute(), false); }
/** * Parses element containing a IA Measure into a node * * @param element Top element in the XML document * @param thisNode Top node created in the XML document * @return result that the decoder is finished for this node */ @Override protected DecodeResult internalDecode(Element element, Node thisNode) { String expressionStr = getXpath("measureId"); Consumer<? super Attribute> consumer = p -> thisNode.putValue("measureId", p.getValue()); setOnNode(element, expressionStr, consumer, Filters.attribute(), true); decode(element.getChild("component", defaultNs), thisNode); return DecodeResult.TREE_FINISHED; }