List of usage examples for org.jdom2 Element getChildText
public String getChildText(final String cname)
From source file:uk.co.platosys.db.jdbc.DatabaseProperties.java
License:Open Source License
/** * creates a new database and returns a String with its name * @param masterDatabase//from w ww . j a v a 2s . c o m * @param newCredentials * @return * @throws PlatosysDBException */ public static String createDatabase(String masterDatabase, DatabaseCredentials newCredentials) throws PlatosysDBException { logger.log("checking database credentials etc"); //some checks: String databaseName = newCredentials.getName(); String databaseUser = newCredentials.getUsername(); String databaseURL = newCredentials.getUrl(); logger.log("into the next method"); Document configDoc = null; Element rootElement = null; try { File configDir = new File(UNIX_CONFIG_READ_DIR); File configFile = new File(configDir, CONFIG_FILE); SAXBuilder builder = new org.jdom2.input.SAXBuilder(); configDoc = builder.build(configFile); rootElement = configDoc.getRootElement(); List<Element> databases = rootElement.getChildren("database"); Iterator<Element> it = databases.iterator(); while (it.hasNext()) { Element databaseElement = (Element) it.next(); if (databaseElement.getAttributeValue("name").equals(masterDatabase)) { //check the database drivers match if (!(databaseElement.getChildText("databaseDriver").equals(newCredentials.getDriver()))) { throw new PlatosysDBException("Database driver class names do not match"); } //TODO: fix location checking /* * not doing database location checks. Not working, too much time to fix * for now. //check the URL matches; strip off the name suffix of the URL String masterURL = databaseElement.getChildText("databaseUrl"); logger.log("full masterURL is "+masterURL); int b = masterDatabase.length(); int a = masterURL.length(); logger.log("masterDatabase is "+masterDatabase); masterURL = masterURL.substring(0, a-b); logger.log("stripped masterURL is "+masterURL); logger.log("new dburl is "+databaseURL); a = databaseURL.length(); b = databaseName.length(); String newURL = databaseURL.substring(0, a-b); logger.log("newURL is"+newURL); if (!masterURL.equals(newURL)){ throw new PlatosysDBException("New database must match the master database location"); }*/ } if (databaseElement.getAttributeValue("name").equals(databaseName)) { throw new PlatosysDBException("Database name " + databaseName + " already exists"); } /* if (databaseElement.getChildText("databaseUser").equals(databaseUser)){ throw new PlatosysDBException("Database user "+databaseUser+" already exists"); }*/ } } catch (Exception x) { logger.log("problem doing createDB checks", x); throw new PlatosysDBException("Error doing create DB checks", x); } //connect to the master database and create new database and role Connection connection = ConnectionSource.getConnection(masterDatabase); try { Statement statement = connection.createStatement(); //not creating new role because it is the same one (see how we get the credentials). //arguably we should create a new role. So just creating database. //statement.execute("CREATE ROLE "+databaseUser+" WITH LOGIN PASSWORD "+newCredentials.getPassword()); statement.execute("CREATE DATABASE " + databaseName); } catch (Exception x) { logger.log("problem creating database", x); throw new PlatosysDBException("Failed to create new database: ", x); } try { connection.close(); } catch (Exception x) { } try { //write this to a file: logger.log(2, "writing info to a file"); File configDir = new File(UNIX_CONFIG_WRITE_DIR); File configFile = new File(configDir, CONFIG_FILE); Element databaseElement = new Element("database"); databaseElement.setAttribute("name", databaseName); databaseElement.setAttribute("status", "slave"); Element driverElement = new Element("databaseDriver"); driverElement.setText(newCredentials.getDriver()); databaseElement.addContent(driverElement); Element urlElement = new Element("databaseUrl"); urlElement.setText(newCredentials.getUrl()); databaseElement.addContent(urlElement); Element userElement = new Element("databaseUser"); userElement.setText(newCredentials.getUsername()); databaseElement.addContent(userElement); Element passwordElement = new Element("databasePassword"); passwordElement.setText(newCredentials.getPassword()); databaseElement.addContent(passwordElement); rootElement.addContent(databaseElement); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); FileWriter writer = new FileWriter(configFile); outputter.output(configDoc, writer); writer.close(); } catch (Exception x) { logger.log("problem writing database info to xml", x); throw new PlatosysDBException("problem writing new database configuration file ", x); } return newCredentials.getName(); }
From source file:UserInterface.MainJFrame.java
public void loadDataFromXML() throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder(); File employeeXMLFile = new File( "C:\\Users\\Ankit Bhayani\\Documents\\NetBeansProjects\\AEDFALL2015Assignment5\\data\\SalesEmployee.xml"); Document d1 = (Document) builder.build(employeeXMLFile); Element mrootNode = d1.getRootElement(); List list1 = mrootNode.getChildren("Employee"); for (int i = 0; i < list1.size(); i++) { Element node = (Element) list1.get(i); SalesPerson employee = business.getEmployeeDirectory().addEmployee(); employee.setFirstName(node.getChildText("fname")); employee.setLastName(node.getChildText("lname")); employee.setOrganization(node.getChildText("organization")); Person person = employee;/*from ww w . ja v a 2s.c o m*/ UserAccount ua = business.getUserDirectory().addUserAccount(); ua.setUserName(node.getChildText("uname")); ua.setPassword(node.getChildText("pwd")); ua.setPerson(person); ua.setRole(UserAccount.EMPLOYEE_ROLE); ua.setIsActive("Yes"); } File prodXMLFile = new File( "C:\\Users\\Ankit Bhayani\\Documents\\NetBeansProjects\\AEDFALL2015Assignment5\\data\\ProductList.xml"); Document d2 = (Document) builder.build(prodXMLFile); Element drootnode = d2.getRootElement(); List list = drootnode.getChildren("Product"); for (int j = 0; j < list.size(); j++) { Element nodes = (Element) list.get(j); Product product = business.getXeroxProductCatalog().addProduct(); product.setProdName(nodes.getChildText("prodName")); product.setProdDesc(nodes.getChildText("description")); product.setFloorPrice(Float.valueOf(nodes.getChildText("floorPrice"))); product.setTargetPrice(Float.valueOf(nodes.getChildText("targetPrice"))); product.setCeilingPrice(Float.valueOf(nodes.getChildText("ceilingPrice"))); product.setAvail(Integer.valueOf(nodes.getChildText("avail"))); } File customerXMLfile = new File( "C:\\Users\\Ankit Bhayani\\Documents\\NetBeansProjects\\AEDFALL2015Assignment5\\data\\Customer.xml"); Document d3 = (Document) builder.build(customerXMLfile); Element srootNode = d3.getRootElement(); List list2 = srootNode.getChildren("Customer"); for (int i = 0; i < list2.size(); i++) { Element node = (Element) list2.get(i); Customer customer = business.getCustomerDirectory().addCustomer(); customer.setCustomerName(node.getChildText("customerName")); } /*File orderXMLfile = new File("C:\\Users\\Ankit Bhayani\\Documents\\NetBeansProjects\\AEDFALL2015Assignment5\\data\\Order.xml"); Document d4 = (Document) builder.build(orderXMLfile); Element rnode = d4.getRootElement(); List list3 = rnode.getChildren("OrderItem"); for (int i = 0; i < list3.size(); i++) { Element node = (Element) list3.get(i); Order order = new Order(); Product p=(Product)node.getChildText("pname"); OrderItem oi = order.addOrderItem(order, i, i); customer.setCustomerName(node.getChildText("customerName")); } */ }
From source file:utils.ParserXML.java
License:Apache License
/** * search recursuvely the element and returns the contents * @param root/* ww w . ja v a2 s .co m*/ * @param element name of element * @return value of element, null if element don't exist */ public static String getElementContentInStructure(Element root, String element) { String value = root.getChildText(element); Element result; if (value == null) { result = ParserXML.searchElementStatic(root.getChildren(), element); if (result != null) { value = result.getText(); } } return value; }
From source file:Utils.XMLParser.java
public ArrayList<String> getTitulos() throws JDOMException, IOException { //Este documento agora possui toda a estrutura do arquivo. Document d = sb.build(f);//from www .j a v a 2 s . c o m //Recuperamos o elemento root mural = d.getRootElement(); //Recuperamos os elementos filhos (children) List elements = mural.getChildren(); Iterator i = elements.iterator(); ArrayList<String> titulo = new ArrayList<>(); String s; //Iteramos com os elementos filhos, e filhos do dos filhos while (i.hasNext()) { Element element = (Element) i.next(); s = element.getChildText("textoExplicativo"); titulo.add(s); } return titulo; }
From source file:Utils.XMLParser.java
public ArrayList<String> getQuestoes() throws JDOMException, IOException { //Este documento agora possui toda a estrutura do arquivo. Document d = sb.build(f);//from w w w . j av a 2s .c om //Recuperamos o elemento root mural = d.getRootElement(); //Recuperamos os elementos filhos (children) List elements = mural.getChildren(); Iterator i = elements.iterator(); ArrayList<String> questoes = new ArrayList<>(); String s; //Iteramos com os elementos filhos, e filhos do dos filhos while (i.hasNext()) { Element element = (Element) i.next(); s = element.getChildText("questoesChave"); questoes.add(s); } return questoes; }
From source file:whitehole.ObjectDB.java
License:Open Source License
public static void initialize() { fallback = true;//w ww . ja v a 2 s . c o m timestamp = 0; categories = new LinkedHashMap<>(); objects = new LinkedHashMap<>(); File odbfile = new File("objectdb.xml"); if (!odbfile.exists()) return; try { SAXBuilder sxb = new SAXBuilder(); Document doc = sxb.build(odbfile); Element root = doc.getRootElement(); timestamp = root.getAttribute("timestamp").getLongValue(); List<Element> catelems = root.getChild("categories").getChildren("category"); for (Element catelem : catelems) categories.put(catelem.getAttribute("id").getIntValue(), catelem.getText()); List<Element> objelems = root.getChildren("object"); for (Element objelem : objelems) { Object entry = new Object(); entry.ID = objelem.getAttributeValue("id"); entry.name = objelem.getChildText("name"); Element flags = objelem.getChild("flags"); entry.games = flags.getAttribute("games").getIntValue(); entry.category = objelem.getChild("category").getAttribute("id").getIntValue(); entry.preferredFile = objelem.getChild("preferredfile").getAttributeValue("name"); entry.notes = objelem.getChildText("notes"); entry.dataFiles = new ArrayList<>(); String datafiles = objelem.getChildText("files"); for (String datafile : datafiles.split("\n")) entry.dataFiles.add(datafile); List<Element> fields = objelem.getChildren("field"); entry.fields = new HashMap<>(fields.size()); for (Element field : fields) { Object.Field fielddata = new Object.Field(); fielddata.ID = field.getAttribute("id").getIntValue(); fielddata.type = field.getAttributeValue("type"); fielddata.name = field.getAttributeValue("name"); fielddata.values = field.getAttributeValue("values"); fielddata.notes = field.getAttributeValue("notes"); entry.fields.put(fielddata.ID, fielddata); } objects.put(entry.ID, entry); } } catch (Exception ex) { timestamp = 0; return; } fallback = false; }
From source file:Xml.XmlParser.java
public void parse() { try {/* w w w. j a va 2 s . c om*/ SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(new StringReader(xmlFile)); Element elm = doc.getRootElement(); email = elm.getChildText("email"); token = elm.getChildText("token"); lifetime = elm.getChildText("lifetime"); } catch (JDOMException | IOException ex) { } }
From source file:XMLGenerator.ParsingXML.java
public ArrayList xmlParsing(String xml, String root, String nodes) { String result = ""; xml = xml.replace("xmlns", "doc"); xml = xml.replace("xmlns=\"\"", ""); xml = xml.replaceAll(" /", "/"); SAXBuilder builder = new SAXBuilder(); try {/* w ww. ja v a 2 s .co m*/ Document documentparse = builder.build(new StringReader(xml)); String[] split_root = root.split(">"); int jml_root = split_root.length; list = new List[jml_root]; ele = new ArrayList(); al = new ArrayList(); ele.add(documentparse.getRootElement()); list[ele.size() - 1] = ele.get(0).getChildren(split_root[0]); int index = jml_root; for (int x = 1; x <= jml_root; x++) { if (index == 1) { for (int j = 0; j < list[ele.size() - 1].size(); j++) { Element node = (Element) list[ele.size() - 1].get(j); String[] split_nodes = nodes.split(","); int z = 0; for (String node1 : split_nodes) { if (node.getChildText(node1) == null) { result += "kosong"; } else if (node.getChildText(node1).equalsIgnoreCase("")) { result += "kosong"; } else { result += node.getChildText(node1); } result += (z == (split_nodes.length - 1)) ? "" : ","; z++; } al.add(result); } } else { for (int j = 0; j < list[(x - 1)].size(); j++) { ele.add((Element) list[(x - 1)].get(j)); list[ele.size() - 1] = ele.get(ele.size() - 1).getChildren(split_root[x]); index--; } } } } catch (JDOMException ex) { Logger.getLogger(ParsingXML.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ParsingXML.class.getName()).log(Level.SEVERE, null, ex); } return al; }
From source file:xmljdom.XMLJDOM.java
/** * @param args the command line arguments *///w w w . ja v a 2 s. c o m public static void main(String[] args) { SAXBuilder builder = new SAXBuilder(); File f = new File("/home/joci/Joci/Java_Tanfolyam/cd_catalog.xml"); try { Document document = builder.build(f); Element root = document.getRootElement(); List<Element> elements = root.getChildren(); List<CD> cds = new ArrayList<>(); for (Element oneCD : elements) { CD cd = new CD(oneCD.getChildText("ARTIST"), oneCD.getChildText("TITLE"), oneCD.getChildText("COMPANY"), oneCD.getChildText("COUNTRY"), Double.parseDouble(oneCD.getChildText("PRICE")), Integer.parseInt(oneCD.getChildText("YEAR"))); cds.add(cd); } for (CD cd : cds) { System.out.println(cd); } } catch (JDOMException | IOException ex) { System.out.println(ex); } }