List of usage examples for org.dom4j Node getText
String getText();
Returns the text of this node.
From source file:org.opencms.importexport.CmsXmlPageConverter.java
License:Open Source License
/** * Converts the contents of a page into an xml page.<p> * //from ww w . ja va 2s .co m * @param cms the cms object * @param content the content used with xml templates * @param locale the locale of the body element(s) * @param encoding the encoding to the xml page * @return the xml page content or null if conversion failed * @throws CmsImportExportException if the body content or the XMLTEMPLATE element were not found * @throws CmsXmlException if there is an error reading xml contents from the byte array into a document */ public static CmsXmlPage convertToXmlPage(CmsObject cms, byte[] content, Locale locale, String encoding) throws CmsImportExportException, CmsXmlException { CmsXmlPage xmlPage = null; Document page = CmsXmlUtils.unmarshalHelper(content, null); Element xmltemplate = page.getRootElement(); if ((xmltemplate == null) || !"XMLTEMPLATE".equals(xmltemplate.getName())) { throw new CmsImportExportException(Messages.get().container(Messages.ERR_NOT_FOUND_ELEM_XMLTEMPLATE_0)); } // get all edittemplate nodes Iterator i = xmltemplate.elementIterator("edittemplate"); boolean useEditTemplates = true; if (!i.hasNext()) { // no edittemplate nodes found, get the template nodes i = xmltemplate.elementIterator("TEMPLATE"); useEditTemplates = false; } // now create the XML page xmlPage = new CmsXmlPage(locale, encoding); while (i.hasNext()) { Element currentTemplate = (Element) i.next(); String bodyName = currentTemplate.attributeValue("name"); if (CmsStringUtil.isEmpty(bodyName)) { // no template name found, use the parameter body name bodyName = "body"; } String bodyContent = null; if (useEditTemplates) { // no content manipulation needed for edittemplates bodyContent = currentTemplate.getText(); } else { // parse content for TEMPLATEs StringBuffer contentBuffer = new StringBuffer(); for (Iterator k = currentTemplate.nodeIterator(); k.hasNext();) { Node n = (Node) k.next(); if (n.getNodeType() == Node.CDATA_SECTION_NODE) { contentBuffer.append(n.getText()); continue; } else if (n.getNodeType() == Node.ELEMENT_NODE) { if ("LINK".equals(n.getName())) { contentBuffer.append(OpenCms.getSystemInfo().getOpenCmsContext()); contentBuffer.append(n.getText()); continue; } } } bodyContent = contentBuffer.toString(); } if (bodyContent == null) { throw new CmsImportExportException(Messages.get().container(Messages.ERR_BODY_CONTENT_NOT_FOUND_0)); } bodyContent = CmsStringUtil.substitute(bodyContent, CmsStringUtil.MACRO_OPENCMS_CONTEXT, OpenCms.getSystemInfo().getOpenCmsContext()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(bodyContent)) { xmlPage.addValue(bodyName, locale); xmlPage.setStringValue(cms, bodyName, locale, bodyContent); } } return xmlPage; }
From source file:org.opencms.search.extractors.CmsExtractorOpenOffice.java
License:Open Source License
/** * Internal routine that parses the specific content.xml part of * an odf document.<p>/*from w ww . j a v a 2s . c o m*/ * * @param in the input stream spooled to the start of the content.xml part * * @return the extracted content * * @throws Exception if sth goes wrong */ private String readContent(java.io.InputStream in) throws Exception { StringBuffer resultBuffer = new StringBuffer(); SAXReader reader = new SAXReader(); Document doc = reader.read(in); List<Node> textlist = CmsXmlGenericWrapper.selectNodes(doc, "//text:p[@*] | //text:span[@*]"); Iterator<Node> li = textlist.iterator(); while (li.hasNext()) { Node textNode = li.next(); String text = textNode.getText(); if (text.length() > 1) { text = " " + text + " "; resultBuffer.append(text); } } return resultBuffer.toString(); }
From source file:org.opencms.setup.xml.CmsSetupXmlHelper.java
License:Open Source License
/** * Returns the value in the given xpath of the given xml file.<p> * /*w w w . j ava2 s .c om*/ * @param document the xml document * @param xPath the xpath to read (should select a single node or attribute) * * @return the value in the given xpath of the given xml file, or <code>null</code> if no matching node */ public static String getValue(Document document, String xPath) { Node node = document.selectSingleNode(xPath); if (node != null) { // return the value return node.getText(); } else { return null; } }
From source file:org.opencms.setup.xml.CmsSetValueAction.java
License:Open Source License
/** * @see org.opencms.setup.xml.CmsXmlUpdateAction#executeUpdate(org.dom4j.Document, java.lang.String, boolean) *//* w ww .j a v a2 s . c o m*/ @Override public boolean executeUpdate(Document doc, String xpath, boolean forReal) { org.dom4j.Node node = doc.selectSingleNode(xpath); if ((node != null) && Objects.equal(node.getText(), m_value)) { return false; } CmsSetupXmlHelper.setValue(doc, xpath, m_value); return true; }
From source file:org.opencms.setup.xml.v7.CmsXmlChangeGalleryClasses.java
License:Open Source License
/** * @see org.opencms.setup.xml.A_CmsSetupXmlUpdate#executeUpdate(org.dom4j.Document, java.lang.String, boolean) *///from w w w . j a v a2s . c o m @Override protected boolean executeUpdate(Document document, String xpath, boolean forReal) { Node node = document.selectSingleNode(xpath); String oldClass = node.getText(); if ((oldClass != null) && !oldClass.contains(".CmsAjax") && oldClass.contains(".Cms")) { oldClass = oldClass.replace(".Cms", ".CmsAjax"); CmsSetupXmlHelper.setValue(document, xpath, oldClass); return true; } return false; }
From source file:org.opencms.util.ant.CmsAntTaskEnsureDirManifest.java
License:Open Source License
/** * Run the task.<p>//from w ww. j av a2 s . c om * * Sets the given property to <code>__ABORT__</code> if canceled, or to a list of selected * modules if not.<p> * * @throws BuildException if something goes wrong * * @see org.apache.tools.ant.Task#execute() */ @SuppressWarnings("unchecked") @Override public void execute() throws BuildException { try { // read xml Document doc; BufferedInputStream in = new BufferedInputStream(new FileInputStream(getXmlFile())); try { doc = CmsXmlUtils.unmarshalHelper(new InputSource(in), null); } finally { in.close(); } // get directory content String directory = getDirectory(); String[] files = new File(directory).list(); for (int i = 0; i < files.length; i++) { File file = new File(directory, files[i]); if (!file.isDirectory()) { continue; } // prepare new file array String[] children = file.list(); String[] newFiles = new String[files.length + children.length]; System.arraycopy(files, 0, newFiles, 0, i + 1); for (int j = 0; j < children.length; j++) { newFiles[j + i + 1] = files[i] + '/' + children[j]; } if (i + 1 < files.length) { System.arraycopy(files, i + 1, newFiles, i + 1 + children.length, files.length - (i + 1)); } files = newFiles; } // delete superfluous entries String prefix = new File(directory).getAbsolutePath() .substring(new File(getBase()).getAbsolutePath().length() + 1).replace('\\', '/'); List<Node> xmlFiles = doc .selectNodes("export/files/file/destination[starts-with(.,'" + prefix + "/')]"); for (Node xmlFile : xmlFiles) { String path = xmlFile.getText(); File file = new File(getBase() + "/" + path); if (!file.exists()) { CmsSetupXmlHelper.setValue(doc, getFileXpath(path), null); } } // create missing entries for (int i = 0; i < files.length; i++) { String destination = prefix + '/' + files[i]; if (destination.endsWith("/CVS") || destination.contains("/CVS/")) { // ignore cvs data continue; } String xpath = getFileXpath(destination); if (CmsSetupXmlHelper.getValue(doc, xpath) != null) { // entry already present continue; } // create entry String prevDest = prefix + (i == 0 ? "" : '/' + files[i - 1]); createEntry(doc, prevDest, destination); } // write xml BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(getXmlFile())); try { CmsXmlUtils.marshal(doc, out, "UTF-8"); } finally { out.close(); } } catch (Exception e) { throw new BuildException(e.getLocalizedMessage(), e); } }
From source file:org.opencms.workplace.tools.git.CmsGitCheckin.java
License:Open Source License
/** * Imports the selected modules from the git repository.<p> * * @return true if there were no errors during the import *//*from w w w . j a va 2s. c o m*/ @SuppressWarnings("resource") private boolean importModules() { boolean result = true; try { m_logStream.println("Checking module dependencies."); Multimap<String, String> dependencies = HashMultimap.create(); Set<String> unsortedModules = Sets.newHashSet(m_modulesToExport); for (String module : m_modulesToExport) { String manifestPath = CmsStringUtil.joinPaths(m_currentConfiguration.getModulesPath(), module, m_currentConfiguration.getResourcesSubFolder(), "manifest.xml"); Document doc = CmsXmlUtils.unmarshalHelper(CmsFileUtil.readFully(new FileInputStream(manifestPath)), new CmsXmlEntityResolver(null)); List<?> depNodes = doc.getRootElement().selectNodes("//dependencies/dependency/@name"); for (Object nodeObj : depNodes) { Node node = ((Node) nodeObj); String dependency = node.getText(); if (m_modulesToExport.contains(dependency)) { // we can only handle dependencies between selected modules // and just have to assume that other dependencies are fulfilled dependencies.put(module, dependency); } } } List<String> sortedModules = Lists.newArrayList(); // if there are no cycles, this loop will find one element on each iteration for (int i = 0; i < m_modulesToExport.size(); i++) { String nextModule = null; for (String key : unsortedModules) { if (dependencies.get(key).isEmpty()) { nextModule = key; break; } } if (nextModule != null) { sortedModules.add(nextModule); unsortedModules.remove(nextModule); for (String key : Sets.newHashSet(dependencies.keySet())) { // copy key set to avoid concurrent modification exception dependencies.get(key).remove(nextModule); } } } m_logStream.println("Modules sorted by dependencies: " + sortedModules); for (String moduleName : sortedModules) { String dir = CmsStringUtil.joinPaths(m_currentConfiguration.getModulesPath(), moduleName, m_currentConfiguration.getResourcesSubFolder()); File dirEntry = new File(dir); if (!dirEntry.exists()) { continue; } try { m_logStream.println("Creating temp file for module " + moduleName); File outputFile = File.createTempFile(moduleName + "-", ".zip"); FileOutputStream fos = new FileOutputStream(outputFile); m_logStream.println("Zipping module structure to " + outputFile.getAbsolutePath()); zipRfsFolder(dirEntry, fos); result &= importModule(outputFile); outputFile.delete(); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); e.printStackTrace(m_logStream); result = false; } } } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); m_logStream.println("Unable to check dependencies for modules, giving up."); e.printStackTrace(m_logStream); result = false; } return result; }
From source file:org.opencustomer.connector.scheduling.SchedulingManager.java
License:Mozilla Public License
/** * Reads alarm jobs from a xml configuration file, and adds the jobs to the AlarmManager. * @param file xml configuration file.// w ww. ja v a 2 s.c o m */ public void readXMLJobs(File file) { SAXReader reader = new SAXReader(); Document document; try { document = reader.read(file); } catch (DocumentException e1) { log.warn("error parsing file " + file.getName()); return; } Element root = document.getRootElement(); Iterator iter = root.elementIterator(); while (iter.hasNext()) { Element element = (Element) iter.next(); String type = element.valueOf("@type"); String name = element.valueOf("@name"); String className = element.valueOf("@class"); AlarmListener alarm = null; try { Class cl = Class.forName(className); Constructor b = cl.getConstructor(new Class[] {}); alarm = (AlarmListener) b.newInstance(new Object[] {}); } catch (Exception e) { log.warn("unable to get class for event: " + name, e); } if (alarm != null && type.equals("DATE")) { Node dateNode = root.selectSingleNode("//events/event/date"); if (dateNode != null && dateNode.getText() != null) { SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); try { AlarmEntry alarmEntry = new AlarmEntry(name, sdf.parse(dateNode.getText()), alarm); alarmEntry.setRingInNewThead(); if (log.isDebugEnabled()) log.debug("adding event: " + alarmEntry); alarmManager.addAlarm(alarmEntry); } catch (ParseException e) { log.warn("unparseable date format of event: " + name, e); } catch (PastDateException e) { if (log.isInfoEnabled()) log.info("ignoring old event: " + name); } } } else if (alarm != null && type.equals("DELAY")) { Node minuteNode = root.selectSingleNode("//events/event/minute"); if (minuteNode != null && minuteNode.getText() != null) { int minute = Integer.parseInt(minuteNode.getText()); try { AlarmEntry alarmEntry = new AlarmEntry(name, minute, true, alarm); alarmEntry.setRingInNewThead(); if (log.isDebugEnabled()) log.debug("adding event: " + alarmEntry); alarmManager.addAlarm(alarmEntry); } catch (PastDateException e) { if (log.isInfoEnabled()) log.info("ignoring old event: " + name); ; } } } else if (alarm != null && type.equals("CRON")) { //Minuten int minutes[] = getChildEntries(element, "minute"); //Stunden int hours[] = getChildEntries(element, "hour"); //Tag des Monats int dayOfMonth[] = getChildEntries(element, "dayofmonth"); //Monat int months[] = getChildEntries(element, "month"); //Tag der Woche int dayOfWeek[] = getChildEntries(element, "dayofweek"); //Jahr Node yearNode = root.selectSingleNode("//events/event/year"); int year = -1; if (yearNode != null && yearNode.getText() != null) year = Integer.parseInt(yearNode.getText()); try { AlarmEntry alarmEntry = new AlarmEntry(name, minutes, hours, dayOfMonth, months, dayOfWeek, year, alarm); alarmEntry.setRingInNewThead(); if (log.isDebugEnabled()) log.debug("adding event: " + alarmEntry); alarmManager.addAlarm(alarmEntry); } catch (PastDateException e) { if (log.isInfoEnabled()) log.info("ignoring old event: " + name); } } } }
From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java
License:Open Source License
/** * Evaluate a sequence a statements, and insert the result of the * evaluation the given parent node at the given position. */// w w w.j av a 2s . c o m public static void insert(LocationData locationData, Node parent, int position, Object toInsert) { List nodesToInsert = xpathObjectToDOM4JList(locationData, toInsert); if (parent instanceof Element) Collections.reverse(nodesToInsert); for (Iterator j = nodesToInsert.iterator(); j.hasNext();) { Object object = j.next(); Node node = object instanceof String || object instanceof Number ? Dom4jUtils.createText(object.toString()) : (Node) ((Node) object).clone(); if (parent instanceof Element) { Element element = (Element) parent; if (node instanceof Attribute) { element.attributes().add(node); } else { element.content().add(position, node); } } else if (parent instanceof Attribute) { Attribute attribute = (Attribute) parent; attribute.setValue(attribute.getValue() + node.getText()); } else if (parent instanceof Document) { // Update a document element final Document document = (Document) parent; if (node instanceof Element) { if (document.getRootElement() != null) throw new ValidationException("Document already has a root element", locationData); document.setRootElement((Element) node); } else if (node instanceof ProcessingInstruction) { document.add(node); } else { throw new ValidationException( "Only an element or processing instruction can be at the root of a document", locationData); } } else { throw new ValidationException("Cannot insert into a node of type '" + parent.getClass() + "'", locationData); } } }