List of usage examples for org.dom4j Element addCDATA
Element addCDATA(String cdata);
CDATA
node with the given text to this element. From source file:nl.tue.gale.common.XPPEntityReader.java
License:Open Source License
protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException { DocumentFactory df = getDocumentFactory(); Document document = df.createDocument(); Element parent = null; XmlPullParser pp = getXPPParser();// w w w. j ava 2 s . co m pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); pp.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false); defineEntities(pp); while (true) { int type = pp.nextToken(); switch (type) { case XmlPullParser.PROCESSING_INSTRUCTION: { String text = pp.getText(); int loc = text.indexOf(" "); if (loc >= 0) { String target = text.substring(0, loc); String txt = text.substring(loc + 1); document.addProcessingInstruction(target, txt); } else { document.addProcessingInstruction(text, ""); } break; } case XmlPullParser.COMMENT: { if (parent != null) { parent.addComment(pp.getText()); } else { document.addComment(pp.getText()); } break; } case XmlPullParser.CDSECT: { if (parent != null) { parent.addCDATA(pp.getText()); } else { String msg = "Cannot have text content outside of the " + "root document"; throw new DocumentException(msg); } break; } case XmlPullParser.ENTITY_REF: if (parent != null) { if (pp.getName().equals("gt")) { parent.addText(">"); } else if (pp.getName().equals("lt")) { parent.addText("<"); } else if (pp.getName().equals("amp")) { parent.addText("&"); } else if (pp.getName().equals("quot")) { parent.addText("\""); } else parent.addEntity(pp.getName(), "&" + pp.getName() + ";"); } break; case XmlPullParser.END_DOCUMENT: return document; case XmlPullParser.START_TAG: { QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace()) : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace()); Element newElement = df.createElement(qname); int nsStart = pp.getNamespaceCount(pp.getDepth() - 1); int nsEnd = pp.getNamespaceCount(pp.getDepth()); for (int i = nsStart; i < nsEnd; i++) { if (pp.getNamespacePrefix(i) != null) { newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i)); } } for (int i = 0; i < pp.getAttributeCount(); i++) { QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i)) : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i), pp.getAttributeNamespace(i)); newElement.addAttribute(qa, pp.getAttributeValue(i)); } if (parent != null) { parent.add(newElement); } else { document.add(newElement); } parent = newElement; break; } case XmlPullParser.END_TAG: { if (parent != null) { parent = parent.getParent(); } break; } case XmlPullParser.TEXT: { String text = pp.getText(); if (parent != null) { parent.addText(text); } else { String msg = "Cannot have text content outside of the " + "root document"; throw new DocumentException(msg); } break; } default: break; } } }
From source file:org.alfresco.web.bean.search.SearchContext.java
License:Open Source License
/** * @return this SearchContext as XML// w ww . j a v a 2 s . co m * * Example: * <code> * <?xml version="1.0" encoding="UTF-8"?> * <search> * <text>CDATA</text> * <mode>int</mode> * <location>XPath</location> * <categories> * <category>XPath</category> * </categories> * <content-type>String</content-type> * <folder-type>String</folder-type> * <mimetype>String</mimetype> * <attributes> * <attribute name="String">String</attribute> * </attributes> * <ranges> * <range name="String"> * <lower>String</lower> * <upper>String</upper> * <inclusive>boolean</inclusive> * </range> * </ranges> * <fixed-values> * <value name="String">String</value> * </fixed-values> * <query>CDATA</query> * </search> * </code> */ public String toXML() { try { NamespaceService ns = Repository.getServiceRegistry(FacesContext.getCurrentInstance()) .getNamespaceService(); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement(ELEMENT_SEARCH); root.addElement(ELEMENT_TEXT).addCDATA(this.text); root.addElement(ELEMENT_MODE).addText(Integer.toString(this.mode)); if (this.location != null) { root.addElement(ELEMENT_LOCATION).addText(this.location); } Element categories = root.addElement(ELEMENT_CATEGORIES); for (String path : this.categories) { categories.addElement(ELEMENT_CATEGORY).addText(path); } if (this.contentType != null) { root.addElement(ELEMENT_CONTENT_TYPE).addText(this.contentType); } if (this.folderType != null) { root.addElement(ELEMENT_FOLDER_TYPE).addText(this.folderType); } if (this.mimeType != null && this.mimeType.length() != 0) { root.addElement(ELEMENT_MIMETYPE).addText(this.mimeType); } Element attributes = root.addElement(ELEMENT_ATTRIBUTES); for (QName attrName : this.queryAttributes.keySet()) { attributes.addElement(ELEMENT_ATTRIBUTE).addAttribute(ELEMENT_NAME, attrName.toPrefixString(ns)) .addCDATA(this.queryAttributes.get(attrName)); } Element ranges = root.addElement(ELEMENT_RANGES); for (QName rangeName : this.rangeAttributes.keySet()) { RangeProperties rangeProps = this.rangeAttributes.get(rangeName); Element range = ranges.addElement(ELEMENT_RANGE); range.addAttribute(ELEMENT_NAME, rangeName.toPrefixString(ns)); range.addElement(ELEMENT_LOWER).addText(rangeProps.lower); range.addElement(ELEMENT_UPPER).addText(rangeProps.upper); range.addElement(ELEMENT_INCLUSIVE).addText(Boolean.toString(rangeProps.inclusive)); } Element values = root.addElement(ELEMENT_FIXED_VALUES); for (QName valueName : this.queryFixedValues.keySet()) { values.addElement(ELEMENT_VALUE).addAttribute(ELEMENT_NAME, valueName.toPrefixString(ns)) .addCDATA(this.queryFixedValues.get(valueName)); } // outputing the full lucene query may be useful for some situations Element query = root.addElement(ELEMENT_QUERY); String queryString = buildQuery(0); if (queryString != null) { query.addCDATA(queryString); } StringWriter out = new StringWriter(1024); XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint()); writer.setWriter(out); writer.write(doc); return out.toString(); } catch (Throwable err) { throw new AlfrescoRuntimeException("Failed to export SearchContext to XML.", err); } }
From source file:org.b5chat.crossfire.core.property.XMLProperties.java
License:Open Source License
/** * Sets a property to an array of values. Multiple values matching the same property * is mapped to an XML file as multiple elements containing each value. * For example, using the name "foo.bar.prop", and the value string array containing * {"some value", "other value", "last value"} would produce the following XML: * <pre>/*from ww w .jav a 2 s. com*/ * <foo> * <bar> * <prop>some value</prop> * <prop>other value</prop> * <prop>last value</prop> * </bar> * </foo> * </pre> * * @param name the name of the property. * @param values the values for the property (can be empty but not null). */ public void setProperties(String name, List<String> values) { String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy, // stopping one short. Element element = document.getRootElement(); for (int i = 0; i < propName.length - 1; i++) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(propName[i]) == null) { element.addElement(propName[i]); } element = element.element(propName[i]); } String childName = propName[propName.length - 1]; // We found matching property, clear all children. List<Element> toRemove = new ArrayList<Element>(); @SuppressWarnings("unchecked") Iterator<Element> iter = element.elementIterator(childName); while (iter.hasNext()) { toRemove.add(iter.next()); } for (iter = toRemove.iterator(); iter.hasNext();) { element.remove(iter.next()); } // Add the new children. for (String value : values) { Element childElement = element.addElement(childName); if (value.startsWith("<![CDATA[")) { @SuppressWarnings("unchecked") Iterator<Node> it = childElement.nodeIterator(); while (it.hasNext()) { Node node = it.next(); if (node instanceof CDATA) { childElement.remove(node); break; } } childElement.addCDATA(value.substring(9, value.length() - 3)); } else { childElement.setText(StringEscapeUtils.escapeXml(value)); } } saveProperties(); // Generate event. Map<String, Object> params = new HashMap<String, Object>(); params.put("value", values); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params); }
From source file:org.b5chat.crossfire.core.property.XMLProperties.java
License:Open Source License
/** * Sets the value of the specified property. If the property doesn't * currently exist, it will be automatically created. * * @param name the name of the property to set. * @param value the new value for the property. */// w w w . ja va 2s .c o m public synchronized void setProperty(String name, String value) { if (!StringEscapeUtils.escapeXml(name).equals(name)) { throw new IllegalArgumentException("Property name cannot contain XML entities."); } if (name == null) { return; } if (value == null) { value = ""; } // Set cache correctly with prop name and value. propertyCache.put(name, value); String[] propName = parsePropertyName(name); // Search for this property by traversing down the XML heirarchy. Element element = document.getRootElement(); for (String aPropName : propName) { // If we don't find this part of the property in the XML heirarchy // we add it as a new node if (element.element(aPropName) == null) { element.addElement(aPropName); } element = element.element(aPropName); } // Set the value of the property in this node. if (value.startsWith("<![CDATA[")) { @SuppressWarnings("unchecked") Iterator<Node> it = element.nodeIterator(); while (it.hasNext()) { Node node = it.next(); if (node instanceof CDATA) { element.remove(node); break; } } element.addCDATA(value.substring(9, value.length() - 3)); } else { element.setText(value); } // Write the XML properties to disk saveProperties(); // Generate event. Map<String, Object> params = new HashMap<String, Object>(); params.put("value", value); PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params); }
From source file:org.eclipse.jubula.client.core.businessprocess.AbstractXMLReportGenerator.java
License:Open Source License
/** * Builds and returns a test report element. Subclasses can create an entire * test result hierarchy by recursively calling this method, using the * returned element as an argument for the next method call. * //from w w w . j a va 2 s .c om * @param resultNode * <code>TestResultNode</code> to translate to an XML element. * @param element * The XML element to which the result for node will be added. * This can be considered the parent of the returned element. * @return The <code>Element</code> created. */ protected Element buildElement(Element element, TestResultNode resultNode) { Element insertInto = element; Object node = resultNode.getNode(); if (node instanceof ITestSuitePO) { ITestSuitePO ts = (ITestSuitePO) node; Element suite = element.addElement("testsuite"); //$NON-NLS-1$ insertInto = suite; addGeneralElements(resultNode, insertInto); IAUTMainPO aut = ts.getAut(); Element autEl = suite.addElement("aut"); //$NON-NLS-1$ autEl.addElement("name").addText(aut.getName()); //$NON-NLS-1$ autEl.addElement("config").addText(getTestResult().getAutConfigName()); //$NON-NLS-1$ autEl.addElement("server").addText(getTestResult().getAutAgentHostName()); //$NON-NLS-1$ autEl.addElement("cmdline-parameter").setText(getTestResult().getAutArguments()); //$NON-NLS-1$ insertInto = suite.addElement("test-run"); //$NON-NLS-1$ } else if (node instanceof IEventExecTestCasePO) { insertInto = element.addElement("eventhandler"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); Element typeEl = insertInto.addElement("type"); //$NON-NLS-1$ typeEl.addText(I18n.getString(((IEventExecTestCasePO) node).getEventType())); Element reentryEl = insertInto.addElement("reentry-property"); //$NON-NLS-1$ reentryEl.addText(((IEventExecTestCasePO) node).getReentryProp().toString()); } else if (node instanceof ITestCasePO) { insertInto = element.addElement("testcase"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } else if (node instanceof ICapPO) { insertInto = element.addElement("step"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); addCapElements(resultNode, insertInto, (ICapPO) node); } else if (node instanceof ICommentPO) { insertInto = element.addElement("comment"); //$NON-NLS-1$ Element nameElement = insertInto.addElement("name"); //$NON-NLS-1$ nameElement.addCDATA(((ICommentPO) node).getName()); } else if (node instanceof IConditionalStatementPO) { insertInto = element.addElement("ifthenelse"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } else if (node instanceof IAbstractContainerPO) { insertInto = element.addElement("container"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } else if (node instanceof IWhileDoPO) { insertInto = element.addElement("whiledo"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } else if (node instanceof IDoWhilePO) { insertInto = element.addElement("dowhile"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } else if (node instanceof IIteratePO) { insertInto = element.addElement("repeat"); //$NON-NLS-1$ addGeneralElements(resultNode, insertInto); } addParamNodeElements(resultNode, insertInto); return insertInto; }
From source file:org.eclipse.jubula.client.core.businessprocess.AbstractXMLReportGenerator.java
License:Open Source License
/** * adds information for a Cap to the XML file * /*w ww .java 2 s .com*/ * @param resultNode * the actual node * @param insertInto * where to insert elements in xml * @param node * NodePO */ protected void addCapElements(TestResultNode resultNode, Element insertInto, ICapPO node) { ICapPO cap = node; getTimestampFromResultNode(resultNode, insertInto); Element compEl = insertInto.addElement("component-name"); //$NON-NLS-1$ compEl.addText(StringUtils.defaultString(resultNode.getComponentName())); Element compTypeEl = insertInto.addElement("component-type"); //$NON-NLS-1$ compTypeEl.addText(CompSystemI18n.getString(cap.getComponentType(), true)); double heuristicMatch = resultNode.getOmHeuristicEquivalence(); if (heuristicMatch >= 0) { Element heuristicMatchElement = insertInto.addElement("component-heuristic-match"); //$NON-NLS-1$ heuristicMatchElement.addText(String.valueOf(heuristicMatch)); } Element actionEl = insertInto.addElement("action-type"); //$NON-NLS-1$ actionEl.addText(CompSystemI18n.getString(cap.getActionName(), true)); if (StringUtils.isNotBlank(resultNode.getCommandLog())) { Element commandEl = insertInto.addElement("command-log"); //$NON-NLS-1$ commandEl.addCDATA(resultNode.getCommandLog()); } if (resultNode.getStatus() == TestResultNode.ERROR || resultNode.getStatus() == TestResultNode.RETRYING) { Element error = insertInto.addElement("error"); //$NON-NLS-1$ Element errorType = error.addElement("type"); //$NON-NLS-1$ TestErrorEvent event = resultNode.getEvent(); if (event != null) { errorType.addText(I18n.getString(event.getId(), true)); Map<String, Object> eventProps = event.getProps(); if (eventProps.containsKey(TestErrorEvent.Property.DESCRIPTION_KEY)) { String key = (String) eventProps.get(TestErrorEvent.Property.DESCRIPTION_KEY); Object[] args = (Object[]) eventProps.get(TestErrorEvent.Property.PARAMETER_KEY); args = args != null ? args : new Object[0]; Element mapEntry = error.addElement("description"); //$NON-NLS-1$ if (mapEntry != null && key != null) { mapEntry.addText( resultNode.hasBackingNode() ? String.valueOf(I18n.getString(key, args)) : key); } } else { for (Map.Entry<String, Object> entry : eventProps.entrySet()) { if (!TestErrorEvent.Property.DESCRIPTION_KEY.equals(entry.getKey())) { Element mapEntry = error.addElement(entry.getKey()); mapEntry.addText(String.valueOf(entry.getValue())); } } } } if (ClientTest.instance().isScreenshotForXML()) { final byte[] screenshotData = resultNode.getScreenshot(); if (screenshotData != null) { Element screenshotElement = error.addElement("screenshot"); //$NON-NLS-1$ screenshotElement.addText(new String(Base64.encodeBase64(screenshotData, false))); } } } }
From source file:org.infoglue.cms.applications.common.actions.SimpleXmlServiceAction.java
License:Open Source License
public String doContentTypeDefinitions() throws Exception { List contentTypeDefinitions = getContentTypeDefinitions(); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("definitions"); TransactionHistoryController transactionHistoryController = TransactionHistoryController.getController(); for (Iterator i = contentTypeDefinitions.iterator(); i.hasNext();) { ContentTypeDefinitionVO vo = (ContentTypeDefinitionVO) i.next(); if (vo.getType().compareTo(ContentTypeDefinitionVO.CONTENT) == 0) { TransactionHistoryVO transactionHistoryVO = transactionHistoryController .getLatestTransactionHistoryVOForEntity(ContentTypeDefinitionImpl.class, vo.getContentTypeDefinitionId()); Element definition = DocumentHelper.createElement("definition"); definition.addAttribute("id", "" + vo.getContentTypeDefinitionId()) .addAttribute("type", "" + vo.getType()).addAttribute("name", vo.getName()); if (transactionHistoryVO != null) definition.addAttribute("mod", formatDate(transactionHistoryVO.getTransactionDateTime())); Element schemaValue = definition.addElement("schemaValue"); schemaValue.addCDATA(vo.getSchemaValue()); root.add(definition);/* w w w. j a va2 s . c o m*/ } } return out(getFormattedDocument(doc)); }
From source file:org.infoglue.cms.applications.contenttool.actions.ContentTreeXMLAction.java
License:Open Source License
public Element getContentVersionElement(ContentVersionVO vo) throws SystemException, Bug, UnsupportedEncodingException { Element element = DocumentHelper.createElement("contentVersion"); Element head = DocumentHelper.createElement("head"); Element value = DocumentHelper.createElement("value"); head.addAttribute("id", "" + vo.getContentVersionId()); head.addAttribute("languageId", "" + vo.getLanguageId()); head.addAttribute("languageName", vo.getLanguageName()); head.addAttribute("isActive", "" + vo.getIsActive()); TransactionHistoryController transactionHistoryController = TransactionHistoryController.getController(); TransactionHistoryVO transactionHistoryVO = transactionHistoryController .getLatestTransactionHistoryVOForEntity(ContentVersionImpl.class, vo.getContentVersionId()); if (transactionHistoryVO != null) head.addAttribute("mod", formatDate(transactionHistoryVO.getTransactionDateTime())); // head.addAttribute("mod", formatDate(vo.getModifiedDateTime())); value.addCDATA(URLEncoder.encode(vo.getVersionValue(), "UTF-8")); element.add(head);/*w w w .ja v a2 s . co m*/ element.add(value); return element; }
From source file:org.infoglue.cms.applications.contenttool.actions.ContentTreeXMLAction.java
License:Open Source License
public String doContentTypeDefinitions() throws Exception { List contentTypeDefinitions = getContentTypeDefinitions(); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("definitions"); TransactionHistoryController transactionHistoryController = TransactionHistoryController.getController(); for (Iterator i = contentTypeDefinitions.iterator(); i.hasNext();) { ContentTypeDefinitionVO vo = (ContentTypeDefinitionVO) i.next(); if (vo.getType().compareTo(ContentTypeDefinitionVO.CONTENT) == 0) { TransactionHistoryVO transactionHistoryVO = transactionHistoryController .getLatestTransactionHistoryVOForEntity(ContentTypeDefinitionImpl.class, vo.getContentTypeDefinitionId()); Element definition = DocumentHelper.createElement("definition"); definition.addAttribute("id", "" + vo.getContentTypeDefinitionId()) .addAttribute("type", "" + vo.getType()).addAttribute("name", vo.getName()); if (transactionHistoryVO != null) definition.addAttribute("mod", formatDate(transactionHistoryVO.getTransactionDateTime())); Element schemaValue = definition.addElement("schemaValue"); schemaValue.addCDATA(vo.getSchemaValue()); root.add(definition);/*from w ww. j a v a 2s . c om*/ } } return out(getFormattedDocument(doc)); }
From source file:org.infoglue.cms.applications.contenttool.actions.SimpleContentXmlAction.java
License:Open Source License
public Element getContentVersionValueElement(ContentVersionVO vo) throws SystemException, Bug, UnsupportedEncodingException { Element value = DocumentHelper.createElement("value"); if (enableCompression) { Base64Encoder encoder = new Base64Encoder(); CompressionHelper zip = new CompressionHelper(); byte[] val = zip.compress(vo.getVersionValue()); value.addCDATA(encoder.encode(val)); } else {/* www .j a v a 2s . co m*/ value.addCDATA(URLEncoder.encode(vo.getVersionValue(), "UTF-8")); } return value; }