Java Code Examples for org.dom4j.Document

The following examples show how to use org.dom4j.Document. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: gemfirexd-oss   Source File: TestSummaryCreatorTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 2
Source Project: olat   Source File: FilePersister.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Source Project: java-technology-stack   Source File: OptionsTagTests.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 4
Source Project: olat   Source File: SurveyFileResourceValidator.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source Project: bulbasaur   Source File: TaskTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 6
Source Project: studio   Source File: CmisServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: ApkCustomizationTool   Source File: Command.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 修改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();
    }
}
 
Example 8
Source Project: gocd   Source File: StageXmlRepresenterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 9
Source Project: Openfire   Source File: VCardTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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() );
}
 
Example 10
Source Project: fixflow   Source File: SvgAnnotationComponent.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 11
Source Project: MicroCommunity   Source File: PaymentFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source Project: spring-analysis-note   Source File: CheckboxTagTests.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 13
Source Project: olat   Source File: QTIObjectTreeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
* 
*
*/
  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;
  }
 
Example 14
Source Project: cuba   Source File: FilterParserImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source Project: Whack   Source File: ComponentFinder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 16
Source Project: Openfire   Source File: XMPPPacketReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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" ) );
}
 
Example 17
Source Project: liteFlow   Source File: Dom4JReader.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 18
/**
 * 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;
}
 
Example 19
Source Project: boubei-tss   Source File: RemoteArticleService.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 20
/**
   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;
    }
}
 
Example 21
Source Project: mts   Source File: ASNReferenceFinder.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 22
Source Project: unitime   Source File: CurriculumClassification.java    License: Apache License 2.0 5 votes vote down vote up
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;
	}
}
 
Example 23
Source Project: syndesis   Source File: XmlSchemaHelper.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 24
@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;
}
 
Example 25
Source Project: mts   Source File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 26
Source Project: Openfire   Source File: WebXmlUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 );
}
 
Example 27
Source Project: unitime   Source File: BaseImport.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 28
Source Project: Openfire   Source File: WebXmlUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 29
Source Project: syndesis   Source File: XmlSchemaHelper.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 30
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);
    }
}