List of usage examples for org.dom4j Document getRootElement
Element getRootElement();
From source file:com.devoteam.srit.xmlloader.core.Parameter.java
License:Open Source License
public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception { // remove beginning to '<' character int iPosBegin = xml.indexOf('<'); if (iPosBegin > 0) { xml = xml.substring(iPosBegin);// ww w . ja v a 2 s . co m } // remove from '>' character to the end int iPosEnd = xml.lastIndexOf('>'); if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1)) { xml = xml.substring(0, iPosEnd + 1); } int iPosXMLLine = xml.indexOf("<?xml"); if (iPosXMLLine < 0) { xml = "<?xml version='1.0'?>" + xml; } // remove the namespace because the parser does not support them if there are not declare in the root node if (deleteNS) { xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<"); xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</"); } // remove doctype information (dtd files for the XML syntax) xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", ""); InputStream input = new ByteArrayInputStream(xml.getBytes()); SAXReader reader = new SAXReader(false); reader.setEntityResolver(new XMLLoaderEntityResolver()); Document document = reader.read(input); XPath xpathObject = document.createXPath(xpath); Object obj = xpathObject.evaluate(document.getRootElement()); if (obj instanceof List) { List<Node> list = (List<Node>) obj; for (Node node : list) { add(node.asXML()); } } else if (obj instanceof DefaultElement) { Node node = (Node) obj; add(node.asXML()); } else if (obj instanceof DefaultAttribute) { Node node = (Node) obj; add(node.getStringValue()); } else if (obj instanceof DefaultText) { Node node = (Node) obj; add(node.getText()); } else { add(obj.toString()); } }
From source file:com.devoteam.srit.xmlloader.diameter.dictionary.Dictionary.java
License:Open Source License
/** * Parse the dictionary from a file./*from w w w. j a v a 2s . c o m*/ */ private void parseFromFile(String path) throws Exception { XMLDocument dictionaryDocument = new XMLDocument(); dictionaryDocument.setXMLSchema(URIFactory.newURI("../conf/schemas/diameter-dictionary.xsd")); dictionaryDocument.setXMLFile(URIFactory.newURI(path)); dictionaryDocument.parse(); Document document = dictionaryDocument.getDocument(); // parse vendors applicationByName = new HashMap(); applicationById = new HashMap(); traceDebug("try to parsing application base"); // // base first, important for references from other applications // parseApplication(document.getRootElement().element("base")); traceDebug("try to parsing all application"); // // all applications // List<Element> elements = document.getRootElement().elements("application"); for (Element element : elements) { parseApplication(element); } }
From source file:com.devoteam.srit.xmlloader.genscript.Param.java
License:Open Source License
public String applySubstitution(String text, Msg msg) throws Exception { String msgAvecParametres = ""; if (getRegle() != null) { String[] regexTab = getRegle().split("#"); // Si la regle est sous forme d'expression rgulire if (regexTab[0].toUpperCase().contains("REGEX")) { GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE, "Replace parameter " + getRegle() + " => " + name); String[] regexRule = Arrays.copyOfRange(regexTab, 1, regexTab.length); msgAvecParametres = regexRemplace(regexRule, 0, text); }// ww w . j av a 2s . com // Si la regle est sous forme de xpath else if (regexTab[0].toUpperCase().contains("XPATH")) { GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE, "Replace parameter " + getRegle() + " => " + name); // Rcupration des paramtres String xpathRule = regexTab[1]; String attribut = regexTab[2]; attribut = attribut.replace("@", ""); // Cration de l'arbre DOM correspondant au message SAXReader reader = new SAXReader(); try { Document document = reader.read(new ByteArrayInputStream(text.getBytes("UTF-8"))); // Cration de l'objet XPATH ) selectionner XPath xpath = new DefaultXPath(xpathRule); // Rcupration des noeuds correspondants List<Node> nodes = xpath.selectNodes(document.getRootElement(), xpath); // Pour chaque noeuds modifier Element aRemplacer = null; for (Node n : nodes) { setRemplacedValue(n.getText()); if (n instanceof Element) { aRemplacer = (Element) n; } else { aRemplacer = n.getParent(); } String newValue = getName(); String oldValue = aRemplacer.attribute(attribut).getValue(); // On regarde si on est dans le cas de paramtres mixtes if (regexTab.length > 3) { if (regexTab[3].equals("REGEX")) { setRemplacedValue(null); String[] regexRule = Arrays.copyOfRange(regexTab, 4, regexTab.length); newValue = regexRemplace(regexRule, 0, oldValue); } } aRemplacer.setAttributeValue(attribut, newValue); } // Convertion en chane de caractre de l'arbre DOM du message msgAvecParametres = document.getRootElement().asXML(); } catch (Exception e) { } } // si la rgle est sous forme de pathkey else if (regexTab[0].toUpperCase().contains("PATHKEY")) { String valeurARemplacer = null; // On rcupre la valeur remplacer String pathKeyWord = regexTab[1]; if (msg != null) { Parameter valeurParamARemplacer = msg.getParameter(pathKeyWord); if (valeurParamARemplacer.length() > 0) { valeurARemplacer = valeurParamARemplacer.get(0).toString(); } // On remplace dans tout le message par le parametre if (valeurARemplacer != null) { msgAvecParametres = text.replace(valeurARemplacer, getName()); if (!msgAvecParametres.equals(text)) { GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE, "Replace parameter " + valeurARemplacer + " => " + name); setRemplacedValue(valeurARemplacer); } } } } } // Si le message n'a pas subit de modification, on retourne null if (!isUsed()) { return null; } // Sinon on retourne le message modifi avec les paramtres return msgAvecParametres; }
From source file:com.devoteam.srit.xmlloader.genscript.ScriptGenerator.java
License:Open Source License
public void generateTest() throws Exception { // Si le fichier n'existe pas dj if (!fileRoot.exists()) { test = new Test("Genscript", "Script converted from capture"); }//w w w.j a v a 2 s .c o m // Si le fichier de sortie existe dj else { // On ouvre le fichier existant File xml = fileRoot; Document testDoc; SAXReader reader = new SAXReader(); testDoc = reader.read(xml); Element testExistant = testDoc.getRootElement(); // On gnre un nouvel objet test partir de l'lment existant dans le fichier test = new Test(testExistant.attributeValue("name"), testExistant.attributeValue("description")); test.setTest(testExistant); } // On tente de rcuprer le testcase gnrer Element testcaseExistant = null; for (Iterator i = test.getTest().elements().iterator(); i.hasNext();) { Element elem = (Element) i.next(); if (elem.getName().equals("testcase") && elem.attribute("name").getText().equals(testcaseName)) { testcaseExistant = elem; } } // On rcupre les paramtres existants for (Iterator i = test.getTest().elements().iterator(); i.hasNext();) { Element elem = (Element) i.next(); if (elem.getName().equals("parameter")) { Param p = new Param(elem.attributeValue("name"), "test", elem.attributeValue("operation") + "," + elem.attributeValue("value"), null, Param.TARGET_SENDCLIENT); p.setName(p.getFamily()); p.setRemplacedValue(elem.attributeValue("value")); ParamGenerator.getInstance().recordParam(p); } } // Si le testcase n'existe pas encore if (testcaseExistant == null) { // On le crait testcase = new TestCase(testcaseName, "Testcase generate from capture", "true"); test.getTest().add(testcase.getTestCase()); } // Sinon on gnre un testcase partir de celui existant dans le fichier else { testcase = new TestCase(testcaseExistant.attributeValue("name"), testcaseExistant.attributeValue("description"), testcaseExistant.attributeValue("state")); testcase.setTestCase(testcaseExistant); // On rcupre les paramtres existants for (Iterator i = testcase.getTestCase().elements().iterator(); i.hasNext();) { Element elem = (Element) i.next(); if (elem.getName().equals("parameter")) { Param p = new Param(elem.attributeValue("name"), "testcase", elem.attributeValue("operation") + "," + elem.attributeValue("value"), null, Param.TARGET_SENDCLIENT); p.setName(p.getFamily()); p.setRemplacedValue(elem.attributeValue("value")); ParamGenerator.getInstance().recordParam(p); } } } // On ajoute le testcase dans le test test.addTestCase(testcase); // On tente de rcuprer le scenario Element scenarioExistant = null; // On enregistre les scenarios de ce testcase for (Iterator j = testcase.getTestCase().elements().iterator(); j.hasNext();) { Element elem = (Element) j.next(); if (elem.getName().equals("scenario") && elem.getText().contains(listeFiltre.get(0).getHostPort().toString())) { scenarioExistant = elem; } else if (elem.getName().equals("scenario")) { Scenario sc = new Scenario(elem.attributeValue("name"), elem.getText(), listeFiltre); testcase.addScenario(sc); } } // Si le scenario n'existe pas encore if (scenarioExistant == null) { // On le crait scenario = new Scenario(getScenarioName(), getScenarioPath(), listeFiltre); testcase.getTestCase().add(scenario.toXmlElement()); } else { scenario = new Scenario(scenarioExistant.attributeValue("name"), scenarioExistant.getText(), listeFiltre); scenario.setScenario(scenarioExistant); } // On ajoute ce scenario au testcase testcase.addScenario(scenario); }
From source file:com.digiaplus.modules.scorm.ScormCPManifestTreeModel.java
License:Apache License
/** * Constructor of the content packaging tree model * @param manifest the imsmanifest.xml file * @param itemStatus a Map containing the status of each item like "completed, not attempted, ..." *//* w w w .j ava2s.c om*/ public ScormCPManifestTreeModel(File manifest, Map itemStatus) { this.itemStatus = itemStatus; Document doc = loadDocument(manifest); // get all organization elements. need to set namespace rootElement = doc.getRootElement(); String nsuri = rootElement.getNamespace().getURI(); nsuris.put("ns", nsuri); XPath meta = rootElement.createXPath("//ns:organization"); meta.setNamespaceURIs(nsuris); XPath metares = rootElement.createXPath("//ns:resources"); metares.setNamespaceURIs(nsuris); Element elResources = (Element) metares.selectSingleNode(rootElement); if (elResources == null) throw new DAPRuntimeException(this.getClass(), "could not find element resources"); List resourcesList = elResources.elements("resource"); resources = new HashMap(resourcesList.size()); for (Iterator iter = resourcesList.iterator(); iter.hasNext();) { Element elRes = (Element) iter.next(); String identVal = elRes.attributeValue("identifier"); String hrefVal = elRes.attributeValue("href"); if (hrefVal != null) { // href is optional element for resource element try { hrefVal = URLDecoder.decode(hrefVal, "UTF-8"); } catch (UnsupportedEncodingException e) { // each JVM must implement UTF-8 } } resources.put(identVal, hrefVal); } /* * Get all organizations */ List organizations = new LinkedList(); organizations = meta.selectNodes(rootElement); if (organizations.isEmpty()) { throw new DAPRuntimeException(this.getClass(), "could not find element organization"); } GenericTreeNode gtn = buildTreeNodes(organizations); setRootNode(gtn); rootElement = null; // help gc resources = null; }
From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java
License:Apache License
/** * Loads preference by filePath./*from w ww . ja v a 2 s.com*/ * * @param filePath * @return */ public Object load(String filePath) { Object obj = null; File file = new File(filePath); if (!file.exists()) { return null; } try { SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element parent = doc.getRootElement(); NodeInfo rootInfo = new NodeInfo(parent); obj = Class.forName(rootInfo.getClazz()).newInstance(); load(obj, parent); } catch (DocumentException ex) { String errMsg = "The system cannot find the file specified path " + filePath + "."; Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, errMsg, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { String errMsg = "No-args constructor is missing for " + ex.getMessage(); Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, errMsg, ex); } catch (IllegalAccessException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } return obj; }
From source file:com.dockingsoftware.dockingpreference.PreferenceProcessor.java
License:Apache License
/** * Loads user preference information.// w w w.ja va2 s .c o m * * @param obj the object whose field should be modified */ public void load(Object obj) { String filePath = GlobalConstant.USER_HOME + "/" + obj.getClass().getName() + GlobalConstant.FILE_EXTENSION; File file = new File(filePath); if (!file.exists()) { return; } try { SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element parent = doc.getRootElement(); load(obj, parent); } catch (DocumentException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalArgumentException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { String errMsg = "No-args constructor is missing for " + ex.getMessage(); Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, errMsg, ex); } catch (IllegalAccessException ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(PreferenceProcessor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.doculibre.constellio.izpack.PersistenceXMLUtils.java
License:Open Source License
@SuppressWarnings("unchecked") public static void run(AbstractUIProcessHandler handler, String[] args) { if (args.length != 5) { System.out.println("persistence_mysqlPath defaultPersistencePath server login password"); return;/*from w w w . j av a 2s . c om*/ } String persistence_mysqlPath = args[0]; String defaultPersistencePath = args[1]; String server = args[2]; String login = args[3]; String password = args[4]; Document xmlDocument; try { xmlDocument = new SAXReader().read(persistence_mysqlPath); Element root = xmlDocument.getRootElement(); Iterator<Element> it = root.elementIterator("persistence-unit"); if (!it.hasNext()) { System.out.println("Corrupt persistence file :" + persistence_mysqlPath); return; } it = it.next().elementIterator("properties"); if (!it.hasNext()) { System.out.println("Corrupt persistence file :" + persistence_mysqlPath); return; } Element properties = it.next(); for (it = properties.elementIterator("property"); it.hasNext();) { Element property = it.next(); String id = property.attributeValue("name"); if (id.equals(SERVER_ELEMENT_ID)) { Attribute att = property.attribute("value"); att.setText(BEFORE_SERVER_NAME + server + AFTER_SERVER_NAME); } else { if (id.equals(LOGIN_ELEMENT_ID)) { Attribute att = property.attribute("value"); att.setText(login); } else { if (id.equals(PASSWORD_ELEMENT_ID)) { Attribute att = property.attribute("value"); att.setText(password); } } } } OutputFormat format = OutputFormat.createPrettyPrint(); File xmlFile = new File(persistence_mysqlPath); XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format); writer2.write(xmlDocument); writer2.close(); // copier au fichier de persistence par dfaut: xmlFile = new File(defaultPersistencePath); writer2 = new XMLWriter(new FileOutputStream(xmlFile), format); writer2.write(xmlDocument); writer2.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.izpack.TomcatUtil.java
License:Open Source License
@SuppressWarnings("unchecked") public static void run(AbstractUIProcessHandler handler, String[] args) { if (args.length != 2) { System.out.println("serverPath port"); return;/*w w w . j a va 2s. c o m*/ } String serverPath = args[0]; String port = args[1]; if (port.equals("8080")) { // C'est celui par defaut => ne rien faire return; } Document xmlDocument; try { xmlDocument = new SAXReader().read(serverPath); Element root = xmlDocument.getRootElement(); Iterator<Element> it = root.elementIterator("Service"); if (!it.hasNext()) { System.out.println("Corrupt persistence file :" + serverPath); return; } Element connectors = it.next(); for (it = connectors.elementIterator("Connector"); it.hasNext();) { Element connector = it.next(); String id = connector.attributeValue("protocol"); if (id.startsWith("HTTP")) { Attribute att = connector.attribute("port"); att.setText(port); break; } } OutputFormat format = OutputFormat.createPrettyPrint(); File xmlFile = new File(serverPath); XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format); writer2.write(xmlDocument); writer2.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.izpack.UsersToXmlFile.java
License:Open Source License
public static void run(AbstractUIProcessHandler handler, String[] args) { if (args.length != 3) { System.out.println("file login password"); return;/*from w w w . j ava 2s .c o m*/ } String target = args[0]; File xmlFile = new File(target); BufferedWriter writer; try { writer = new BufferedWriter(new FileWriter(xmlFile)); } catch (IOException e) { e.printStackTrace(); return; } try { for (String line : Arrays.asList(emptyFileLines)) { writer.write(line + System.getProperty("line.separator")); } writer.close(); } catch (Exception e) { e.printStackTrace(); } String login = args[1]; String passwd = args[2]; UsersToXmlFile elem = new UsersToXmlFile(); ConstellioUser dataUser = elem.new ConstellioUser(login, passwd, null); dataUser.setFirstName("System"); dataUser.setLastName("Administrator"); dataUser.getRoles().add(Roles.ADMIN); Document xmlDocument; try { xmlDocument = new SAXReader().read(target); Element root = xmlDocument.getRootElement(); BaseElement user = new BaseElement(USER); user.addAttribute(FIRST_NAME, dataUser.getFirstName()); user.addAttribute(LAST_NAME, dataUser.getLastName()); user.addAttribute(LOGIN, dataUser.getUsername()); user.addAttribute(PASSWORD_HASH, dataUser.getPasswordHash()); if (dataUser.getLocale() != null) { user.addAttribute(LOCALE, dataUser.getLocaleCode()); } Set<String> constellioRoles = dataUser.getRoles(); if (!constellioRoles.isEmpty()) { Element roles = user.addElement(ROLES); for (String constellioRole : constellioRoles) { Element role = roles.addElement(ROLE); role.addAttribute(VALUE, constellioRole); } } root.add(user); OutputFormat format = OutputFormat.createPrettyPrint(); xmlFile = new File(target); // FIXME recrire la DTD // xmlDocument.addDocType(arg0, arg1, arg2) XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format); writer2.write(xmlDocument); writer2.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }