void xmlImport(Element element) throws ImportDocumentException, PasswordIsTooWeakException { this.xmlImportUser(element.getChildren("user")); this.xmlImportDir(element.getChildren("dir")); this.xmlImportPlain(element.getChildren("plain")); this.xmlImportLink(element.getChildren("link")); this.xmlImportApp(element.getChildren("app")); }
/** * An LIUSBServer connection needs no extra information, so we reimplement the superclass method * to just write the necessary parts. * * @return Formatted element containing no attributes except the class name */ @Override public Element store(Object o) { getInstance(o); Element e = new Element("connection"); e.setAttribute("class", this.getClass().getName()); return e; }
private Element crearXMLUsuario(Usuario usuario) { Element element = new Element(ConstantesArchivosXML.PADRE); element.addContent(new Element(ConstantesArchivosXML.PADREID).setText(usuario.getId() + "")); element.addContent( new Element(ConstantesArchivosXML.PADREAPELLIDO).setText(usuario.getApellidos())); element.addContent( new Element(ConstantesArchivosXML.PADREPRIMERNOMBRE).setText(usuario.getPrimerNombre())); element.addContent( new Element(ConstantesArchivosXML.PADRESEGUNDONOMBRE).setText(usuario.getSegundoNombre())); element.addContent( new Element(ConstantesArchivosXML.PADRETIPOIDENTIFICACION) .setText(usuario.getTipo().getNombre())); element.addContent( new Element(ConstantesArchivosXML.PADRECODIGO).setText(usuario.getCodigoUsuarios())); element.addContent( new Element(ConstantesArchivosXML.PADRECORREO).setText(usuario.getCorreoElectronico())); element.addContent( new Element(ConstantesArchivosXML.PADREESCUELA) .setText(usuario.getEnteUniversitarios().getNombreEnteUniversitario())); element.addContent( new Element(ConstantesArchivosXML.PADREIDENTIFICACION) .setText(usuario.getDocumentoIdentidad() + "")); return element; }
public static List<String> getEventsNameByXml() { SAXBuilder sxb = new SAXBuilder(); Document document; List<String> listEvenementsString = null; // Object obj=null; try { document = sxb.build(new File(xmlDefaultPath)); // listevents=getEventsNameByDoc(document); Element racine = document.getRootElement(); // System.out.println("racine="+racine.getText()+"finracine"); List<Element> listEvenementsElement = racine.getChildren("evenement"); listEvenementsString = new ArrayList<String>(); for (Element evenementElement : listEvenementsElement) { listEvenementsString.add(evenementElement.getAttributeValue("nomEvent")); } // System.out.println("listofEventsJdomtaille ="+listEvenementsString.size()); // il faut valider le fichier xml avec la dtd // JDomOperations.validateJDOM(document); // afficheXml(document); } catch (Exception e) { // afficher un popup qui dit que le format du fichier xml entré n'est pas valide System.out.println("format xml non respecté"); System.out.println(e.getMessage()); } return listEvenementsString; }
private TeamResult readTeamResultXml( final List<MatchInfo> matchCache, final List<TeamInfo> teamCache, final List<Category> categories, final Element resultElm) throws Exception { /* example team result XML file content <result matchNumber="1" teamNumber="1" cat1="-1" cat2="-1" cat3="-1" ... > Specific notes about this team and this match </result> */ // Process <result> XML element int theMatchNumber = resultElm.getAttribute("matchNumber").getIntValue(); MatchInfo match = matchCache.stream().filter(m -> m.getMatchNumber() == theMatchNumber).findFirst().get(); int theTeamNumber = resultElm.getAttribute("teamNumber").getIntValue(); TeamInfo team = teamCache.stream().filter(t -> t.getTeamNumber() == theTeamNumber).findFirst().get(); Map<Category, Integer> scores = new HashMap<>(); for (Category c : categories) { String score = resultElm.getAttributeValue(c.getName()); if ((score != null) && (score.length() > 0)) { scores.put(c, Integer.valueOf(score)); } } TeamResult tr = new TeamResult(match, team, scores); tr.setNotes(resultElm.getTextNormalize()); return tr; }
public static Element stripAttributes(Element e) { e.setAttributes(null); for (Element child : e.getChildren()) { stripAttributes(child); // recurse } return e; }
NodeList getElementsByTagNameNS( final Parent xshadow, final String namespaceURI, final String localName) { if (localName == null) { return EMPTYLIST; } if (namespaceURI == null) { return EMPTYLIST; } final boolean alluri = "*".equals(namespaceURI); final boolean allname = "*".equals(localName); final ArrayList<JElement> enodes = new ArrayList<JElement>(); if (xshadow != null) { final Iterator<org.jdom2.Element> it = xshadow.getDescendants(Filters.element()); org.jdom2.Element e = null; if (xshadow instanceof org.jdom2.Element) { e = (org.jdom2.Element) xshadow; } else { if (it.hasNext()) { e = it.next(); } } while (e != null) { if ((allname || localName.equals(e.getName())) && (alluri || namespaceURI.equals(e.getNamespaceURI()))) { enodes.add(find(e)); } e = it.hasNext() ? it.next() : null; } } return new JNodeList(enodes); }
static BlockOrder loadBlockOrder(Element elem) { OBlock block = null; List<Element> blocks = elem.getChildren("block"); if (blocks.size() > 1) log.error("More than one block present: " + blocks.size()); if (blocks.size() > 0) { // sensor String name = blocks.get(0).getAttribute("systemName").getValue(); block = InstanceManager.getDefault(jmri.jmrit.logix.OBlockManager.class).provideOBlock(name); if (block == null) { log.error("Unknown Block \"" + name + "\" is null in BlockOrder."); return null; } if (log.isDebugEnabled()) log.debug("Load Block " + name + "."); } else { log.error("Null BlockOrder element"); return null; } Attribute attr = elem.getAttribute("pathName"); String pathName = null; if (attr != null) pathName = attr.getValue(); attr = elem.getAttribute("entryName"); String entryName = null; if (attr != null) entryName = attr.getValue(); attr = elem.getAttribute("exitName"); String exitName = null; if (attr != null) exitName = attr.getValue(); return new BlockOrder(block, pathName, entryName, exitName); }
/** * Get map info object associated with a zip * * @param zip zip file containing a configuration file * @return map info object if zip contains a map, otherwise null */ public static AutoRefMap getMapInfo(File zip) { // skip non-directories if (zip.isDirectory()) return null; Element worldConfig; try { worldConfig = getConfigFileData(zip); } catch (IOException e) { e.printStackTrace(); return null; } catch (JDOMException e) { e.printStackTrace(); return null; } String mapName = "??", version = "1.0"; Element meta = worldConfig.getChild("meta"); if (meta != null) { mapName = AutoRefMatch.normalizeMapName(meta.getChildText("name")); version = meta.getChildText("version"); } try { return new AutoRefMap(mapName, version, zip); } catch (IOException e) { e.printStackTrace(); return null; } }
/** * trace part_of relations of structid to get all its parent structures, separated by , in order * * <p>TODO treat "in|on" as part_of? probably not * * @param root * @param xpath : "//relation[@name='part_of'][@from='"+structid+"']" * @count number of rounds in the iteration * @return ,-separated organs from part to whole */ private String getPartOfChain(Document document, Element description, Element from, int depth) { String chain = ""; List<Element> statements = description.getChildren("statement"); // check relations for evidence for (Element statement : statements) { List<Element> relations = statement.getChildren("relation"); for (Element relation : relations) { String relationFrom = relation.getAttributeValue("from"); String relationTo = relation.getAttributeValue("to"); if (relationFrom != null && relationFrom.equals(from.getAttributeValue("id")) && relation.getAttributeValue("name").matches("part_of") && relationTo != null) { Element to = getBiologicalEntityWithId(document, relationTo); if (to != null) { chain += to.getAttributeValue("name") + ","; if (depth < 3) { chain += getPartOfChain(document, description, to, ++depth); return chain.replaceFirst(",$", ""); } } } } } return chain.replaceFirst(",$", ""); }
private String getParentOrgan( Document document, Element description, Element parentStructure, String parentOfParentStructure) { // check for 'part_of' relation on parentstructure String partOfChain = getPartOfChain(document, description, parentStructure, 0) .replace(" of ", ",") .trim(); // part of organ of organ if (!partOfChain.isEmpty()) { // use explicit part_of parentOfParentStructure = partOfChain; } // add constraint organ to parentorgan list String parentStructureConstraint = parentStructure.getAttributeValue("constraint"); if (parentStructureConstraint != null) { if (characterKnowledgeBase.isEntityStructuralContraint(parentStructureConstraint)) { // parentorgan = constraint; //use the constraint of parentstruct as parentorgan, e.g. leaf // blade ..., petiole ..., vein .... parentOfParentStructure = parentStructureConstraint + "," + parentOfParentStructure; // blade, leaf } } // add name organ to parentorgan list // parentorgan = parentofparentstructure+" "+parentstruct.getAttributeValue("name");//leaf blade return parentStructure.getAttributeValue("name") + "," + parentOfParentStructure; // blade, leaf }
private void normalizeUnicode(final Element ancestor, final Normalizer.Form form) { assert ancestor != null && form != null; final List<Text> texts = new ArrayList<Text>(); final ContentFilter textFilter = new ContentFilter(ContentFilter.TEXT); for (Content text : ancestor.getContent(textFilter)) { texts.add((Text) text); } for (Element element : ancestor.getDescendants(new ElementFilter())) { for (Content text : element.getContent(textFilter)) { texts.add((Text) text); } } for (Text text : texts) { if (Normalizer.isNormalized(text.getText(), form)) { continue; } final String normalizedString = Normalizer.normalize(text.getText(), form); LOGGER.log( Level.FINE, "Text ''{0}'' normalized to ''{1}''", new Object[] {text.getText(), normalizedString}); text.setText(normalizedString); assert Normalizer.isNormalized(text.getText(), form); } }
public Element toXML() { Element result = new Element("timer"); XMLUtil.createElement("title", getTitle(), result); XMLUtil.createElement("started", started == null ? "" : started.toString(), result); XMLUtil.createElement("total", period.toString(), result); XMLUtil.createElement("speed", update_speed, result); XMLUtil.createElement("x", getX(), result); XMLUtil.createElement("y", getY(), result); XMLUtil.createElement("width", getWidth(), result); XMLUtil.createElement("height", getHeight(), result); XMLUtil.createElement( "foreground", String.format("%08x", total.getForeground().getRGB()), result); XMLUtil.createElement( "background", String.format("%08x", panel.getBackground().getRGB()), result); XMLUtil.createElement("visible", isVisible(), result); Element times = new Element("times"); for (TimeSpan ts : this.times) { times.addContent(ts.toXML()); } result.addContent(times); return result; }
@Override public boolean applyChange(MavenProject project, Element root, String eol) throws ProjectRewriteException { boolean modified = false; if (project.hasParent()) { Namespace ns = getNamespaceOrNull(root); Element parentVersionElement = root.getChild("parent", ns).getChild("version", ns); MavenProject parent = project.getParent(); String parentId = ArtifactUtils.versionlessKey(parent.getGroupId(), parent.getArtifactId()); String parentVersion = releaseVersions.get(parentId); if (null == parentVersion && consistentProjectVersions && releaseVersions.size() > 0) { // Use any release version, as the project's versions are consistent/global parentVersion = releaseVersions.values().iterator().next(); } if (null == parentVersion) { if (parent.getVersion().equals(originalVersions.get(parentId))) { throw new ProjectRewriteException( "Release version for parent " + parent.getName() + " was not found"); } } else { workLog.add("setting parent version to '" + parentVersion + "'"); parentVersionElement.setText(parentVersion); modified = true; } } return modified; }
private String get(XMLProperty p) { final Element child = getElement(p); if (child == null) { return ""; } return child.getValue(); }
private List<Element> getBatchProcessPartElements() { Element batchProcessElement = document.getRootElement(); Filter<Element> filters = Filters.element(BATCH_PROCESS_PART); IteratorIterable<Element> batchProcessPartElement = batchProcessElement.getDescendants(filters); List<Element> batchProcessPartElements = IteratorUtils.toList(batchProcessPartElement); return batchProcessPartElements; }
public static String strip(String s) { Element e = stringToElement(s); if (e != null) { s = e.getText(); } return s; }
protected Element makeElement(String tag, Element... values) { Element element = new Element(tag); for (Element value : values) { element.addContent(value); } return element; }
NodeList getElementsByTagName(final Parent xshadow, final String tagname) { if (tagname == null) { return EMPTYLIST; } final ArrayList<JElement> enodes = new ArrayList<JElement>(); if (xshadow != null) { final Iterator<org.jdom2.Element> it = xshadow.getDescendants(Filters.element()); org.jdom2.Element e = null; if (xshadow instanceof org.jdom2.Element) { e = (org.jdom2.Element) xshadow; } else { if (it.hasNext()) { e = it.next(); } } while (e != null) { if ("*".equals(tagname) || tagname.equals(e.getQualifiedName())) { enodes.add(find(e)); } e = it.hasNext() ? it.next() : null; } } return new JNodeList(enodes); }
public TableConfig readConfigXML( String fileLocation, FeatureType wantFeatureType, NetcdfDataset ds, Formatter errlog) throws IOException { org.jdom2.Document doc; try { SAXBuilder builder = new SAXBuilder(false); if (debugURL) System.out.println(" PointConfig URL = <" + fileLocation + ">"); doc = builder.build(fileLocation); } catch (JDOMException e) { throw new IOException(e.getMessage()); } if (debugXML) System.out.println(" SAXBuilder done"); if (showParsedXML) { XMLOutputter xmlOut = new XMLOutputter(); System.out.println( "*** PointConfig/showParsedXML = \n" + xmlOut.outputString(doc) + "\n*******"); } Element configElem = doc.getRootElement(); String featureType = configElem.getAttributeValue("featureType"); Element tableElem = configElem.getChild("table"); TableConfig tc = parseTableConfig(ds, tableElem, null); tc.featureType = FeatureType.valueOf(featureType); return tc; }
/** * Execute abuse log request. * * @param properties Properties defining request. * @param list List to be filled with abuse logs. * @return True if request should be continued. * @throws APIException */ @Override public boolean executeAbuseLog(Map<String, String> properties, List<Page> list) throws APIException { try { Element root = getRoot(properties, ApiRequest.MAX_ATTEMPTS); // Retrieve category members XPathExpression<Element> xpa = XPathFactory.instance().compile("/api/query/abuselog/item", Filters.element()); List<Element> results = xpa.evaluate(root); Iterator<Element> iter = results.iterator(); while (iter.hasNext()) { Element currentNode = iter.next(); String title = currentNode.getAttributeValue("title"); Page page = DataManager.getPage(getWiki(), title, null, null, null); list.add(page); } // Retrieve continue return false; // Not continuing /*return shouldContinue( root, "/api/query-continue/abuselog", properties);*/ } catch (JDOMException e) { log.error("Error loading abuse filters list", e); throw new APIException("Error parsing XML", e); } }
protected Element genCoverageOfferingBriefElem( String elemName, String covName, String covLabel, String covDescription, GridCoordSystem gridCoordSys) { // <CoverageOfferingBrief> Element briefElem = new Element(elemName, wcsNS); // <CoverageOfferingBrief>/gml:metaDataProperty [0..*] // <CoverageOfferingBrief>/gml:description [0..1] // <CoverageOfferingBrief>/gml:name [0..*] // <CoverageOfferingBrief>/metadataLink [0..*] // <CoverageOfferingBrief>/description [0..1] // <CoverageOfferingBrief>/name [1] // <CoverageOfferingBrief>/label [1] if (covDescription != null && !covDescription.equals("")) briefElem.addContent(new Element("description", wcsNS).addContent(covDescription)); briefElem.addContent(new Element("name", wcsNS).addContent(covName)); briefElem.addContent(new Element("label", wcsNS).addContent(covLabel)); // <CoverageOfferingBrief>/lonLatEnvelope [1] briefElem.addContent(genLonLatEnvelope(gridCoordSys)); // ToDo Add keywords capabilities. // <CoverageOfferingBrief>/keywords [0..*] /keywords [1..*] and /type [0..1] return briefElem; }
/** * {@inheritDoc} * * @author holdawscot */ @Override public void loadXML(Game game, Element objectElement) { super.loadXML(game, objectElement); this.deadlyWeapon = (Weapon) game.getItem(objectElement.getChildText("deadlyWeapon")); this.soundEffect = objectElement.getChildText("soundEffect"); this.killMessage = objectElement.getChildText("killMessage"); }
@Test public void testOutputEscapedMixedMultiText() { // this test has mixed content (text-type and not text type). // and, it has a multi-text-type at the end. Element root = new Element("root"); root.addContent(new Comment("Boo")); root.addContent(new Text(" xx ")); root.addContent(new Text("<emb>")); root.addContent(new Text(" xx ")); FormatSetup fs = new FormatSetup() { @Override public void setup(Format fmt) { fmt.setExpandEmptyElements(true); } }; checkOutput( root, fs, "<root><!--Boo--> xx <emb> xx </root>", "<root><!--Boo-->xx <emb> xx</root>", "<root>\n <!--Boo-->\n xx <emb> xx\n</root>", "<root>\n <!--Boo-->\n xx <emb> xx\n</root>", "<root>\n <!--Boo-->\n xx <emb> xx \n</root>"); }
public Element serialize() { Element element = new Element("listener"); element.setAttribute("type", "sacn"); element.setAttribute("universe", universe + ""); element.setAttribute("listenAdapter", listenAdapter); return element; }
@Test public void testOutputElementCDATA() { String txt = "<root><![CDATA[xx]]></root>"; Element root = new Element("root"); root.addContent(new CDATA("xx")); checkOutput(root, txt, txt, txt, txt, txt); }
private Element crearEstructuraXML() { Element historialNotas = new Element(ConstantesArchivosXML.SUPERPADRE); Query q = entityManager.createQuery(ConsultasJpql.HISTORIAL_NOTAS_ESTUDIANTES); @SuppressWarnings("unchecked") List<Usuario> usuarios = (List<Usuario>) q.getResultList(); for (Usuario usuario : usuarios) { Element usuarioXML = crearXMLUsuario(usuario); Query q2 = entityManager.createQuery(ConsultasJpql.HISTORIAL_NOTAS); q2.setParameter("parametro", usuario.getId()); @SuppressWarnings("unchecked") List<HistorialNotas> notasCurso = (List<HistorialNotas>) q2.getResultList(); for (HistorialNotas curso : notasCurso) { Element cursoXML = crearXMLCurso( curso.getGrupoCurso().getCursoGrupo(), curso.getNota(), curso.getGrupoCurso().getIdGrupo(), curso.getGrupoCurso().getSemestre()); usuarioXML.addContent(cursoXML); } historialNotas.addContent(usuarioXML); } return historialNotas; }
@Test public void testOutputElementMultiMostWhiteExpandEmpty() { // this test has mixed content (text-type and not text type). // and, it has a multi-text-type at the end. Element root = new Element("root"); root.addContent(new CDATA(" ")); root.addContent(new Text(" ")); root.addContent(new Text(" ")); root.addContent(new Text("")); root.addContent(new Text(" ")); root.addContent(new Text(" \n \n ")); root.addContent(new Comment("Boo")); root.addContent(new Text(" \t ")); root.addContent(new Text(" ")); FormatSetup fs = new FormatSetup() { @Override public void setup(Format fmt) { fmt.setExpandEmptyElements(true); } }; checkOutput( root, fs, "<root><![CDATA[ ]]> \n \n <!--Boo--> \t </root>", "<root><!--Boo--></root>", "<root>\n <!--Boo-->\n</root>", "<root>\n <!--Boo-->\n</root>", "<root>\n <!--Boo-->\n</root>"); }
private void setData() { try { Document doc = builder.build(prefFile); Element rootNode = doc.getRootElement(); Element RWDir = new Element("RWDir"); rootNode.getChild("firstLoad").setText("no"); RWDir.setText(RWDIRECTORY.getAbsolutePath()); rootNode.addContent(RWDir); XMLOutputter xmlOutput = new XMLOutputter(); FileWriter fw = new FileWriter(prefFile); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, fw); fw.close(); } catch (IOException io) { io.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } }
static void filterMarkerInElement(List<Element> eltList, Map<String, Object> parameterMap) { final Pattern patternMarker = Pattern.compile("\\$\\{([^}]+)\\}"); // matching pattern is ${..} for (Element elt : eltList) { String elementValue = elt.getText(); if (elementValue == null) { continue; } Matcher matcher = patternMarker.matcher(elementValue); while (matcher.find()) { String marker = matcher.group(0); // full pattern matched ${..} String markerName = matcher.group(1); // get only text between curly braces String parameterValue = ServletUtil.getFirstParameter(parameterMap.get(markerName)); if (parameterValue != null) { elementValue = elementValue.replace(marker, parameterValue); elt.setText(elementValue); } else { logger.warn( "Found marker \"" + marker + "\" with NO matching parameter in Element <" + elt.getName() + ">"); } } } }