下面列出了java.beans.PropertyEditorSupport#org.dom4j.Document 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the value of the specified attribute of the node determined by the given xpath.
*
* @param doc The XML document
* @param xpath The xpath selecting the node whose attribute we want
* @param attrName The name of the attribute
* @return The attribute value
*/
private String getAttrValue(Document doc, String xpath, String attrName)
{
Node node = doc.selectSingleNode(xpath);
if (node instanceof Attribute)
{
// we ignore the attribute name then
return ((Attribute)node).getValue();
}
else if (node != null)
{
return node.valueOf("@" + attrName);
}
else
{
return null;
}
}
/**
* Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
*
* @param doc
* @param type
* @param info
*/
public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) {
final File fUserdataRoot = new File(getQtiFilePath());
final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
final File fReportingDir = new File(fUserdataRoot, path);
try {
fReportingDir.mkdirs();
final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
final Element element = doc.getRootElement();
final XMLWriter xw = new XMLWriter(os, new OutputFormat(" ", true));
xw.write(element);
// closing steams
xw.close();
os.close();
} catch (final Exception e) {
throw new OLATRuntimeException(FilePersister.class,
"Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e);
}
}
@Test
public void withoutItems() throws Exception {
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
this.selectTag.setPath("testBean");
this.selectTag.doStartTag();
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
this.tag.doEndTag();
this.selectTag.doEndTag();
String output = getOutput();
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element rootElement = document.getRootElement();
List children = rootElement.elements();
assertEquals("Incorrect number of children", 0, children.size());
}
@Override
public boolean validate(final File unzippedDir) {
// with VFS FIXME:pb:c: remove casts to LocalFileImpl and LocalFolderImpl if no longer needed.
final VFSContainer vfsUnzippedRoot = new LocalFolderImpl(unzippedDir);
final VFSItem vfsQTI = vfsUnzippedRoot.resolve("qti.xml");
// getDocument(..) ensures that InputStream is closed in every case.
final Document doc = QTIHelper.getDocument((LocalFileImpl) vfsQTI);
// if doc is null an error loading the document occured
if (doc == null) {
return false;
}
final List metas = doc.selectNodes("questestinterop/assessment/qtimetadata/qtimetadatafield");
for (final Iterator iter = metas.iterator(); iter.hasNext();) {
final Element el_metafield = (Element) iter.next();
final Element el_label = (Element) el_metafield.selectSingleNode("fieldlabel");
final String label = el_label.getText();
if (label.equals(AssessmentInstance.QMD_LABEL_TYPE)) { // type meta
final Element el_entry = (Element) el_metafield.selectSingleNode("fieldentry");
final String entry = el_entry.getText();
return entry.equals(AssessmentInstance.QMD_ENTRY_TYPE_SURVEY);
}
}
return false;
}
@Test
public void testdeployDefinition() {
// 初始化
SAXReader reader = new SAXReader();
// 拿不到信息
//URL url = this.getClass().getResource("/multipleTask.xml");
URL url = this.getClass().getResource("/singleTask.xml");
Document document = null;
try {
document = reader.read(url);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String definitionContent = document.asXML();
// deploy first time
DefinitionHelper.getInstance().deployDefinition("singleTask", "测试单人任务流程", definitionContent, true);
//DefinitionHelper.getInstance().deployDefinition("multipleTask", "测试多人任务流程", definitionContent, true);
}
private DataSourceRepository getConfiguration(String site, String cmisRepo) throws CmisRepositoryNotFoundException {
String configPath = Paths.get(getConfigLocation()).toString();
Document document = null;
DataSourceRepository repositoryConfig = null;
try {
document = contentService.getContentAsDocument(site, configPath);
Node node = document.selectSingleNode(REPOSITORY_CONFIG_XPATH.replace(CMIS_REPO_ID_VARIABLE, cmisRepo));
if (node != null) {
repositoryConfig = new DataSourceRepository();
repositoryConfig.setId(getPropertyValue(node, ID_PROPERTY));
repositoryConfig.setType(getPropertyValue(node, TYPE_PROPERTY));
repositoryConfig.setUrl(getPropertyValue(node, URL_PROPERTY));
repositoryConfig.setUsername(getPropertyValue(node, USERNAME_PROPERTY));
repositoryConfig.setPassword(getPropertyValue(node, PASSWORD_PROPERTY));
repositoryConfig.setBasePath(getPropertyValue(node, BASE_PATH_PROPERTY));
repositoryConfig.setDownloadUrlRegex(getPropertyValue(node, DOWNLOAD_URL_REGEX_PROPERTY));
repositoryConfig.setUseSsl(Boolean.parseBoolean(getPropertyValue(node, USE_SSL_PROPERTY)));
} else {
throw new CmisRepositoryNotFoundException();
}
} catch (DocumentException e) {
logger.error("Error while getting configuration for site: " + site + " cmis: " + cmisRepo +
" (config path: " + configPath + ")");
}
return repositoryConfig;
}
/**
* 修改strings.xml文件内容
*
* @param file strings文件
* @param strings 修改的值列表
*/
private void updateStrings(File file, List<Strings> strings) {
try {
if (strings == null || strings.isEmpty()) {
return;
}
Document document = new SAXReader().read(file);
List<Element> elements = document.getRootElement().elements();
elements.forEach(element -> {
final String name = element.attribute("name").getValue();
strings.forEach(s -> {
if (s.getName().equals(name)) {
element.setText(s.getValue());
callback("修改 strings.xml name='" + name + "' value='" + s.getValue() + "'");
}
});
});
XMLWriter writer = new XMLWriter(new FileOutputStream(file));
writer.write(document);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@ParameterizedTest
@FileSource(files = "/feeds/stage.xml")
void shouldGenerateDocumentForStage(String expectedXML) {
String pipelineName = "BulletinBoard";
String stageName = "UnitTest";
String jobName = "run-junit";
XmlWriterContext context = new XmlWriterContext("https://go-server/go", null, null, null, new SystemEnvironment());
Stage stage = StageMother.cancelledStage(stageName, jobName);
stage.getJobInstances().get(0).setIdentifier(new JobIdentifier(pipelineName, 1, null, stageName, "1", jobName));
stage.getJobInstances().get(0).getTransitions().first()
.setStateChangeTime(parseISO8601("2020-01-03T11:14:19+05:30"));
stage.setIdentifier(new StageIdentifier(pipelineName, 10, stage.getName(), "4"));
Document document = new StageXmlRepresenter(stage).toXml(context);
assertThat(document.asXML()).and(expectedXML)
.ignoreWhitespace()
.areIdentical();
}
/**
* Verifies that, using a simplified template, element values that are not a placeholder do not get replaced, even
* if the elemnent value contains a separator character used in the implementation to distinguish individual
* placeholders.
*
* @see <a href="https://issues.igniterealtime.org/browse/OF-1947">OF-1947</a>
*/
@Test
public void testIdentifyNonPlaceholderWithSeparatorChar() throws Exception
{
// Setup fixture.
final Document doc = DocumentHelper.parseText("<vcard><el>place/holder</el></vcard>");
final LdapVCardProvider.VCardTemplate template = new LdapVCardProvider.VCardTemplate(doc);
final Map<String, String> attributes = new HashMap<>();
attributes.put("place", "value");
attributes.put("holder", "value");
// Execute system under test.
final LdapVCardProvider.VCard vCard = new LdapVCardProvider.VCard(template);
final Element result = vCard.getVCard(attributes);
// Verify result.
assertNotNull( result );
assertEquals( "<vcard><el>place/holder</el></vcard>", result.asXML() );
}
public String createComponent(SvgBaseTo svgTo) {
String result = null;
try {
SvgAnnotationTo annoTo = (SvgAnnotationTo)svgTo;
InputStream in = SvgBench.class.getResourceAsStream(comPath);
Document doc = XmlUtil.read(in);
String str = doc.getRootElement().asXML();
str = FlowSvgUtil.replaceAll(str, local_x, StringUtil.getString(annoTo.getX()));
str = FlowSvgUtil.replaceAll(str, local_y, StringUtil.getString(annoTo.getY()));
str = FlowSvgUtil.replaceAll(str, id, annoTo.getId());
str = FlowSvgUtil.replaceAll(str, text, annoTo.getLabel());
StringBuffer sb = new StringBuffer();
sb.append(" M19 0 L0 0 L0 ");
sb.append(annoTo.getHeight());
sb.append(" L19 ");
sb.append(annoTo.getHeight());
str = FlowSvgUtil.replaceAll(str, path, sb.toString());
result = str;
} catch (DocumentException e) {
throw new FixFlowException("",e);
}
return result;
}
/**
* Xml字符串转换为Map
*
* @param xmlStr
* @return
*/
public static Map<String, String> xmlStrToMap(String xmlStr) {
Map<String, String> map = new HashMap<String, String>();
Document doc;
try {
doc = DocumentHelper.parseText(xmlStr);
Element root = doc.getRootElement();
List children = root.elements();
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Element child = (Element) children.get(i);
map.put(child.getName(), child.getTextTrim());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
return map;
}
@Test
public void withCollection() throws Exception {
this.tag.setPath("someList");
this.tag.setValue("foo");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("someList", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
/**
*
*
*/
public List getQTIItemObjectList() {
final Resolver resolver = new ImsRepositoryResolver(repositoryEntryKey);
final Document doc = resolver.getQTIDocument();
final Element root = doc.getRootElement();
final List items = root.selectNodes("//item");
final ArrayList itemList = new ArrayList();
for (final Iterator iter = items.iterator(); iter.hasNext();) {
final Element el_item = (Element) iter.next();
if (el_item.selectNodes(".//response_lid").size() > 0) {
itemList.add(new ItemWithResponseLid(el_item));
} else if (el_item.selectNodes(".//response_str").size() > 0) {
itemList.add(new ItemWithResponseStr(el_item));
}
}
return itemList;
}
/**
* Converts filter conditions tree to filter xml
* @param conditions conditions tree
* @param valueProperty Describes what parameter value will be serialized to xml: current value or default one
* @return filter xml
*/
@Override
@Nullable
public String getXml(ConditionsTree conditions, Param.ValueProperty valueProperty) {
String xml = null;
if (conditions != null && !conditions.getRootNodes().isEmpty()) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("filter");
Element element = root.addElement("and");
for (Node<AbstractCondition> node : conditions.getRootNodes()) {
recursiveToXml(node, element, valueProperty);
}
xml = dom4JTools.writeDocument(document, true);
}
log.trace("toXML: {}", xml);
return xml;
}
/**
* Returns the value of an element selected via an xpath expression from
* a component's component.xml file.
*
* @param component the component.
* @param xpath the xpath expression.
* @return the value of the element selected by the xpath expression.
*/
private String getElementValue(Component component, String xpath) {
File componentDir = componentDirs.get(component);
if (componentDir == null) {
return null;
}
try {
File componentConfig = new File(componentDir, "component.xml");
if (componentConfig.exists()) {
SAXReader saxReader = new SAXReader();
Document componentXML = saxReader.read(componentConfig);
Element element = (Element)componentXML.selectSingleNode(xpath);
if (element != null) {
return element.getTextTrim();
}
}
}
catch (Exception e) {
manager.getLog().error(e);
}
return null;
}
/**
* Check that the 'jabber:client' default namespace declaration is explicitly _not_ stripped from a child element
* of a stanza.
*
* Openfire strips this namespace (among others) to make the resulting XML 're-usable', in context of the
* implementation note in RFC 6120, section 4.8.3.
*
* @see <a href="https://issues.igniterealtime.org/browse/OF-1335">Issue OF-1335: Forwarded messages rewritten to default namespace over S2S</a>
* @see <a href="https://xmpp.org/rfcs/rfc6120.html#streams-ns-xmpp">RFC 6120, 4.8.3. XMPP Content Namespaces</a>
*/
@Test
public void testAvoidStrippingInternalContentNamespace() throws Exception
{
// Setup fixture
final String input =
"<stream:stream xmlns:stream='http://etherx.jabber.org/streams' to='example.com' version='1.0'>" +
" <message xmlns='jabber:client'>" +
" <other xmlns='something:else'>" +
" <message xmlns='jabber:client'/>" +
" </other>" +
" </message>" +
"</stream:stream>";
final Document result = packetReader.read( new StringReader( input ) );
// Verify result.
Assert.assertFalse( "'jabber:client' should not occur before 'something:else'", result.asXML().substring( 0, result.asXML().indexOf("something:else") ).contains( "jabber:client" ) );
Assert.assertTrue( "'jabber:client' should occur after 'something:else'", result.asXML().substring( result.asXML().indexOf("something:else") ).contains( "jabber:client" ) );
}
public static Document getDocument(InputStream inputStream) throws DocumentException, IOException {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(inputStream);
} catch (DocumentException e) {
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return document;
}
/**
* This method is created to be able to exit the nested loops as soon as the correct instance is found.
*
* @param question The question object from the outer loop.
* @param answer The answer object from the outer loop.
* @param xmlParser This object is needed to generate the xml string.
* @param instanceGenerator This object is needed to generate the instances
* @param claferDependency The claferDependency from the outer loop
* @return
*/
private static Document getXMLForNewAlgorithmInsertion(final Question question, final Answer answer, final XMLClaferParser xmlParser, final InstanceGenerator instanceGenerator,
final ClaferDependency claferDependency) {
final HashMap<Question, Answer> constraints = new HashMap<>();
constraints.put(question, answer);
final String constraintOnType = claferDependency.getAlgorithm();
for (final InstanceClafer instance : instanceGenerator.generateInstances(constraints)) {
for (final InstanceClafer childInstance : instance.getChildren()) {
// check if the name of the constraint on the clafer instance is the same as the one on the clafer dependency from the outer loop.
if (childInstance.getType().getName().equals(constraintOnType)) {
return xmlParser.displayInstanceValues(instance, constraints);
}
} // child instance loop
} // instance loop
return null;
}
public String getArticleXML(Long articleId) {
Article article = articleDao.getEntity(articleId);
if(article == null
|| checkBrowsePermission(article.getChannel().getId() ) < 0 ) {
return ""; // 如果文章不存在 或 对文章所在栏目没有浏览权限
}
String pubUrl = article.getPubUrl();
Document articleDoc = XMLDocUtil.createDocByAbsolutePath2(pubUrl);
Element articleElement = articleDoc.getRootElement();
Element hitRateNode = (Element) articleElement.selectSingleNode("//hitCount");
hitRateNode.setText(article.getHitCount().toString()); // 更新点击率
Document doc = org.dom4j.DocumentHelper.createDocument();
Element articleInfoElement = doc.addElement("Response").addElement("ArticleInfo");
articleInfoElement.addElement("rss").addAttribute("version", "2.0").add(articleElement);
// 添加文章点击率;
HitRateManager.getInstanse("cms_article").output(articleId);
return doc.asXML();
}
/**
Save the scenario.
@throws ScenarioException If there is a problem saving the scenario.
*/
public void save() throws ScenarioException {
if (saveFile == null) {
saveAs();
}
if (saveFile != null) {
LOG.debug("Saving to " + saveFile.getAbsolutePath());
Document doc = DocumentHelper.createDocument();
scenario.write(doc);
try {
if (!saveFile.exists()) {
File parent = saveFile.getParentFile();
if (!parent.exists()) {
if (!saveFile.getParentFile().mkdirs()) {
throw new ScenarioException("Couldn't create file " + saveFile.getPath());
}
}
if (!saveFile.createNewFile()) {
throw new ScenarioException("Couldn't create file " + saveFile.getPath());
}
}
XMLWriter writer = new XMLWriter(new FileOutputStream(saveFile), OutputFormat.createPrettyPrint());
writer.write(doc);
writer.flush();
writer.close();
}
catch (IOException e) {
throw new ScenarioException(e);
}
baseDir = saveFile.getParentFile();
changed = false;
}
}
public static Document getDocumentXML(final String xmlFileName)
{
Document document = null;
SAXReader reader = new SAXReader();
reader.setEntityResolver(new XMLLoaderEntityResolver());
try
{
document = reader.read(xmlFileName);
}
catch (DocumentException ex)
{
GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, ex, "Wrong ASN1 file : ");
}
return document;
}
public Document getStudentsDocument() {
if (getStudents() == null) return null;
try {
return new SAXReader().read(new StringReader(getStudents()));
} catch (Exception e) {
sLog.warn("Failed to load cached students for " + getCurriculum().getAbbv() + " " + getName() + ": " + e.getMessage(), e);
return null;
}
}
public static String serialize(final Document document) {
try (StringWriter out = new StringWriter()) {
final OutputFormat format = new OutputFormat(null, false, "UTF-8");
format.setExpandEmptyElements(false);
format.setIndent(false);
final XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
writer.flush();
return out.toString();
} catch (final IOException e) {
throw new IllegalStateException("Unable to serialize given document to XML", e);
}
}
@Override
public GMLMap read(Document doc) {
GMLMap result = new GMLMap();
readBuildings(doc, result);
readRoads(doc, result);
// Convert from lat/lon to metres
double scale = 1.0 / MapTools.sizeOf1Metre((result.getMinY() + result.getMaxY()) / 2, (result.getMinX() + result.getMaxX()) / 2);
CoordinateConversion conversion = new ScaleConversion(result.getMinX(), result.getMinY(), scale, scale);
result.convertCoordinates(conversion);
return result;
}
public static Document stringParseXML(String xml, boolean deleteNS) throws Exception
{
// remove beginning to '<' character
int iPosBegin = xml.indexOf('<');
if (iPosBegin > 0)
{
xml = xml.substring(iPosBegin);
}
// 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' encoding='ISO-8859-15'?>" + 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);
return document;
}
@Test
public void testGetFilterClassName() throws Exception
{
// Setup fixture.
final Document webXml = WebXmlUtils.asDocument( new File( WebXmlUtilsTest.class.getResource( "/org/jivesoftware/util/test-web.xml" ).toURI() ) );
final String filterName = "Set Character Encoding";
// Execute system under test.
final String result = WebXmlUtils.getFilterClassName( webXml, filterName );
// Verify result.
assertEquals( "org.jivesoftware.util.SetCharacterEncodingFilter", result );
}
public void loadXml(InputStream inputStream) throws Exception {
try {
Document document = (new SAXReader()).read(inputStream);
loadXml(document.getRootElement());
} catch (DocumentException e) {
fatal("Unable to parse given XML, reason:"+e.getMessage(), e);
}
}
private static Set<String> getUrlPatterns( String type, Document webXml, String typeName )
{
final Set<String> result = new HashSet<>();
final List<Element> elements = webXml.getRootElement().elements( type + "-mapping" ); // all elements of 'type'-mapping (filter-mapping or servlet-mapping).
for ( final Element element : elements )
{
final String name = element.elementTextTrim( type + "-name" );
if ( typeName.equals( name ) )
{
final List<Element> urlPatternElements = element.elements( "url-pattern" );
for ( final Element urlPatternElement : urlPatternElements )
{
final String urlPattern = urlPatternElement.getTextTrim();
if ( urlPattern != null )
{
result.add( urlPattern );
}
}
// A filter can also be mapped to a servlet (by name). In that case, all url-patterns of the corresponding servlet-mapping should be used.
if ( "filter".equals( type ) )
{
final List<Element> servletNameElements = element.elements( "servlet-name" );
for ( final Element servletNameElement : servletNameElements )
{
final String servletName = servletNameElement.getTextTrim();
if ( servletName != null )
{
result.addAll( getUrlPatterns( "servlet", webXml, servletName ) );
}
}
}
break;
}
}
return result;
}
public static Element newXmlSchema(final String targetNamespace) {
final Document document = DocumentHelper.createDocument();
final Element schema = document.addElement(XML_SCHEMA_PREFIX + ":schema", XML_SCHEMA_NS);
if (!StringUtils.isEmpty(targetNamespace)) {
schema.addAttribute("targetNamespace", targetNamespace);
}
return schema;
}
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) {
File file = promptForFile(exportInteraction, fileFilter);
if (file == null) {
//the user canceled.
return;
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
return;
}
try {
XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
Element rootElement = settingsNode.getElement();
rootElement.detach();
Document document = DocumentHelper.createDocument(rootElement);
xmlWriter.write(document);
} catch (Throwable t) {
LOGGER.error("Internal error. Failed to save.", t);
exportInteraction.reportError("Internal error. Failed to save.");
} finally {
closeQuietly(fileOutputStream);
}
}