java.beans.PropertyEditorSupport#org.dom4j.Document源码实例Demo

下面列出了java.beans.PropertyEditorSupport#org.dom4j.Document 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: gemfirexd-oss   文件: TestSummaryCreatorTask.java
/**
 * 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;
    }
}
 
源代码2 项目: olat   文件: FilePersister.java
/**
 * 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);
    }
}
 
源代码3 项目: java-technology-stack   文件: OptionsTagTests.java
@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());
}
 
源代码4 项目: olat   文件: SurveyFileResourceValidator.java
@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;
}
 
源代码5 项目: bulbasaur   文件: TaskTest.java
@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);
}
 
源代码6 项目: studio   文件: CmisServiceImpl.java
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;
}
 
源代码7 项目: ApkCustomizationTool   文件: Command.java
/**
 * 修改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();
    }
}
 
源代码8 项目: gocd   文件: StageXmlRepresenterTest.java
@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();
}
 
源代码9 项目: Openfire   文件: VCardTest.java
/**
 * 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() );
}
 
源代码10 项目: fixflow   文件: SvgAnnotationComponent.java
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;
}
 
源代码11 项目: MicroCommunity   文件: PaymentFactory.java
/**
 * 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;
}
 
源代码12 项目: spring-analysis-note   文件: CheckboxTagTests.java
@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());
}
 
源代码13 项目: olat   文件: QTIObjectTreeBuilder.java
/**
* 
*
*/
  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;
  }
 
源代码14 项目: cuba   文件: FilterParserImpl.java
/**
 * 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;
}
 
源代码15 项目: Whack   文件: ComponentFinder.java
/**
 * 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;
}
 
源代码16 项目: Openfire   文件: XMPPPacketReaderTest.java
/**
 * 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" ) );
}
 
源代码17 项目: liteFlow   文件: Dom4JReader.java
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;
}
 
源代码19 项目: boubei-tss   文件: RemoteArticleService.java
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();
}
 
源代码20 项目: rcrs-server   文件: ScenarioEditor.java
/**
   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;
    }
}
 
源代码21 项目: mts   文件: ASNReferenceFinder.java
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;
}
 
源代码22 项目: unitime   文件: CurriculumClassification.java
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;
	}
}
 
源代码23 项目: syndesis   文件: XmlSchemaHelper.java
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;
}
 
源代码25 项目: mts   文件: Utils.java
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;
}
 
源代码26 项目: Openfire   文件: WebXmlUtilsTest.java
@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 );
}
 
源代码27 项目: unitime   文件: BaseImport.java
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);
    }
}
 
源代码28 项目: Openfire   文件: WebXmlUtils.java
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;
}
 
源代码29 项目: syndesis   文件: XmlSchemaHelper.java
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;
}
 
源代码30 项目: Pushjet-Android   文件: DOM4JSerializer.java
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);
    }
}