List of usage examples for org.dom4j Document getRootElement
Element getRootElement();
From source file:BlastResultXMLsplit.BlastXMLsplit.java
public BlastXMLsplit(String filepath, int seqnumber) throws FileNotFoundException, IOException, ParserConfigurationException { SAXReader reader = new SAXReader(); reader.setValidation(false);//w w w. j a va 2 s . c om try { System.out.println("Xlmfile reading"); Document document = reader.read(new FileInputStream(filepath));//XMLdocument? System.out.println("Xlmfile read done!"); org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory(); ArrayList str = new ArrayList();//??? String fileoutpath; org.dom4j.Element rootElm = document.getRootElement();// File f = new File(filepath); int count = 1; List<org.dom4j.Element> blastOutput_iterations = rootElm.element("BlastOutput_iterations").elements();//? org.dom4j.Element BlastOutput_program = rootElm.element("BlastOutput_program"); org.dom4j.Element BlastOutput_version = rootElm.element("BlastOutput_version"); org.dom4j.Element BlastOutput_reference = rootElm.element("BlastOutput_reference"); org.dom4j.Element BlastOutput_db = rootElm.element("BlastOutput_db"); //? BlastOutput_program.getParent().remove(BlastOutput_program); BlastOutput_version.getParent().remove(BlastOutput_version); BlastOutput_reference.getParent().remove(BlastOutput_reference); BlastOutput_db.getParent().remove(BlastOutput_db); // org.dom4j.Element BlastOutput_query_def=rootElm.element("BlastOutput_query-def"); //org.dom4j.Element BBlastOutput_query_len=rootElm.element("BlastOutput_query-len"); org.dom4j.Element BlastOutput_param = rootElm.element("BlastOutput_param"); rootElm.remove(BlastOutput_param); String Iteration_queryIDstr, Iteration_queryDefstr, Iteration_query_len; List<org.dom4j.Element> Iterationlist = null; int size = blastOutput_iterations.size(); System.out.println("Your query seqcount is " + size + "\r\n Start dividing your file"); for (int i = 0; i < size; i = i + seqnumber) { //?? fileoutpath = f.getParent() + System.getProperty("file.separator") + count + ".xml"; count++; System.out.println("The " + count + " is located in " + fileoutpath); FileOutputStream fos = new FileOutputStream(fileoutpath); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(fos, format); // XMLWriter writer = new XMLWriter(new FileOutputStream(fileoutpath)); //w?? org.dom4j.Element firstelement = blastOutput_iterations.get(i); Iteration_queryIDstr = firstelement.element("Iteration_query-ID").getText(); Iteration_queryDefstr = firstelement.element("Iteration_query-def").getText(); Iteration_query_len = firstelement.element("Iteration_query-len").getText(); //org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory(); Document document2 = DocumentHelper.createDocument(); ; org.dom4j.Element BlastOutputElement = document2.addElement("BlastOutput"); //doc.setRootElement(BlastOutputElement); //; BlastOutputElement.add(BlastOutput_program); BlastOutputElement.add(BlastOutput_version); BlastOutputElement.add(BlastOutput_reference); BlastOutputElement.add(BlastOutput_db); BlastOutputElement.addElement("BlastOutput_query-ID"); BlastOutputElement.element("BlastOutput_query-ID").setText(Iteration_queryIDstr); BlastOutputElement.addElement("BlastOutput_query-def"); BlastOutputElement.element("BlastOutput_query-def").setText(Iteration_queryDefstr); BlastOutputElement.addElement("BlastOutput_query-len"); BlastOutputElement.element("BlastOutput_query-len").setText(Iteration_query_len); // Element BlastOutput_param_new=DocumentFactory.createElement("BlastOutput_param"); // for (Iterator it = BlastOutput_param.elementIterator(); it.hasNext();) { // Element tempele=(Element) it.next(); // tempele.getParent().remove(tempele); // BlastOutput_param_new.add(tempele); // } BlastOutputElement.add(BlastOutput_param); //BlastOutputElement.add(BlastOutput_param); if (i + seqnumber < blastOutput_iterations.size()) { Iterationlist = blastOutput_iterations.subList(i, i + seqnumber); } else { Iterationlist = blastOutput_iterations.subList(i, blastOutput_iterations.size() - 1); } //System.out.println(Iterationlist.size()); //?query resetIterationlist(Iterationlist); //?BlastOutput_iterations Element BlastOutput_iterations = DocumentFactory.createElement("BlastOutput_iterations"); //BlastOutputElement.addAttribute("BlastOutput_iterations"); //org.dom4j.Element BlastOutput_iterations = new org.dom4j.Element("BlastOutput_iterations"); for (int j = 0; j < Iterationlist.size(); j++) { Iterationlist.get(j).getParent().remove(Iterationlist.get(j)); //System.out.println(j); BlastOutput_iterations.add(Iterationlist.get(j)); } BlastOutputElement.add(BlastOutput_iterations); // writer.write(document2); writer.close(); BlastOutput_program.getParent().remove(BlastOutput_program); BlastOutput_version.getParent().remove(BlastOutput_version); BlastOutput_reference.getParent().remove(BlastOutput_reference); BlastOutput_db.getParent().remove(BlastOutput_db); BlastOutput_param.getParent().remove(BlastOutput_param); } } catch (DocumentException ex) { Logger.getLogger(BlastXMLsplit.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:bookmarks.buddylist.BuddyListServlet.java
License:Open Source License
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Utilities.prepareRequest(request); HttpSession session = request.getSession(); ClientEntry userInfo = (ClientEntry) session.getAttribute("AuthStamp"); String action = (String) request.getParameter("action"); String agent = Utilities.eliminateNull((String) request.getParameter("agent")); BookmarkXML xml = new BookmarkXML(); String nameEntry = Utilities.trimString((String) request.getParameter("name")); String nickEntry = Utilities.trimString((String) request.getParameter("nick")); final String AUTH_FAILURE = "You must register or log in before managing" + " your buddies."; Utilities.prepareResponseAgent(response); if (userInfo == null) { if (agent.equals(Utilities.AGENT_EXT)) { xml.constructNodeAction("FAILURE", AUTH_FAILURE); } else {//from w ww . j a v a 2s . c o m Utilities.prepareResponseWeb(response); xml.constructWithResultMsg("", AUTH_FAILURE); Utilities.styleXML(xml, "error", userInfo); } response.getWriter().println(xml.toString()); return; } //If no action specified, construct buddies management page if (action == null) { Utilities.prepareResponseWeb(response); if (agent.equals(Utilities.AGENT_EXT)) { return; } xml.constructMain(userInfo.getClientName(), "manageBuddies"); Utilities.styleXML(xml, userInfo); response.getWriter().println(xml.toString()); return; } //Validate nickname and username if (action.equals("add") || action.equals("edit") || action.equals("remove")) { try { NICKNAME_CONSTRAINT.validate(nickEntry); USERNAME_CONSTRAINT.validate(nameEntry); } catch (ConstraintException e) { if (e.getConstraint() instanceof StringConstraint) { StringConstraint c = (StringConstraint) e.getConstraint(); String message; if (e.getType() == ConstraintException.VALUE_ABOVE_MAXIMUM) { message = c.getName() + " cannot exceed " + c.getMaxLength() + " characters."; } else if (e.getType() == ConstraintException.VALUE_BELOW_MINIMUM) { message = c.getName() + " must be at least " + c.getMinLength() + " characters."; } else if (e.getType() == ConstraintException.NULL_NOT_ALLOWED) { message = "You must enter a value for " + c.getName(); } else { message = c.getName() + " failed constraint check."; } constructFailure(message).write(response.getWriter()); return; } } } MySqlBuddyList buddyList = null; try { buddyList = new MySqlBuddyList(userInfo.getClientID()); if (action.equals("display")) { Document result = constructSuccess(); Document buddyListDoc = buddyList.toXml(); result.getRootElement().add(buddyListDoc.getRootElement()); result.write(response.getWriter()); return; } if (action.equals("add")) { boolean addResult; if (buddyList.contains(nameEntry)) { constructFailure("Unable to add buddy: user '" + nameEntry + "' is already in your buddy list.") .write(response.getWriter()); return; } if (buddyList.containsPending(nameEntry)) { constructFailure("Unable to add buddy: user '" + nameEntry + "' already has a pending buddy request. He or she has not yet accepted or rejected your friendship.") .write(response.getWriter()); return; } if (nameEntry.toLowerCase().equals(userInfo.getClientName().toLowerCase())) { constructFailure("You may not become buddies with youself. Go get some friends.") .write(response.getWriter()); return; } if (nickEntry != null) addResult = buddyList.add(nameEntry, nickEntry); else addResult = buddyList.add(nameEntry); if (!addResult) { constructFailure("Unable to add buddy: user '" + nameEntry + "' does not exist.") .write(response.getWriter()); return; } constructSuccess().write(response.getWriter()); return; } if (action.equals("remove")) { if (!buddyList.remove(nameEntry)) { constructFailure( "Unable to remove user: user '" + nameEntry + "' does not exist in your buddy list") .write(response.getWriter()); return; } constructSuccess().write(response.getWriter()); return; } if (action.equals("edit")) { if (!buddyList.editBuddyNickname(nameEntry, nickEntry)) { constructFailure( "Unable to edit user: user '" + nameEntry + "' does not exist in your buddy list.") .write(response.getWriter()); return; } constructSuccess().write(response.getWriter()); return; } if (action.equals("getBuddyRequests") || action.equals("login")) { Utilities.prepareResponseAgent(response); ArrayList<BuddyList.Buddy> buddyRequests = buddyList.getBuddyRequests(); xml.constructBuddyRequests(buddyRequests); Utilities.returnResponse(response, xml); return; } if (action.equals("setBuddyRequests")) { String[] userNames = request.getParameterValues("UserName"); String[] accepteds = request.getParameterValues("Accepted"); if (userNames.length != accepteds.length) { constructFailure("Error, UserNames and Accepted input fields do not match in length.") .write(response.getWriter()); return; } for (int i = 0; i < userNames.length; i++) { buddyList.setAccepted(userNames[i], accepteds[i]); } Utilities.prepareResponseAgent(response); xml.constructGenericSuccess(); Utilities.returnResponse(response, xml); } if (action.equals("viewPendingBuddyRequests")) { Utilities.prepareResponseAgent(response); ArrayList<BuddyList.Buddy> pendingBuddyRequests = buddyList.getPendingBuddyRequests(); xml.constructBuddyRequests(pendingBuddyRequests); Utilities.returnResponse(response, xml); return; } if (action.equals("viewTransitiveBuddies")) { if (nameEntry == null || nameEntry.equals("")) { constructFailure("Error, no one spefied by name").write(response.getWriter()); return; } DatabaseWrapper db = DatabaseWrapper.getDatabaseWrapper(); MySqlBuddyList myBuddiesBuddies = null; if (!db.checkUserExists(nameEntry)) { constructFailure("Error, user does not exist").write(response.getWriter()); return; } if (!buddyList.contains(nameEntry)) { constructFailure("Error, user is not your buddy").write(response.getWriter()); return; } myBuddiesBuddies = new MySqlBuddyList(db.getUserByName(nameEntry).getClientID()); Document result = constructSuccess(); Document buddyListDoc = myBuddiesBuddies.toXml(); result.getRootElement().add(buddyListDoc.getRootElement()); result.write(response.getWriter()); return; } } catch (SQLException e) { constructFailure("Error accessing database:\n" + e.getMessage()).write(response.getWriter()); Utilities.ignoreChipmarkException(e); } catch (IllegalAccessException e) { constructFailure("Error IllegalAccess:\n" + e.getMessage()).write(response.getWriter()); Utilities.ignoreChipmarkException(e); } catch (Exception e) { constructFailure("Error :\n" + e.getMessage()).write(response.getWriter()); Utilities.ignoreChipmarkException(e); } }
From source file:br.com.atus.util.CEPWebService.java
@SuppressWarnings("rawtypes") public CEPWebService(String cep) { try {//www. java 2 s . c o m URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml"); Document document = getDocumento(url); Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); if (element.getQualifiedName().equals("uf")) setEstado(element.getText()); if (element.getQualifiedName().equals("cidade")) setCidade(element.getText()); if (element.getQualifiedName().equals("bairro")) setBairro(element.getText()); if (element.getQualifiedName().equals("tipo_logradouro")) setTipoLogradouro(element.getText()); if (element.getQualifiedName().equals("logradouro")) setLogradouro(element.getText()); if (element.getQualifiedName().equals("resultado")) setResultado(Integer.parseInt(element.getText())); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:br.com.cgcop.utilitarios.CEPWebService.java
public void consultar(String cep) throws MalformedURLException, DocumentException { URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml"); Document document = getDocumento(url); Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); if (element.getQualifiedName().equals("uf")) { setEstado(element.getText()); }/* ww w . j a va 2 s .c o m*/ if (element.getQualifiedName().equals("cidade")) { setCidade(element.getText()); } if (element.getQualifiedName().equals("bairro")) { setBairro(element.getText()); } if (element.getQualifiedName().equals("tipo_logradouro")) { setTipoLogradouro(element.getText()); } if (element.getQualifiedName().equals("logradouro")) { setLogradouro(element.getText()); } if (element.getQualifiedName().equals("resultado")) { setResultado(Integer.parseInt(element.getText())); } } }
From source file:br.com.sistemapetshop.util.CepWebService.java
@SuppressWarnings("rawtypes") public CepWebService(String cep) { try {//from www. j a v a2 s. c om URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml"); Document document = getDocumento(url); Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); if (element.getQualifiedName().equals("uf")) { setEstado(element.getText()); } if (element.getQualifiedName().equals("cidade")) { setCidade(element.getText()); } if (element.getQualifiedName().equals("bairro")) { setBairro(element.getText()); } if (element.getQualifiedName().equals("tipo_logradouro")) { setTipoLogradouro(element.getText()); } if (element.getQualifiedName().equals("logradouro")) { setLogradouro(element.getText()); } if (element.getQualifiedName().equals("resultado")) { setResultado(Integer.parseInt(element.getText())); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:br.com.ufra.cep.service.CepWebService.java
public CepWebService(String cep) { try {/*from w w w .j av a2 s. co m*/ URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml"); Document document = getDocumento(url); Element root = document.getRootElement(); for (Iterator i = root.elementIterator(); i.hasNext();) { Element element = (Element) i.next(); if (element.getQualifiedName().equals("estado")) { setEstado(element.getText()); } if (element.getQualifiedName().equals("cidade")) { setCidade(element.getText()); } if (element.getQualifiedName().equals("bairro")) { setBairro(element.getText()); } if (element.getQualifiedName().equals("tipo_logradouro")) { setTipo_logradouro(element.getText()); } if (element.getQualifiedName().equals("logradouro")) { setLogradouro(element.getText()); } if (element.getQualifiedName().equals("resultado")) { setResultado(Integer.parseInt(element.getText())); } if (element.getQualifiedName().equals("resultado_txt")) { setResultado_txt(element.getText()); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:ca.qc.cegepoutaouais.tge.pige.server.report.LateLoanReport.java
License:Open Source License
protected Document generateReport() throws ReportException { try {//from w w w. j av a 2 s . c om String template = ReportHelper .convertStreamToString(ReportHelper.loadFileAsStream(TEMPLATE_BASE_PATH + TEMPLATE_FILENAME)); String css = ReportHelper.convertStreamToString( ReportHelper.loadFileAsStream(TEMPLATE_BASE_PATH + TEMPLATE_STYLES_FILENAME)); logger.debug("Inscription des donnes du rapport dans le modle."); template = MessageFormat.format(template, locale.getProperty("msg.report.lateLoansReportTitle"), MessageFormat.format(locale.getProperty("msg.report.reportGeneratedBy"), getAuthor(), SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, Locale.CANADA_FRENCH) .format(new Date())), locale.getProperty("msg.report.statistics"), locale.getProperty("msg.report.totalNumberOfLoans"), locale.getProperty("msg.report.numberOfLentLoans"), locale.getProperty("msg.report.numberOfLateLoans"), ((Integer) get("total-count")).toString(), ((Integer) get("lent-count")).toString(), ((Integer) get("late-count")).toString(), String.format("%2.2f", (Float) get("percent-lent")), String.format("%2.2f", (Float) get("percent-late")), locale.getProperty("msg.report.userListWithLateLoans")); Document docRoot = DocumentHelper.parseText(template); ReportHelper.applyStyleToHTML(docRoot, css); Element body = (Element) docRoot.selectSingleNode("//data"); List<User> users = (List) get("users"); StringBuilder builder = new StringBuilder("<div>"); if (users.size() > 0) { for (User u : users) { builder.append( "<table class='user-section' border='0' cellspacing='0' cellpadding='5px'><thead><tr><td class='user-section-header'>") .append("[").append(u.getLoanNo()).append("] ").append(u.getLastname()).append(", ") .append(u.getFirstname()).append("</td><td colspan='2' class='user-section-header'>") .append(u.getEmail()).append("</td></tr><tr><td class='user-section-header'>") .append("Quantit").append("</td><td class='user-section-header'>") .append("Description").append("</td><td class='user-section-header'>") .append("chance").append("</td></tr></thead><tbody>"); Set<Loan> loans = u.getLoans(); for (Loan l : loans) { builder.append("<tr><td class='user-section-body'>").append(l.getQuantity()) .append("</td><td class='user-section-body'>").append(l.getDescription()) .append("</td><td class='user-section-body'>").append(l.getTerm().toString()) .append("</td></tr>"); } builder.append("</tbody></table>"); } } else { builder.append("<span>Aucun emprunt en retard!</span>"); } builder.append("</div>"); Document finalDoc = DocumentHelper.parseText(builder.toString()); Element content = finalDoc.getRootElement(); body.add(content); return docRoot; } catch (Exception ex) { throw new ReportException(ex); } }
From source file:cbir.reader.XMLReader.java
License:Open Source License
/** * Parses image information from a given XML file and returns a list of * images with their descriptors (only MPEG_EHD and CEDD extracted by * img(rummager))./*from ww w . j ava 2 s . co m*/ * * @param file * The given img(rummager) XML file. * @return a list of images with their descriptors. * @throws DocumentException */ public List<ImageContainer> parseXMLFile(File file) throws DocumentException { // Read XML file SAXReader reader = new SAXReader(); Document document = reader.read(file); // Get first Element Element rootElement = document.getRootElement(); // Iterate + get image paths + descriptors // outer loop (Info, Data) for (@SuppressWarnings("rawtypes") Iterator iter = rootElement.elementIterator(); iter.hasNext();) { Element element = (Element) iter.next(); // inner loop (Image Data) for (@SuppressWarnings("rawtypes") Iterator innerIter = element.elementIterator(); innerIter.hasNext();) { Element innerElement = (Element) innerIter.next(); // data loop (Filename, EHD, RGB) for (@SuppressWarnings("rawtypes") Iterator dataIter = innerElement.elementIterator(); dataIter.hasNext();) { // get Filename Element dataElement = (Element) dataIter.next(); String filename = new String(dataElement.getText()); List<Descriptor> descriptors = new LinkedList<Descriptor>(); while (dataIter.hasNext()) { // get descriptors dataElement = (Element) dataIter.next(); if (dataElement.getName().equals("EHD") || dataElement.getName().equals("CEDD")) descriptors.add(readDescriptor(dataElement)); } // construct Image and save in list ImageContainer image = new ImageContainer(filename, descriptors.toArray(new Descriptor[descriptors.size()])); imageList.add(image); } } } return imageList; }
From source file:cc.dectinc.video.tagging.tools.MetaImporter.java
/** * Given path, load the metadata of the fiven video file * // www . j ava 2 s . com * @param path */ private void parseFile(String path) { File file = new File(path); if (!file.exists()) { // System.out.println("File not found: " + file.getName()); return; } Document document = null; try { SAXReader reader = new SAXReader(); document = reader.read(file); Element root = document.getRootElement(); Meta meta = new Meta(); meta.set("identifier", root.elementText("identifier")); meta.set("title", root.elementText("title")); meta.set("mediatype", root.elementText("mediatype")); // meta.set("resource", root.elementText("licenseurl")); meta.set("uploader", root.elementText("uploader")); // meta.set("description", root.elementText("description")); // meta.set("year", Integer.parseInt(root.elementText("date"))); // meta.set("holder", root.elementText("")); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); meta.set("pubdate", df.parse(root.elementText("publicdate"))); meta.save(); } catch (Exception e) { e.printStackTrace(); } }
From source file:cc.warlock.build.FeatureVersionReplacer.java
License:Open Source License
protected void replaceVersions() throws BuildException { SAXReader reader = new SAXReader(); try {/*from w ww .j a v a2 s . co m*/ File featureFile = new File(new File(new File(buildDirectory, "features"), feature), "feature.xml"); Document featureDoc = reader.read(featureFile); Element featureEl = featureDoc.getRootElement(); featureEl.attribute("version").setValue(version); // Properties versions = new Properties(); // File versionsFile = new File(buildDirectory, "finalPluginsVersions.properties"); // FileInputStream stream = new FileInputStream(versionsFile); // versions.load(stream); // stream.close(); // // for (Element pluginEl : (List<Element>) featureEl.elements("plugin")) // { // if (pluginEl.attributeValue("version").equals("0.0.0")) // { // if (versions.containsKey(pluginEl.attributeValue("id"))) // pluginEl.attribute("version").setValue(versions.getProperty(pluginEl.attributeValue("id"))); // } // } OutputFormat format = OutputFormat.createPrettyPrint(); FileOutputStream outStream = new FileOutputStream(featureFile); XMLWriter writer = new XMLWriter(outStream, format); writer.write(featureDoc); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }