List of usage examples for org.jdom2 Document getDescendants
@Override public <F extends Content> IteratorIterable<F> getDescendants(final Filter<F> filter)
From source file:LineNumberSAXBuilderDemo.java
License:Open Source License
public static void main(String[] args) throws Exception { SAXBuilder builder = new SAXBuilder(); builder.setSAXHandlerFactory(LineNumberSAXHandler.SAXFACTORY); Document doc = builder.build(new StringReader(xml)); for (Iterator<LineNumberElement> iter = doc.getDescendants(Filters.fclass(LineNumberElement.class)); iter .hasNext();) {//from ww w . j a v a2s .c om LineNumberElement e = iter.next(); System.out.println(e.getName() + ": lines " + e.getStartLine() + " to " + e.getEndLine()); } }
From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java
License:Open Source License
static List<Challenge> parseNmasPolicyXML(final String str, final Locale locale) throws IOException, JDOMException { final List<Challenge> returnList = new ArrayList<Challenge>(); final Reader xmlreader = new StringReader(str); final SAXBuilder builder = new SAXBuilder(); final Document doc = builder.build(xmlreader); final boolean required = doc.getRootElement().getName().equals("RequiredQuestions"); for (Iterator qIter = doc.getDescendants(new ElementFilter("Question")); qIter.hasNext();) { final Element loopQ = (Element) qIter.next(); final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255); final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 1); final String challengeText = readDisplayString(loopQ, locale); final Challenge challenge = new ChaiChallenge(required, challengeText, minLength, maxLength, true, 0, false);/*from w w w .j a va 2 s . c o m*/ returnList.add(challenge); } for (Iterator iter = doc.getDescendants(new ElementFilter("UserDefined")); iter.hasNext();) { final Element loopQ = (Element) iter.next(); final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255); final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 1); final Challenge challenge = new ChaiChallenge(required, null, minLength, maxLength, false, 0, false); returnList.add(challenge); } return returnList; }
From source file:com.novell.ldapchai.impl.edir.NmasResponseSet.java
License:Open Source License
static ChallengeSet parseNmasUserResponseXML(final String str) throws IOException, JDOMException, ChaiValidationException { final List<Challenge> returnList = new ArrayList<Challenge>(); final Reader xmlreader = new StringReader(str); final SAXBuilder builder = new SAXBuilder(); final Document doc = builder.build(xmlreader); final Element rootElement = doc.getRootElement(); final int minRandom = StringHelper.convertStrToInt(rootElement.getAttributeValue("RandomQuestions"), 0); final String guidValue; {/* w ww .j a va 2 s .co m*/ final Attribute guidAttribute = rootElement.getAttribute("GUID"); guidValue = guidAttribute == null ? null : guidAttribute.getValue(); } for (Iterator iter = doc.getDescendants(new ElementFilter("Challenge")); iter.hasNext();) { final Element loopQ = (Element) iter.next(); final int maxLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MaxLength"), 255); final int minLength = StringHelper.convertStrToInt(loopQ.getAttributeValue("MinLength"), 2); final String defineStrValue = loopQ.getAttributeValue("Define"); final boolean adminDefined = defineStrValue.equalsIgnoreCase("Admin"); final String typeStrValue = loopQ.getAttributeValue("Type"); final boolean required = typeStrValue.equalsIgnoreCase("Required"); final String challengeText = loopQ.getText(); final Challenge challenge = new ChaiChallenge(required, challengeText, minLength, maxLength, adminDefined, 0, false); returnList.add(challenge); } return new ChaiChallengeSet(returnList, minRandom, null, guidValue); }
From source file:cz.muni.fi.mir.mathmlcanonicalization.modules.MfencedReplacer.java
License:Apache License
@Override public void execute(final Document doc) { if (doc == null) { throw new NullPointerException("doc"); }/*from w w w.j a va2s .c o m*/ final List<Element> toReplace = new ArrayList<Element>(); for (Element mfenced : doc.getDescendants(new ElementFilter(FENCED))) { toReplace.add(mfenced); } if (toReplace.isEmpty()) { LOGGER.fine("No mfenced elements found"); return; } for (Element mfenced : toReplace) { replaceMfenced(mfenced); } }
From source file:jodtemplate.pptx.postprocessor.StylePostprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final IteratorIterable<Element> atElements = document .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace())); final List<Element> atElementsList = new ArrayList<>(); while (atElements.hasNext()) { atElementsList.add(atElements.next()); }/*from www . j a v a2 s .c o m*/ for (Element at : atElementsList) { if (at.getContentSize() != 0) { final Content content = at.getContent(0); if (content instanceof Comment) { final Comment comment = (Comment) content; processComment(comment, at, slide, configuration); } } } return document; }
From source file:jodtemplate.pptx.preprocessor.FormatTagsPreprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) { final IteratorIterable<Element> apElements = document .getDescendants(Filters.element(PPTXDocument.P_ELEMENT, getNamespace())); final List<Element> apElementsList = new ArrayList<>(); while (apElements.hasNext()) { apElementsList.add(apElements.next()); }/*from w ww . ja v a 2 s.c o m*/ for (Element ap : apElementsList) { final List<Element> apChildrenList = ap.getChildren(); if (apChildrenList.size() != 0) { final List<Element> arabrElementsListResult = processArAndABrElements(apChildrenList, configuration.getParserFactory().createParser()); int firstArElementIndex = ap.indexOf(ap.getChild(PPTXDocument.R_ELEMENT, getNamespace())); if (firstArElementIndex < 0) { firstArElementIndex = 0; } ap.removeChildren(PPTXDocument.R_ELEMENT, getNamespace()); ap.removeChildren(PPTXDocument.BR_ELEMENT, getNamespace()); ap.addContent(firstArElementIndex, arabrElementsListResult); } } return document; }
From source file:jodtemplate.pptx.preprocessor.PicPreprocessor.java
License:Apache License
public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final ExpressionHandler expressionHandler = configuration.getExpressionHandler(); final IteratorIterable<Element> picElements = document .getDescendants(Filters.element(PPTXDocument.PIC_ELEMENT, getPresentationmlNamespace())); final List<Element> picElementsList = new ArrayList<>(); while (picElements.hasNext()) { picElementsList.add(picElements.next()); }//w w w. ja v a 2 s . com for (Element pic : picElementsList) { final Attribute descr = pic.getChild(PPTXDocument.NVPICPR_ELEMENT, getPresentationmlNamespace()) .getChild(PPTXDocument.CNVPR_ELEMENT, getPresentationmlNamespace()) .getAttribute(PPTXDocument.DESCR_ATTR); if (descr != null && expressionHandler.isExpression(descr.getValue())) { final VariableExpression expression = expressionHandler.createVariableExpression(descr.getValue()); Object value; try { value = PropertyUtils.getNestedProperty(context, expression.getVariable()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new JODTemplateException("Unable to get value: " + expression.getVariable()); } if (value instanceof ImageField) { final ImageField imageField = (ImageField) value; imageService.insertImage(imageField, slide, resources, pic); } else { throw new JODTemplateException("Field " + expression.getVariable() + " should contain image."); } } } return document; }
From source file:jodtemplate.pptx.preprocessor.ShortListPreprocessor.java
License:Apache License
@Override public Document process(final Map<String, Object> context, final Document document, final Slide slide, final Resources resources, final Configuration configuration) throws JODTemplateException { final IteratorIterable<Element> parentElements = document .getDescendants(Filters.element(parentElement, getNamespace())); final List<Element> parentElementsList = new ArrayList<>(); while (parentElements.hasNext()) { parentElementsList.add(parentElements.next()); }/*from www .j a v a2 s. co m*/ for (final Element parent : parentElementsList) { final IteratorIterable<Element> atElements = parent .getDescendants(Filters.element(PPTXDocument.T_ELEMENT, getNamespace())); final List<Element> atElementsList = new ArrayList<>(); while (atElements.hasNext()) { atElementsList.add(atElements.next()); } final ExpressionHandler expressionHandler = configuration.getExpressionHandler(); boolean isLoop = false; InlineListExpression expression = null; for (final Element at : atElementsList) { final String text = at.getText(); if (configuration.getExpressionHandler().isInlineList(text)) { expression = expressionHandler.createInlineListExpression(text); at.setText(expressionHandler.createVariable(expression.getVariable())); isLoop = true; } } if (isLoop) { int apIndex = parent.getParent().indexOf(parent); final String beginList = expressionHandler.createBeginList(expression.getWhat(), expression.getAs()); final String endList = expressionHandler.createEndList(); parent.getParent().addContent(apIndex, new Comment(beginList)); apIndex++; parent.getParent().addContent(apIndex + 1, new Comment(endList)); } } return document; }
From source file:org.dhatim.edi.utils.EDISchemaEntityManager.java
License:Open Source License
/** * Factory method to create a new instance * * @return//from w w w . j ava 2 s .c o m * @throws IOException */ public static EDISchemaEntityManager createInstance() throws IOException { List<URL> urnFiles = ClassUtil.getResources("/fragment.xml", EDISchemaEntityManager.class); Map<String, String> catalog = new HashMap<String, String>(); log.debug("Loading XML schemas information from " + urnFiles); for (URL url : urnFiles) { InputStream in = url.openStream(); try { if (in != null) { SAXBuilder builder = new SAXBuilder(); Document document = builder.build(in); @SuppressWarnings("unchecked") Iterator<Element> it = document.getDescendants(new ElementFilter("uri")); while (it.hasNext()) { Element next = it.next(); String uri = next.getAttributeValue("uri"); String name = next.getAttributeValue("name"); // URI is now something like platform:/fragment/org.milyn.edi.unedifact.d99a-mapping/path/path/file.xsd // we need only /path/path/file.xsd // cut platform:/fragment/ uri = uri.substring(19); // cut after first '/' uri = uri.substring(uri.indexOf('/')); catalog.put(name, uri); } } } catch (JDOMException e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } } } // One resource we have to add manually catalog.put("urn:org.milyn.edi.unedifact.v41", "/META-INF/schema/v41-segments.xsd"); log.debug("Loaded " + catalog.size() + " entries"); return new EDISchemaEntityManager(catalog); }
From source file:org.graphwalker.io.GraphML.java
License:Open Source License
/** * Parses the graphml file, and returns the model as a edu.uci.ics.jung.graph.impl.Graph * // w ww . j av a 2 s . c o m * @param fileName The graphml file * @return The graph */ private Graph parseFile(String fileName) { Graph graph = new Graph(); graph.setFileKey(fileName); SAXBuilder parser = new SAXBuilder(); try { logger.debug("Parsing file: " + fileName); Document doc = parser.build(Util.getFile(fileName)); // Parse all vertices (nodes) Iterator<Element> iter_node = doc.getDescendants(new ElementFilter("node")); while (iter_node.hasNext()) { Object o = iter_node.next(); if (o instanceof Element) { Element element = (Element) o; if (element.getAttributeValue("yfiles.foldertype") != null) { logger.debug(" Excluded node: " + element.getAttributeValue("yfiles.foldertype")); continue; } Iterator<Element> iterUMLNoteIter = element.getDescendants(new ElementFilter("UMLNoteNode")); if (iterUMLNoteIter.hasNext()) { Iterator<Element> iter_label = element.getDescendants(new ElementFilter("NodeLabel")); if (iter_label.hasNext()) { Object o3 = iter_label.next(); Element nodeLabel = (Element) o3; logger.debug(" Full name: '" + nodeLabel.getQualifiedName() + "'"); logger.debug(" Name: '" + nodeLabel.getTextTrim() + "'"); graph.setDescriptionKey(nodeLabel.getTextTrim()); } continue; } logger.debug(" id: " + element.getAttributeValue("id")); // Used to remember which vertex to store the image location. Vertex currentVertex = null; Iterator<Element> iterNodeLabel = element.getDescendants(new ElementFilter("NodeLabel")); while (iterNodeLabel.hasNext()) { Object o2 = iterNodeLabel.next(); if (o2 instanceof Element) { Element nodeLabel = (Element) o2; logger.debug(" Full name: '" + nodeLabel.getQualifiedName() + "'"); logger.debug(" Name: '" + nodeLabel.getTextTrim() + "'"); String str = nodeLabel.getTextTrim(); Vertex v = new Vertex(); graph.addVertex(v); currentVertex = v; // Parse description Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data")); while (iter_data.hasNext()) { Object o3 = iter_data.next(); if (o instanceof Element) { Element data = (Element) o3; if (!data.getAttributeValue("key").equals("d5")) continue; v.setDesctiptionKey(data.getText()); break; } } v.setIdKey(element.getAttributeValue("id")); v.setVisitedKey(0); v.setFileKey(fileName); v.setFullLabelKey(str); v.setIndexKey(getNewVertexAndEdgeIndex()); v.setLabelKey(Vertex.getLabel(str)); v.setMergeKey(AbstractElement.isMerged(str)); v.setNoMergeKey(AbstractElement.isNoMerge(str)); v.setBlockedKey(AbstractElement.isBlocked(str)); v.setSwitchModelKey(Vertex.isSwitchModel(str)); Integer index = AbstractElement.getIndex(str); if (index != 0) { v.setIndexKey(index); } v.setReqTagKey(AbstractElement.getReqTags(str)); } } // Extract any manual test instructions Iterator<Element> iterData = element.getDescendants(new ElementFilter("data")); while (iterData.hasNext() && currentVertex != null) { Object o2 = iterData.next(); if (o2 instanceof Element) { Element data = (Element) o2; if (!data.getContent().isEmpty() && data.getContent(0) != null) { String text = data.getContent(0).getValue().trim(); if (!text.isEmpty()) { logger.debug(" Data: '" + text + "'"); currentVertex.setManualInstructions(text); } } } } // Using the yEd editor, an image can be used to depict the vertex. // When merging multiple // graphs into one, the code below, stores the image location, which // will be used when // writing that merged graphml file. Iterator<Element> iterImage = element.getDescendants(new ElementFilter("Image")); while (iterImage.hasNext() && currentVertex != null) { Object o2 = iterImage.next(); if (o2 instanceof Element) { Element image = (Element) o2; if (image.getAttributeValue("href") != null) { logger.debug(" Image: '" + image.getAttributeValue("href") + "'"); currentVertex.setImageKey(image.getAttributeValue("href")); } } } Iterator<Element> iterGeometry = element.getDescendants(new ElementFilter("Geometry")); while (iterGeometry.hasNext() && currentVertex != null) { Object o2 = iterGeometry.next(); if (o2 instanceof Element) { Element geometry = (Element) o2; logger.debug(" width: '" + geometry.getAttributeValue("width") + "'"); logger.debug(" height: '" + geometry.getAttributeValue("height") + "'"); logger.debug(" x position: '" + geometry.getAttributeValue("x") + "'"); logger.debug(" y position: '" + geometry.getAttributeValue("y") + "'"); currentVertex.setWidth(Float.parseFloat(geometry.getAttributeValue("width"))); currentVertex.setHeight(Float.parseFloat(geometry.getAttributeValue("height"))); currentVertex.setLocation( new Point2D.Float(Float.parseFloat(geometry.getAttributeValue("x")), Float.parseFloat(geometry.getAttributeValue("y")))); } } Iterator<Element> iterFill = element.getDescendants(new ElementFilter("Fill")); while (iterFill.hasNext() && currentVertex != null) { Object o2 = iterFill.next(); if (o2 instanceof Element) { Element fill = (Element) o2; logger.debug(" fill color: '" + fill.getAttributeValue("color") + "'"); currentVertex.setFillColor(new Color( Integer.parseInt(fill.getAttributeValue("color").replace("#", ""), 16))); } } } } Object[] vertices = graph.getVertices().toArray(); // Parse all edges (arrows or transitions) Iterator<Element> iter_edge = doc.getDescendants(new ElementFilter("edge")); while (iter_edge.hasNext()) { Object o = iter_edge.next(); if (o instanceof Element) { Element element = (Element) o; logger.debug(" id: " + element.getAttributeValue("id")); Edge e = new Edge(); Iterator<Element> iter2 = element.getDescendants(new ElementFilter("EdgeLabel")); Element edgeLabel = null; if (iter2.hasNext()) { Object o2 = iter2.next(); if (o2 instanceof Element) { edgeLabel = (Element) o2; logger.debug(" Full name: '" + edgeLabel.getQualifiedName() + "'"); logger.debug(" Name: '" + edgeLabel.getTextTrim() + "'"); logger.debug(" Edge label x: " + edgeLabel.getAttributeValue("x")); logger.debug(" Edge label y: " + edgeLabel.getAttributeValue("y")); logger.debug(" Edge label width: " + edgeLabel.getAttributeValue("width")); logger.debug(" Edge label height: " + edgeLabel.getAttributeValue("height")); e.setLabelHeight(Float.parseFloat(edgeLabel.getAttributeValue("height"))); e.setLabelWidth(Float.parseFloat(edgeLabel.getAttributeValue("width"))); e.setLabelLocation(new Point2D.Float(Float.parseFloat(edgeLabel.getAttributeValue("x")), Float.parseFloat(edgeLabel.getAttributeValue("y")))); } } Iterator<Element> iter3 = element.getDescendants(new ElementFilter("Path")); Element edgePath = null; if (iter3.hasNext()) { Object o3 = iter3.next(); if (o3 instanceof Element) { edgePath = (Element) o3; logger.debug(" Path sx: '" + edgePath.getAttributeValue("sx")); logger.debug(" Path sy: '" + edgePath.getAttributeValue("sy")); logger.debug(" Path tx: '" + edgePath.getAttributeValue("tx")); logger.debug(" Path ty: '" + edgePath.getAttributeValue("ty")); e.setPathSourceLocation( new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("sx")), Float.parseFloat(edgePath.getAttributeValue("sy")))); e.setPathTargetLocation( new Point2D.Float(Float.parseFloat(edgePath.getAttributeValue("tx")), Float.parseFloat(edgePath.getAttributeValue("ty")))); } } // Add edge path points if there is any. Iterator<Element> iter4 = element.getDescendants(new ElementFilter("Point")); Element edgePathPoint = null; while (iter4.hasNext()) { Object o4 = iter4.next(); if (o4 instanceof Element) { edgePathPoint = (Element) o4; logger.debug(" PathPoint x: '" + edgePathPoint.getAttributeValue("x")); logger.debug(" PathPoint y: '" + edgePathPoint.getAttributeValue("y")); e.setPathPoints( new Point2D.Float(Float.parseFloat(edgePathPoint.getAttributeValue("x")), Float.parseFloat(edgePathPoint.getAttributeValue("y")))); } } logger.debug(" source: " + element.getAttributeValue("source")); logger.debug(" target: " + element.getAttributeValue("target")); Vertex source = null; Vertex dest = null; for (Object vertice : vertices) { Vertex vertex = (Vertex) vertice; // Find source vertex if (vertex.getIdKey().equals(element.getAttributeValue("source")) && vertex.getFileKey().equals(fileName)) { source = vertex; } if (vertex.getIdKey().equals(element.getAttributeValue("target")) && vertex.getFileKey().equals(fileName)) { dest = vertex; } } if (source == null) { String msg = "Could not find starting node for edge. Name: '" + element.getAttributeValue("source") + "' In file '" + fileName + "'"; logger.error(msg); throw new RuntimeException(msg); } if (dest == null) { String msg = "Could not find end node for edge. Name: '" + element.getAttributeValue("target") + "' In file '" + fileName + "'"; logger.error(msg); throw new RuntimeException(msg); } e.setIdKey(element.getAttributeValue("id")); e.setFileKey(fileName); e.setIndexKey(getNewVertexAndEdgeIndex()); // Parse description Iterator<Element> iter_data = element.getDescendants(new ElementFilter("data")); while (iter_data.hasNext()) { Object o3 = iter_data.next(); if (o instanceof Element) { Element data = (Element) o3; if (!data.getAttributeValue("key").equals("d9")) continue; e.setDesctiptionKey(data.getText()); break; } } if (!graph.addEdge(e, source, dest)) { String msg = "Failed adding edge: " + e + ", to graph: " + graph; logger.error(msg); throw new RuntimeException(msg); } if (edgeLabel != null) { // The label of an edge has the following format: // Label Parameter [Guard] / Action1;Action2;ActionN; // Keyword // Where the Label, Parameter. Guard, Actions and Keyword are // optional. String str = edgeLabel.getText(); e.setFullLabelKey(str); String[] guardAndAction = Edge.getGuardAndActions(str); String[] labelAndParameter = Edge.getLabelAndParameter(str); e.setGuardKey(guardAndAction[0]); e.setActionsKey(guardAndAction[1]); e.setLabelKey(labelAndParameter[0]); e.setParameterKey(labelAndParameter[1]); e.setWeightKey(Edge.getWeight(str)); e.setBlockedKey(AbstractElement.isBlocked(str)); Integer index = AbstractElement.getIndex(str); if (index != 0) { e.setIndexKey(index); } e.setReqTagKey(AbstractElement.getReqTags(str)); } e.setVisitedKey(0); logger.debug(" Added edge: '" + e.getLabelKey() + "', with id: " + e.getIndexKey()); // Extract any manual test instructions Iterator<Element> iterData = element.getDescendants(new ElementFilter("data")); while (iterData.hasNext() && e != null) { Object o2 = iterData.next(); if (o2 instanceof Element) { Element data = (Element) o2; if (!data.getContent().isEmpty() && data.getContent(0) != null) { String text = data.getContent(0).getValue().trim(); if (!text.isEmpty()) { logger.debug(" Data: '" + text + "'"); e.setManualInstructions(text); } } } } } } } catch (RuntimeException e) { throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage()); } catch (JDOMException e) { throw new RuntimeException("Could not parse file: '" + fileName + "'. " + e.getMessage()); } logger.debug("Finished parsing graph: " + graph); removeBlockedEntities(graph); logger.debug("Graph after removing BLOCKED entities: " + graph); return graph; }