/** 打开查询结果 */ public static String[] openQuery(Hashtable params) { JParamObject PO = new JParamObject(); for (Enumeration e = params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); String val = (String) params.get(key); PO.SetValueByParamName(key, val); } String[] queryResult = new String[2]; JResponseObject RO = (JResponseObject) JActiveDComDM.AbstractDataActiveFramework.InvokeObjectMethod( "DataReport", "OpenQuery", PO, ""); String XMLStr = (String) RO.ResponseObject; if (RO != null && RO.ResponseObject != null) { XMLStr = (String) RO.ResponseObject; JXMLBaseObject XMLObj = new JXMLBaseObject(XMLStr); Element queryElmt = XMLObj.GetElementByName("Query"); // 格式 queryResult[0] = queryElmt.getAttributeValue("QueryFormat"); // 数据 queryResult[0] = queryElmt.getAttributeValue("QueryData"); } return queryResult; }
public boolean load() { try { if (new File(FILE_PATH).exists()) { FileInputStream FIS = new FileInputStream(FILE_PATH); JXMLBaseObject cobjXmlObj = new JXMLBaseObject(); cobjXmlObj.InitXMLStream(FIS); FIS.close(); Vector exps = new Vector(); Element rootElmt = cobjXmlObj.GetElementByName(JCStoreTableModel.ROOT_NAME); for (Iterator i = rootElmt.getChildren().iterator(); i.hasNext(); ) { Element crtElmt = (Element) i.next(); JCExpression exp = new JCExpression(); exp.mId = crtElmt.getAttributeValue("id", ""); exp.mName = crtElmt.getAttributeValue("name", ""); exp.mShowValue = crtElmt.getAttributeValue("show", ""); exp.mStoreValue = crtElmt.getAttributeValue("store", ""); exps.add(exp); } if (mModel != null) { mModel.setExpression(exps); } } } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public ParseDoc(Object xmlFile, String rootId, TreeMap prevIdMap) { SAXBuilder saxBuilder = new SAXBuilder(); try { if (xmlFile instanceof String) { document = saxBuilder.build((String) xmlFile); } else if (xmlFile instanceof URL) { document = saxBuilder.build((URL) xmlFile); } root = ParseUtils.parseRoot(document, rootId); objects = new TreeMap(); // Build description string (but not for the snippets.xml file) if (xmlFile instanceof String) { List authorL = root.getChildren("author"); String author = "<unknown>"; if (root.getAttributeValue("name") != null) { author = root.getAttributeValue("name"); } else if (authorL.size() > 0) { author = ((Element) authorL.get(0)).getValue(); } String description = "from file " + xmlFile.toString() + " (author: " + author + ") on " + new Date().toString(); HasIdentifiers.addGlobalIdentifier("_description_", description); } // Get all macro definitions, and remove them from document TreeMap macroMap = ParseUtils.getMacroDefs(root); // Process all macro expansions; replace macro expansion request with result ParseUtils.expandMacros(root, macroMap); // Get all elements in document, and assign identifiers to them; idMap = ParseUtils.parseId(root, prevIdMap); // Rewriting done; output debug XML code if (root.getAttributeValue("debug") != null) { XMLOutputter outputter = new XMLOutputter(); FileOutputStream fos = new FileOutputStream(xmlFile + ".debug"); outputter.output(document, fos); fos.close(); } } catch (JDOMException e) { // indicates a well-formedness or other error throw new Error("JDOMException: " + e.getMessage()); } catch (IOException e) { // indicates an IO problem throw new Error("IOException: " + e.getMessage()); } }
public static void main(String[] args) { // TODO code application logic here ouvrirDoc(); List<Element> listRDF = racine.getChildren("rdf"); nbRDF = listRDF.size(); initMatrices(); int i = 0; int j; for (Iterator iRDF = listRDF.iterator(); iRDF.hasNext(); i++) { Element curRDF1 = (Element) iRDF.next(); urls.add(curRDF1.getAttributeValue("url")); j = 0; for (Iterator jRDF = listRDF.iterator(); jRDF.hasNext(); j++) { Element curRDF2 = (Element) jRDF.next(); if (i > j) { comparerRDF(curRDF1, i, curRDF2, j, args[0]); } } } diviserMatrices(); afficherMatrice(mat, nbRDF); genererDotSource(Float.parseFloat(args[1])); EcritureGrapheDansTxt.ecrireTxtFile(nbRDF, urls, mat); }
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; }
/** Reads the XML data and create the data */ public void readDOMDataElement(Element element, IDataSets datasets) { // start with source data for (Object child : CodeFragment.getDataElementsOfType(CodeFragment.TYPE.SOURCE, element)) { Element code = (Element) child; try { collectSourceDataFromDOM(code, datasets); } catch (Exception e) { e.printStackTrace(); Util.errorMessage( "Failed to load source " + code.getAttributeValue("name") + ", error " + e.getMessage()); } } // process the data for (Object child : CodeFragment.getDataElementsOfType(CodeFragment.TYPE.GENERATED, element)) { Element code = (Element) child; try { processDataFromDOM(code, datasets); } catch (Exception e) { e.printStackTrace(); Util.errorMessage("Failed to run process " + e.getMessage()); } } }
public static HMM parseHMM(Element hmmelt, TreeMap idMap, TreeMap objects) { HMM hmm = new HMM(hmmelt, idMap, objects); hmm.analyze(objects); objects.put(hmmelt.getAttributeValue("id"), hmm); return hmm; }
private void load_snap_from_xml(Element snap, StructureCollection structs, LinkedList tempList) throws VisualizerLoadException { Iterator iterator = snap.getChildren().iterator(); if (!iterator.hasNext()) throw new VisualizerLoadException("Ran out of elements"); structs.loadTitle((Element) (iterator.next()), tempList, this); structs.calcDimsAndStartPts(tempList, this); if (!iterator.hasNext()) return; Element child = (Element) iterator.next(); if (child.getName().compareTo("doc_url") == 0) { // load the doc_url add_a_documentation_URL(child.getText().trim()); if (!iterator.hasNext()) return; child = (Element) iterator.next(); } if (child.getName().compareTo("pseudocode_url") == 0) { // load the psuedocode_url add_a_pseudocode_URL(child.getText().trim()); if (!iterator.hasNext()) return; child = (Element) iterator.next(); } if (child.getName().compareTo("audio_text") == 0) { // load the psuedocode_url add_audio_text(child.getText().trim()); if (!iterator.hasNext()) return; child = (Element) iterator.next(); } // create & load the individual structures, hooking them into the StructureCollection. // linespernode : calculate it at end of loadStructure call while (child.getName().compareTo("question_ref") != 0) { StructureType child_struct = assignStructureType(child); child_struct.loadStructure(child, tempList, this); structs.addChild(child_struct); if (!iterator.hasNext()) return; child = (Element) iterator.next(); } if (child.getName().compareTo("question_ref") == 0) { // set up question ref add_a_question_xml(child.getAttributeValue("ref")); } else // should never happen throw new VisualizerLoadException( "Expected question_ref element, but found " + child.getName()); if (iterator.hasNext()) { child = (Element) iterator.next(); throw new VisualizerLoadException( "Found " + child.getName() + " when expecting end of snap."); } } // load_snap_from_xml
private QueryResult gatherResultInfoForSelectQuery( String queryString, int queryNr, boolean sorted, Document doc, String[] rows) { Element root = doc.getRootElement(); // Get head information Element child = root.getChild("head", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); // Get result rows (<head>) List headChildren = child.getChildren( "variable", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); Iterator it = headChildren.iterator(); ArrayList<String> headList = new ArrayList<String>(); while (it.hasNext()) { headList.add(((Element) it.next()).getAttributeValue("name")); } List resultChildren = root.getChild("results", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")) .getChildren( "result", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); int nrResults = resultChildren.size(); QueryResult queryResult = new QueryResult(queryNr, queryString, nrResults, sorted, headList); it = resultChildren.iterator(); while (it.hasNext()) { Element resultElement = (Element) it.next(); String result = ""; // get the row values and paste it together to one String for (int i = 0; i < rows.length; i++) { List bindings = resultElement.getChildren( "binding", Namespace.getNamespace("http://www.w3.org/2005/sparql-results#")); String rowName = rows[i]; for (int j = 0; j < bindings.size(); j++) { Element binding = (Element) bindings.get(j); if (binding.getAttributeValue("name").equals(rowName)) if (result.equals("")) result += rowName + ": " + ((Element) binding.getChildren().get(0)).getTextNormalize(); else result += "\n" + rowName + ": " + ((Element) binding.getChildren().get(0)).getTextNormalize(); } } queryResult.addResult(result); } return queryResult; }
public void handleElement(Element e) { // create morph item if (e.getName().equals("entry")) { try { morphItems.add(new MorphItem(e)); } catch (RuntimeException exc) { System.err.println("Skipping morph item: " + e.getAttributeValue("word")); System.err.println(exc.toString()); } } // create macro item else if (e.getName().equals("macro")) { try { macroItems.add(new MacroItem(e)); } catch (RuntimeException exc) { System.err.println("Skipping macro item: " + e.getAttributeValue("name")); System.err.println(exc.toString()); } } }
/** * Método public static void leerArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite * leer un archivo XML que contiene los datos de los usuarios a través de jdom */ public static void leerArchivoXML(ListaUsuario listaDeUsuarios) { try { SAXBuilder builder = new SAXBuilder(); /* Se crea un documento nuevo con el nombre del archivo */ Document doc = builder.build(nombreArchivo); /* Se obtiene la raíz del archivo (la etiqueta inicial) */ Element raiz = doc.getRootElement(); /* Se puede obtener el atributo de la raíz (de la etiqueta) */ System.out.println(raiz.getAttributeValue("tipo")); /* Se obtienen todos los hijos cuya etiqueta esa "usuario" */ /* y se asignan esos hijos a un List */ List listaUsuarios = raiz.getChildren("usuario"); System.out.println("Formada por:" + listaUsuarios.size() + " usuarios"); System.out.println("------------------"); /* Se genera un iterador para recorrer el List que se generó */ Iterator i = listaUsuarios.iterator(); /* Se recorre el List */ while (i.hasNext()) { /* Se obtiene cada uno y se asigna a un objeto de tipo Element */ Element e = (Element) i.next(); /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas */ /* hijas de usuario, es decir, nombre, apellido y cargo */ Element nick = e.getChild("nick"); Element clave = e.getChild("clave"); Element nombre = e.getChild("nombre"); Element apellido = e.getChild("apellido"); Element fechanac = e.getChild("fechanac"); Element avatar = e.getChild("avatar"); /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */ Usuario elUsuario = new Usuario( nick.getText(), clave.getText(), nombre.getText(), apellido.getText(), fechanac.getText(), avatar.getText()); listaDeUsuarios.AgregarElemento(elUsuario); } } catch (Exception e) { e.printStackTrace(); } }
public String QuerySQL(String xmlStr) { String outstr = ""; Document doc; Element rootNode; String intStr = Basic.decode(xmlStr); try { Reader reader = new StringReader(intStr); SAXBuilder ss = new SAXBuilder(); doc = ss.build(reader); rootNode = doc.getRootElement(); String SqlStr = "select " + rootNode.getAttributeValue("fieldStr"); SqlStr = SqlStr + " from " + rootNode.getAttributeValue("tableStr"); SqlStr = SqlStr + " where (1=1) " + rootNode.getAttributeValue("whereStr"); DBTable datatable = new DBTable(); RecordSet rs = datatable.queryData(SqlStr); String[] fieldArr = rootNode.getAttributeValue("fieldStr").split(","); outstr = "<queryDataS success=\"true\">"; while (rs.next()) { outstr = outstr + "<queryData"; for (int i = 0; i < fieldArr.length; i++) { outstr = outstr + " " + fieldArr[i].trim() + "=\"" + rs.getString(fieldArr[i].trim()) + "\""; } outstr = outstr + "/>"; } outstr = outstr + "</queryDataS>"; } catch (JDOMException ex) { outstr = "<queryDataS success=false>"; outstr = outstr + ex.getMessage() + "</queryDataS>"; } return Basic.encode(outstr); }
public void addVariables(Element inRoot) throws org.jdom2.DataConversionException { Element vs = inRoot.getChild("decoder").getChild("variables"); Element segment = new Element("segment"); segment.setAttribute("space", "253"); root.addContent(segment); Iterator it = vs.getDescendants(); while (it.hasNext()) { Object o = it.next(); if (o instanceof Element) { Element e = (Element) o; if (e.getName().equals("variable")) { // get common attributes String comment = e.getAttributeValue("comment"); for (Object oc : e.getChildren("comment")) { Element ec = (Element) oc; if (ec.getAttributeValue("lang", "xml").equals("")) comment = ec.getText(); } String name = e.getAttributeValue("label"); if (name.equals("")) name = e.getAttributeValue("item"); for (Object on : e.getChildren("label")) { Element en = (Element) on; if (en.getAttributeValue("lang", "xml").equals("")) name = en.getText(); } long cv = e.getAttribute("CV").getIntValue(); // find subtype and process Element type; type = e.getChild("decVal"); if (type != null) { segment.addContent(handleDecVal(type, cv, name, comment, e.getAttributeValue("mask"))); continue; } type = e.getChild("enumVal"); if (type != null) { segment.addContent(handleEnumVal(type, cv, name, comment, e.getAttributeValue("mask"))); continue; } type = e.getChild("shortAddressVal"); if (type != null) { segment.addContent(handleShortAddressVal(type, cv, name, comment)); continue; } type = e.getChild("longAddressVal"); if (type != null) { segment.addContent(handleLongAddressVal(type, cv, name, comment)); continue; } } } } }
public Element handleEnumVal(Element type, long cv, String name, String comment, String mask) throws org.jdom2.DataConversionException { Element r; if (mask != null && !mask.equals("")) { r = new Element("bit"); r.setAttribute("size", "8"); r.setAttribute("mask", maskToInt(mask)); } else { r = new Element("int"); } r.setAttribute("origin", "" + (4278190080L + cv)); r.addContent(new Element("name").addContent(name)); if (comment != null && !comment.equals("")) r.addContent(new Element("description").addContent(comment)); Element map = new Element("map"); int counter = 0; r.addContent(map); for (Object c : type.getChildren("enumChoice")) { Element choice = (Element) c; if (choice.getAttribute("value") != null) { counter = choice.getAttribute("value").getIntValue(); } String cname = choice.getAttributeValue("choice"); for (Object oc : choice.getChildren("choice")) { Element ec = (Element) oc; if (ec.getAttributeValue("lang", "xml").equals("")) cname = ec.getText(); } Element relation = new Element("relation"); map.addContent(relation); relation.addContent(new Element("property").addContent("" + counter)); relation.addContent(new Element("value").addContent(cname)); counter++; } return r; }
private static boolean comparerObjet(Element triplet1, Element triplet2) { Element uri1 = triplet1.getChild("uri"); Element uri2 = triplet2.getChild("uri"); Element literal1 = triplet1.getChild("literal"); Element literal2 = triplet1.getChild("literal"); if ((uri1 == null && uri2 != null) || (uri2 == null && uri1 != null)) { return false; } else if (uri1 != null && uri2 != null) { String uri1text = uri1.getText(); String uri2text = uri2.getText(); if (!(uri1text.equals(uri2text))) { return false; } } else if (literal1 != null && literal2 != null) { String lang1 = literal1.getAttributeValue("lang", Namespace.XML_NAMESPACE); String lang2 = literal2.getAttributeValue("lang", Namespace.XML_NAMESPACE); String datatype1 = literal1.getAttributeValue("datatype"); String datatype2 = literal2.getAttributeValue("datatype"); String literal1Text = literal1.getText(); String literal2Text = literal2.getText(); if (lang1 != null && lang2 != null) { if (!lang1.equals(lang2)) { return false; } else if (!literal1Text.equals(literal2Text)) { return false; } } else if (datatype1 != null && datatype2 != null) { if (!datatype1.equals(datatype2)) { return false; } else if (!literal1Text.equals(literal2Text)) { return false; } } } return true; }
@Override public Collection<Task> loadTasks() { Collection<Task> loadedTasks = null; try { String path = config.getFileName(); if (path == null) { log.error("Cannot get path to taskFile. Will halt."); throw new BadConfigException("Cannot get path to taskFile. Will halt."); } if (new File(path).exists()) { Boolean valid = Tools.valXML(path); if (valid) { try { SAXBuilder builder = new SAXBuilder(); doc = builder.build(config.getFileName()); Iterator it = doc.getRootElement().getChildren("task").iterator(); loadedTasks = new TreeSet<Task>(taskComparator); while (it.hasNext()) { Element element = (Element) it.next(); String id = element.getAttributeValue("id"); String name = element.getChildText("name"); String description = element.getChildText("description"); String date = element.getChildText("date"); Task task = new Task(id, name, description, sdf.parse(date)); loadedTasks.add(task); } } catch (JDOMException ex) { log.error("Error in loading tasks from xml ", ex); throw new IOException("Error in loading tasks from xml ", ex); } catch (ParseException ex) { log.error("Error in xml parsing."); throw new IOException("Error in xml parsing.", ex); } } else { log.info("XML File is not valid. Check it."); throw new InvalidFileException("XML File is not valid. Check it."); } } else { saveTask(null); } } catch (Exception ex) { log.error("Tasks wasn't loaded, IO or XML errors occured", ex); throw new InternalControllerException("Tasks wasn't loaded, IO or XML errors occured", ex); } return loadedTasks; }
public void parseCode() { // Parse all <code> and <parameter> elements List codeList = ParseUtils.parseDescendants(root, "code", idMap); Iterator i = codeList.iterator(); while (i.hasNext()) { Element codeElt = (Element) i.next(); String codeId = codeElt.getAttributeValue("id"); if (objects.containsKey(codeId)) { System.out.println("Note: Shadowing definition of <code id=\"" + codeId + "\">"); } objects.put(codeId, new Code(codeElt, idMap)); } }
private static void writeElement(XMLStreamWriter xtw, Element element) throws XMLStreamException { xtw.writeStartElement(element.getName()); for (String attributeName : element.getAttributeNames()) { xtw.writeAttribute(attributeName, element.getAttributeValue(attributeName)); } if (element.hasText()) { xtw.writeCharacters(element.getText()); } else { for (Element child : element.getChildren()) { writeElement(xtw, child); } } xtw.writeEndElement(); }
// get licensing features, with appropriate defaults @SuppressWarnings("unchecked") private void loadLicensingFeatures(Element licensingElt) { List<LicensingFeature> licensingFeats = new ArrayList<LicensingFeature>(); boolean containsLexFeat = false; if (licensingElt != null) { for (Iterator<Element> it = licensingElt.getChildren("feat").iterator(); it.hasNext(); ) { Element featElt = it.next(); String attr = featElt.getAttributeValue("attr"); if (attr.equals("lex")) containsLexFeat = true; String val = featElt.getAttributeValue("val"); List<String> alsoLicensedBy = null; String alsoVals = featElt.getAttributeValue("also-licensed-by"); if (alsoVals != null) { alsoLicensedBy = Arrays.asList(alsoVals.split("\\s+")); } boolean licenseEmptyCats = true; boolean licenseMarkedCats = false; boolean instantiate = true; byte loc = LicensingFeature.BOTH; String lmc = featElt.getAttributeValue("license-marked-cats"); if (lmc != null) { licenseMarkedCats = Boolean.valueOf(lmc).booleanValue(); // change defaults licenseEmptyCats = false; loc = LicensingFeature.TARGET_ONLY; instantiate = false; } String lec = featElt.getAttributeValue("license-empty-cats"); if (lec != null) { licenseEmptyCats = Boolean.valueOf(lec).booleanValue(); } String inst = featElt.getAttributeValue("instantiate"); if (inst != null) { instantiate = Boolean.valueOf(inst).booleanValue(); } String locStr = featElt.getAttributeValue("location"); if (locStr != null) { if (locStr.equals("target-only")) loc = LicensingFeature.TARGET_ONLY; if (locStr.equals("args-only")) loc = LicensingFeature.ARGS_ONLY; if (locStr.equals("both")) loc = LicensingFeature.BOTH; } licensingFeats.add( new LicensingFeature( attr, val, alsoLicensedBy, licenseEmptyCats, licenseMarkedCats, instantiate, loc)); } } if (!containsLexFeat) { licensingFeats.add(LicensingFeature.defaultLexFeature); } _licensingFeatures = new LicensingFeature[licensingFeats.size()]; licensingFeats.toArray(_licensingFeatures); }
/** Make a keybinding out of an XML element */ public static KeyBinding readXML(Element e) { try { String plugin = e.getAttributeValue("plugin"); String desc = e.getAttributeValue("desc"); KeyBinding b = new KeyBinding(plugin, desc, null); for (Object neo : e.getChildren()) { Element ne = (Element) neo; if (ne.getName().equals("char")) b.types.add(new TypeChar(ne.getAttributeValue("char").charAt(0))); else if (ne.getName().equals("keycode")) b.types.add( new TypeKeycode( ne.getAttribute("keyCode").getIntValue(), ne.getAttribute("modifier").getIntValue())); else if (ne.getName().equals("jinput")) b.types.add( new TypeJInput( ne.getAttributeValue("ident"), ne.getAttribute("value").getFloatValue())); } // backwards compatibility if (e.getAttribute("key") != null) { TypeChar kb = new TypeChar(e.getAttributeValue("key").charAt(0)); b.types.add(kb); } else if (e.getAttribute("keyCode") != null) { TypeKeycode kb = new TypeKeycode( e.getAttribute("keyCode").getIntValue(), e.getAttribute("modifier").getIntValue()); b.types.add(kb); } return b; } catch (DataConversionException e1) { e1.printStackTrace(); return null; } }
// get relation sort order, or use defaults private void loadRelationSortOrder(Element relationSortingElt) { // use defaults if no order specified if (relationSortingElt == null) { for (int i = 0; i < defaultRelationSortOrder.length; i++) { _relationIndexMap.put(defaultRelationSortOrder[i], new Integer(i)); } return; } // otherwise load from 'order' attribute String orderAttr = relationSortingElt.getAttributeValue("order"); String[] relSortOrder = orderAttr.split("\\s+"); for (int i = 0; i < relSortOrder.length; i++) { _relationIndexMap.put(relSortOrder[i], new Integer(i)); } }
public void handleElement(Element e) { // create family if (e.getName().equals("family")) { try { lexicon.add(new Family(e)); } catch (RuntimeException exc) { System.err.println("Skipping family: " + e.getAttributeValue("name")); System.err.println(exc.toString()); } } // save distributive attributes else if (e.getName().equals("distributive-features")) distrElt = e; // save licensing features else if (e.getName().equals("licensing-features")) licensingElt = e; // save relation sort order else if (e.getName().equals("relation-sorting")) relationSortingElt = e; }
public static List<String> getEventsNameByDoc(Document pdocument) { Element racine = pdocument.getRootElement(); List<Element> listEvenementsElement = racine.getChildren("evenement"); List<String> listEvenementsString = new ArrayList<String>(); for (Element evenementElement : listEvenementsElement) { listEvenementsString.add(evenementElement.getAttributeValue("nomEvent")); } // //On crée un Iterator sur notre liste // Iterator i = listEvenementsElement.iterator(); // while (i.hasNext()){ // Element evenementElement = (Element)i.next(); // //On affiche le nom de l'élément courant // System.out.println(courant.getChild("nom").getText()); // } return listEvenementsString; }
// Empieza La Carga de la Partida public static void leerArchivoXML(ListaPartida listaDePartidas) { try { SAXBuilder builder = new SAXBuilder(); /* Se crea un documento nuevo con el nombre del archivo */ Document doc = builder.build(nombreArchivoPartida); /* Se obtiene la raíz del archivo (la etiqueta inicial) */ Element raiz = doc.getRootElement(); /* Se puede obtener el atributo de la raíz (de la etiqueta) */ System.out.println(raiz.getAttributeValue("tipo")); /* Se obtienen todos los hijos cuya etiqueta esa "usuario" */ /* y se asignan esos hijos a un List */ List listaPartida = raiz.getChildren("partida"); System.out.println("Formada por:" + listaPartida.size() + " Partidas"); System.out.println("------------------"); /* Se genera un iterador para recorrer el List que se generó */ Iterator i = listaPartida.iterator(); /* Se recorre el List */ while (i.hasNext()) { /* Se obtiene cada uno y se asigna a un objeto de tipo Element */ Element e = (Element) i.next(); /* Se obtiene el nombre, apellido y cargo de cada una de las etiquetas */ /* hijas de usuario, es decir, nombre, apellido y cargo */ Element nick = e.getChild("Usuario"); Element ID = e.getChild("ID"); Element fechaactual = e.getChild("fechaacual"); Element fechainicio = e.getChild("fechainicio"); /* Se crea un nodo nuevo con la información y se agrega a la lista de usuarios */ Partida laPartida = new Partida( nick.getText(), ID.getContentSize(), fechaactual.getText(), fechainicio.getText()); listaDePartidas.AgregarElemento(laPartida); } } catch (Exception e) { e.printStackTrace(); } }
public void addHeader(Element inRoot) { Element id = new Element("identification"); String mfg = inRoot.getChild("decoder").getChild("family").getAttributeValue("mfg"); id.addContent(new Element("manufacturer").addContent(mfg)); String name = inRoot.getChild("decoder").getChild("family").getAttributeValue("name"); id.addContent(new Element("model").addContent(name)); id.addContent(new Element("hardwareVersion")); id.addContent(new Element("softwareVersion")); // add models in map, if any Element map = new Element("map"); for (Object o : inRoot.getChild("decoder").getChild("family").getChildren("model")) { Element e = (Element) o; Element relation = new Element("relation"); relation.addContent(new Element("property").addContent("Model")); relation.addContent(new Element("value").addContent(e.getAttributeValue("model"))); map.addContent(relation); } id.addContent(map); root.addContent(id); }
private StructureType assignStructureType(Element structure) throws VisualizerLoadException { String name = structure.getName().toLowerCase(); if (name.compareTo("graph") == 0) { if (structure.getAttributeValue("weighted").compareTo("true") == 0) return new Graph_Network("NETWORK"); else return new Graph_Network("GRAPH"); } else if (name.equals("array")) return new MD_Array(); else if (name.equals("no3darray")) return new No3darray(); else if (name.equals("linkedlist")) return new VisLinkedList(); else if (name.equals("no3dlinkedlist")) return new No3dLinkedList(); else if (name.equals("linkedlistnonull")) return new VisLinkedListNoNull(); else if (name.equals("bargraph")) return new BarScat("BAR"); else if (name.equals("scattergraph")) return new BarScat( "SCAT"); // not implemented in xml dtd, and does not have a load-from-xml method defined else if (name.equals("stack")) return new Stack(); else if (name.equals("queue")) return new Queue(); else if (name.equals("tree")) { if (structure.getChild("binary_node") != null) return new BinaryTree(); else return new GeneralTree(); } else if (name.equals("text")) return new TextStructure(); // if the XML element name is different from your structure's name, you can do something like // this: // else if( name.equalsIgnoreCase("node")) // return new Node(); else if (name.equals("legend")) return new LegendofColors(); else { // try dynamic typing try { return assignStructureType(name); } catch (Exception e) { throw new VisualizerLoadException( "Unable to instantiate class \"" + name + "\":\n" + e.getMessage()); } } }
private void collectSourceDataFromDOM(Element code, IDataSets dataset) throws Exception { // get code fragment CodeFragment.TYPE type = CodeFragment.TYPE.valueOf(code.getAttributeValue("type")); if (type == CodeFragment.TYPE.SOURCE) { String dataname = code.getAttributeValue("name"); String dataid = code.getAttributeValue("dataid"); // check import method and reader Element importelement = code.getChild(IImport.class.getName()); Element readerelement = code.getChild(IReader.class.getName()); // get URI String URI = importelement.getAttributeValue("URI"); String scheme = (new URI(URI)).getScheme(); // look for a suitable import method IImports allimports = WorkFlowManager.getInstance().getImports(); IImportMethod importmethod = allimports.findImport(scheme); if (importmethod == null) { Util.errorMessage("Could not find suitable import for scheme '" + scheme + "'"); return; } IImport method = importmethod.getImport(); method.setURI(URI); // get reader String readername = readerelement.getAttributeValue("name"); String format = readerelement.getAttributeValue("format"); String readertype = readerelement.getAttributeValue("datatype"); IReaders allreaders = WorkFlowManager.getInstance().getReaders(); IReader reader = allreaders.findReaderWithName(readername); if (reader == null) { Util.errorMessage("Could not find reader " + readername); return; } reader.setType(readertype); reader.setDataFormat(format); reader.setType(readertype); dataset.importDataContent(method, reader, dataname, dataid); } }
public String getDataTableXML(String xmlStr) { String outstr = ""; Document doc; Element rootNode, child; ConnectionManager cm = ConnectionManager.getInstance(); try { cm.get(); Reader reader = new StringReader(xmlStr); SAXBuilder ss = new SAXBuilder(); doc = ss.build(reader); rootNode = doc.getRootElement(); List list = rootNode.getChildren(); Element childRoot = (Element) list.get(0); DBGrid dbGrid = new DBGrid(); dbGrid.setGridID(childRoot.getAttributeValue("id")); dbGrid.setGridType(childRoot.getAttributeValue("gridType")); dbGrid.setfieldSQL(childRoot.getAttributeValue("SQLStr")); dbGrid.setfieldcn(childRoot.getAttributeValue("fieldCN")); dbGrid.setenumType(childRoot.getAttributeValue("enumType")); dbGrid.setvisible(childRoot.getAttributeValue("visible")); dbGrid.setfieldName(childRoot.getAttributeValue("fieldname")); dbGrid.setfieldWidth(childRoot.getAttributeValue("fieldwidth")); dbGrid.setfieldType(childRoot.getAttributeValue("fieldtype")); dbGrid.setfieldCheck(childRoot.getAttributeValue("fieldCheck")); dbGrid.setcountSQL(childRoot.getAttributeValue("countSQL")); dbGrid.setpagesize(Integer.parseInt(childRoot.getAttributeValue("pageSize"))); dbGrid.setAbsolutePage(Integer.parseInt(childRoot.getAttributeValue("AbsolutePage"))); dbGrid.setRecordCount(Integer.parseInt(childRoot.getAttributeValue("RecordCount"))); dbGrid.setCheck(childRoot.getAttributeValue("checkbl").toLowerCase().trim().equals("true")); dbGrid.setAlign(childRoot.getAttributeValue("tralign")); /* if (childRoot.getAttributeValue("bottomVisible").toLowerCase().equals("true")) dbGrid.setGridBottomVisible(true); else dbGrid.setGridBottomVisible(false); */ // zr if (childRoot.getAttributeValue("bottomVisible").toLowerCase().equals("true")) { dbGrid.setGridBottomVisible(true); // dbGrid.setSumfield(childRoot.getAttributeValue("sumfield")); } else dbGrid.setGridBottomVisible(false); dbGrid.setWhereStr(Basic.decode(childRoot.getAttributeValue("whereStr"))); outstr = dbGrid.getEditDataTable(); // System.out.println(outstr); } catch (JDOMException ex) { System.out.print(ex.getMessage()); } finally { cm.release(); } return outstr; }
public String doExcelHou(String xmlStr, WritableWorkbook wwb) { String outstr = ""; Document doc; Element rootNode, child; // System.out.println(xmlStr); try { Reader reader = new StringReader(xmlStr); SAXBuilder ss = new SAXBuilder(); doc = ss.build(reader); rootNode = doc.getRootElement(); if (rootNode.getAttributeValue("type").equals("lp")) { return getloadspell(rootNode.getText()); } if (rootNode.getAttributeValue("type").equals("lm")) { return getLoadName(rootNode.getText()); } List list = rootNode.getChildren(); Element childRoot = (Element) list.get(0); String fieldTitle = childRoot.getAttributeValue("fieldTitle"); if (rootNode.getAttributeValue("type").equals("enum")) { String enumType = childRoot.getAttributeValue("enumType"); return getEnumType(enumType, fieldTitle); } if (rootNode.getAttributeValue("type").equals("sql")) { String SqlStr = childRoot.getAttributeValue("SqlStr"); DBTable datatable = new DBTable(); return datatable.getDropDownStr(SqlStr, fieldTitle); } if (rootNode.getAttributeValue("type").equals("excel")) { String SqlStr = childRoot.getAttributeValue("SQLStr"); // System.out.println(SqlStr); String whereStr = Basic.decode(childRoot.getAttributeValue("whereStr")); // System.out.println(whereStr); DBTable datatable = new DBTable(); return datatable.getExcel(SqlStr, whereStr); } // ! if (rootNode.getAttributeValue("type").equals("excelhou")) { String SqlStr = childRoot.getAttributeValue("SQLStr"); String fieldCN = childRoot.getAttributeValue("fieldCN"); String fieldType = childRoot.getAttributeValue("fieldType"); String fieldWidth = childRoot.getAttributeValue("fieldWidth"); String visible = childRoot.getAttributeValue("visible"); String enumType = childRoot.getAttributeValue("enumType"); String whereStr = Basic.decode(childRoot.getAttributeValue("whereStr")); DBTable datatable = new DBTable(); return datatable.writeExcel_new( wwb, SqlStr, whereStr, fieldCN, fieldType, fieldWidth, visible, enumType); } if (rootNode.getAttributeValue("type").equals("comboBox")) { String comboBoxID = childRoot.getAttributeValue("comboBoxID"); JOption jOption = new JOption(comboBoxID); String enumType = childRoot.getAttributeValue("enumType"); String titleStr = childRoot.getAttributeValue("titleStr"); String sqlStr = childRoot.getAttributeValue("sqlStr"); String defaultoption = childRoot.getAttributeValue("defaultOption"); String titleVisible = childRoot.getAttributeValue("titleVisible"); String keyVisible = childRoot.getAttributeValue("keyVisible"); if (defaultoption != null) { String[] options = defaultoption.split(",", -2); if (options.length == 2) { jOption.addOption(options[0], options[1]); } } if (titleVisible.toLowerCase().trim().equals("false")) jOption.setTitleVisible(false); if (keyVisible.toLowerCase().trim().equals("false")) jOption.setKeyVisible(false); jOption.setEnumType(enumType); jOption.setSQlStr(sqlStr); jOption.setTitleStr(titleStr); return jOption.getDropHtml(); } } catch (JDOMException ex) { System.out.print(ex.getMessage()); } return outstr; }
public static Relatorio parse(java.io.File checkStyleResultsFile, String classe, String programa) throws SQLException, ClassNotFoundException { conn = conectar(); if (!checkStyleResultsFile.exists()) { return null; } Relatorio relatorio = new Relatorio(); SAXBuilder builder = new SAXBuilder(); String sql5 = "select * from ferramenta where nome='pmd'"; Statement stmt = conn.createStatement(); ResultSet rs3 = stmt.executeQuery(sql5); /* Inserindo classe se não existir */ if (!rs3.next()) { String sql6 = "insert into ferramenta " + "(id," + "descricao, " + "linguagem, " + "nome," + "tipo," + "versao) " + "values (?,?,?,?,?,?)"; PreparedStatement stat3 = conn.prepareStatement(sql6); stat3.setString(1, "PM0006"); stat3.setString(2, ""); stat3.setString(3, "java"); stat3.setString(4, "pmd"); stat3.setString(5, "codigo fonte"); stat3.setString(6, ""); stat3.executeUpdate(); } try { Document document = builder.build(checkStyleResultsFile); Element rootNode = document.getRootElement(); List filesXml = rootNode.getChildren("file"); List<Arquivo> files = new ArrayList<Arquivo>(); for (int i = 0; i < filesXml.size(); i++) { Element fileNode = (Element) filesXml.get(i); String name = fileNode.getAttributeValue("name"); List errorsXml = fileNode.getChildren("violation"); List<Error> errors = new ArrayList<Error>(); for (int j = 0; j < errorsXml.size(); j++) { Element errorNode = (Element) errorsXml.get(j); String beginline = errorNode.getAttributeValue("beginline"); String endline = errorNode.getAttributeValue("endline"); String begincolumn = errorNode.getAttributeValue("begincolumn"); String endcolumn = errorNode.getAttributeValue("endcolumn"); String classe2 = errorNode.getAttributeValue("class"); String externalinfourl = errorNode.getAttributeValue("externalInfoUrl"); String rules = errorNode.getAttributeValue("rule"); String ruleset = errorNode.getAttributeValue("ruleset"); String priority = errorNode.getAttributeValue("priority"); String sql = "insert into warning" + "(tool, " + "nameprogram, " + "nameclass, " + "namemethod, " + "beginline, " + "endline," + "begincolumn, " + "endcolumn," + "typewarning," + "description," + "priority," + "externalinfourl," + "ruleset ) values (?,?,?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement pstm = conn.prepareStatement(sql); pstm.setString(1, "PM0006"); pstm.setString(2, programa); String aux = classe.replace("source-", ""); String aux3 = aux.replace("-", "."); String aux4 = aux3.replace(".java", ""); pstm.setString(3, aux4); pstm.setString(4, ""); pstm.setInt(5, Integer.parseInt(beginline)); pstm.setInt(6, Integer.parseInt(endline)); pstm.setInt(7, Integer.parseInt(begincolumn)); pstm.setInt(8, Integer.parseInt(endcolumn)); pstm.setString(9, rules); String aux2 = "" + errorNode.getValue(); File arquivo = new File("/home/vr/Dropbox/WarningsFix/tmp/buffer.txt"); FileWriter fw = new FileWriter(arquivo, true); BufferedWriter bw = new BufferedWriter(fw); bw.write(aux2); bw.close(); fw.close(); // faz a leitura do arquivo try { FileReader fr = new FileReader(arquivo); BufferedReader br = new BufferedReader(fr); // equanto houver mais linhas String linha; while ((linha = br.readLine()) != null) { // lê a proxima linha pstm.setString(10, linha); } br.close(); fr.close(); } catch (IOException ex) { ex.printStackTrace(); } arquivo.delete(); pstm.setInt(11, Integer.parseInt(priority)); pstm.setString(12, externalinfourl); pstm.setString(13, ruleset); pstm.executeUpdate(); System.out.println( " " + beginline + " " + endline + " " + begincolumn + " " + endcolumn + " " + classe2 + " " + programa + " " + externalinfourl + " " + priority + " " + ruleset + " " + rules); errors.add( new Error( beginline, endline, begincolumn, endcolumn, classe2, externalinfourl, priority, ruleset, rules)); } files.add(new Arquivo(name, errors)); } relatorio.setFiles(files); } catch (JDOMException e) { e.printStackTrace(); // To change body of catch statement use Arquivo | Settings | Arquivo // Templates. } catch (IOException e) { e.printStackTrace(); // To change body of catch statement use Arquivo | Settings | Arquivo // Templates. } desconectar(conn); return relatorio; }