org.jdom.input.SAXBuilder

Here are the examples of the java api class org.jdom.input.SAXBuilder taken from open source projects.

1. SlackNotificationListenerTest#getElement()

Project: tcSlackBuildNotifier
File: SlackNotificationListenerTest.java
private Element getElement(String filePath) {
    SAXBuilder builder = new SAXBuilder();
    builder.setIgnoringElementContentWhitespace(true);
    try {
        Document doc = builder.build(filePath);
        return doc.getRootElement();
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

2. SlackNotificationMainSettingsTest#getElement()

Project: tcSlackBuildNotifier
File: SlackNotificationMainSettingsTest.java
private Element getElement(String filePath) {
    SAXBuilder builder = new SAXBuilder();
    builder.setIgnoringElementContentWhitespace(true);
    try {
        Document doc = builder.build(filePath);
        return doc.getRootElement();
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

3. ModelGen#loadXml()

Project: intellij-community
File: ModelGen.java
public static Element loadXml(File configXml) throws Exception {
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setEntityResolver(new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            return new InputSource(new CharArrayReader(new char[0]));
        }
    });
    final Document document = saxBuilder.build(configXml);
    return document.getRootElement();
}

4. StoreDefinitionsMapper#readStore()

Project: voldemort
File: StoreDefinitionsMapper.java
public static StoreDefinition readStore(Reader input) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document doc = builder.build(input);
        Element root = doc.getRootElement();
        return readStore(root);
    } catch (JDOMException e) {
        throw new MappingException(e);
    } catch (IOException e) {
        throw new MappingException(e);
    }
}

5. RestUtils#parseSerializerDefinition()

Project: voldemort
File: RestUtils.java
private static SerializerDefinition parseSerializerDefinition(String serializerInfoXml, String elementName) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document doc = builder.build(new StringReader(serializerInfoXml));
        Element root = doc.getRootElement();
        Element serializerElement = root.getChild(elementName);
        return StoreDefinitionsMapper.readSerializer(serializerElement);
    } catch (JDOMException e) {
        throw new MappingException(e);
    } catch (IOException e) {
        throw new MappingException(e);
    }
}

6. XmlToPlainText#convert()

Project: spacewalk
File: XmlToPlainText.java
/**
     * Converts an xml/html snippet to a plain text string..
     * @param snippet the xml snippet to convert..
     * @return returns the converted plain text or
     *           the orignal xml in the case of an error.
     */
public String convert(String snippet) {
    String xmlSnippet = "<foo>" + snippet + "</foo>";
    plainText = new StringBuilder();
    SAXBuilder builder = new SAXBuilder();
    try {
        Document doc = builder.build(new StringReader(xmlSnippet));
        toPlainText(doc);
        return plainText.toString();
    } catch (JDOMException e) {
        log.warn("Couldn't parse the snippet -> [" + snippet + "]", e);
    } catch (IOException e) {
        log.warn("Couldn't parse the snippet -> [" + snippet + "]", e);
    }
    return snippet;
}

7. StaticWithJdomTest#test()

Project: powermock
File: StaticWithJdomTest.java
@org.junit.Test
public void test() throws Exception {
    PowerMock.mockStatic(StaticClass.class);
    EasyMock.expect(StaticClass.staticMethod()).andReturn(2).anyTimes();
    PowerMock.replay(StaticClass.class);
    int i = StaticClass.staticMethod();
    String xml = "<xml>" + i + "</xml>";
    SAXBuilder b = new SAXBuilder();
    Document d = b.build(new StringReader(xml));
    Assert.assertTrue(d.getRootElement().getText().equals("2"));
    PowerMock.verify(StaticClass.class);
}

8. XmlUtils#getRootAttribute()

Project: oozie
File: XmlUtils.java
/**
     * //TODO move this to action registry method Return the value of an attribute from the root element of an XML
     * document.
     *
     * @param filePath path of the XML document.
     * @param attributeName attribute to retrieve value for.
     * @return value of the specified attribute.
     */
public static String getRootAttribute(String filePath, String attributeName) {
    ParamChecker.notNull(filePath, "filePath");
    ParamChecker.notNull(attributeName, "attributeName");
    SAXBuilder saxBuilder = createSAXBuilder();
    try {
        Document doc = saxBuilder.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath));
        return doc.getRootElement().getAttributeValue(attributeName);
    } catch (JDOMException e) {
        throw new RuntimeException();
    } catch (IOException e) {
        throw new RuntimeException();
    }
}

9. EffectivePomMojo#prettyFormat()

Project: maven-plugins
File: EffectivePomMojo.java
/**
     * @param effectivePom not null
     * @return pretty format of the xml  or the original <code>effectivePom</code> if an error occurred.
     */
private static String prettyFormat(String effectivePom) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document effectiveDocument = builder.build(new StringReader(effectivePom));
        StringWriter w = new StringWriter();
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(effectiveDocument, w);
        return w.toString();
    } catch (JDOMException e) {
        return effectivePom;
    } catch (IOException e) {
        return effectivePom;
    }
}

10. LyricsService#parseSearchResult()

Project: libresonic
File: LyricsService.java
private LyricsInfo parseSearchResult(String xml) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new StringReader(xml));
    Element root = document.getRootElement();
    Namespace ns = root.getNamespace();
    String lyric = StringUtils.trimToNull(root.getChildText("Lyric", ns));
    String song = root.getChildText("LyricSong", ns);
    String artist = root.getChildText("LyricArtist", ns);
    return new LyricsInfo(lyric, artist, song);
}

11. JDOMUtil#getSaxBuilder()

Project: intellij-community
File: JDOMUtil.java
private static SAXBuilder getSaxBuilder() {
    SoftReference<SAXBuilder> reference = ourSaxBuilder.get();
    SAXBuilder saxBuilder = com.intellij.reference.SoftReference.dereference(reference);
    if (saxBuilder == null) {
        saxBuilder = new SAXBuilder();
        saxBuilder.setEntityResolver(new EntityResolver() {

            @Override
            @NotNull
            public InputSource resolveEntity(String publicId, String systemId) {
                return new InputSource(new CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY));
            }
        });
        ourSaxBuilder.set(new SoftReference<SAXBuilder>(saxBuilder));
    }
    return saxBuilder;
}

12. FileOpenRecentMenuAction#loadRecent()

Project: incubator-taverna-workbench
File: FileOpenRecentMenuAction.java
private void loadRecent(File recentFile) throws FileNotFoundException, IOException, JDOMException {
    SAXBuilder builder = new SAXBuilder();
    @SuppressWarnings("unused") Document document;
    try (InputStream fileInputStream = new BufferedInputStream(new FileInputStream(recentFile))) {
        document = builder.build(fileInputStream);
    }
    synchronized (recents) {
        recents.clear();
        //RecentDeserializer deserialiser = new RecentDeserializer();
        try {
        // recents.addAll(deserialiser.deserializeRecent(document
        // .getRootElement()));
        } catch (Exception e) {
            logger.warn("Could not read recent workflows from file " + recentFile, e);
        }
    }
}

13. XMLUtilities#getDOMDocument()

Project: incubator-taverna-plugin-bioinformatics
File: XMLUtilities.java
/**
	 *
	 * @param document
	 *            the string to create a DOM document from
	 * @return a Document object that represents the string of XML.
	 * @throws MobyException
	 *             if the xml is invalid syntatically.
	 */
public static Document getDOMDocument(String document) throws MobyException {
    if (document == null)
        throw new MobyException(newline + "null found where an XML document was expected.");
    SAXBuilder builder = new SAXBuilder();
    // Create the document
    Document doc = null;
    try {
        doc = builder.build(new StringReader(document));
    } catch (JDOMException e) {
        throw new MobyException(newline + "Error parsing XML:->" + newline + document + newline + Utils.format(e.getLocalizedMessage(), 3) + ".");
    } catch (IOException e) {
        throw new MobyException(newline + "Error parsing XML:->" + newline + Utils.format(e.getLocalizedMessage(), 3) + ".");
    } catch (Exception e) {
        throw new MobyException(newline + "Error parsing XML:->" + newline + Utils.format(e.getLocalizedMessage(), 3) + ".");
    }
    return doc;
}

14. BiomartActivity#configure()

Project: incubator-taverna-plugin-bioinformatics
File: BiomartActivity.java
@Override
public void configure(JsonNode json) throws ActivityConfigurationException {
    this.json = json;
    String martQueryText = json.get("martQuery").asText();
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = builder.build(new StringReader(martQueryText));
        biomartQuery = MartServiceXMLHandler.elementToMartQuery(document.getRootElement(), null);
    } catch (JDOMExceptionIOException |  e) {
        throw new ActivityConfigurationException(e);
    }
}

15. DataManagementToolTest#prettyXmlPrint()

Project: continuum
File: DataManagementToolTest.java
public String prettyXmlPrint(String xml) throws Exception {
    SAXBuilder saxBuilder = new SAXBuilder();
    Document document = saxBuilder.build(new StringReader(xml));
    XMLOutputter outp = new XMLOutputter();
    outp.setFormat(Format.getPrettyFormat());
    StringWriter sw = new StringWriter();
    outp.output(document, sw);
    return sw.getBuffer().toString();
}

16. JDOMUtil#getSaxBuilder()

Project: consulo
File: JDOMUtil.java
private static SAXBuilder getSaxBuilder() {
    SoftReference<SAXBuilder> reference = ourSaxBuilder.get();
    SAXBuilder saxBuilder = com.intellij.reference.SoftReference.dereference(reference);
    if (saxBuilder == null) {
        saxBuilder = new SAXBuilder();
        saxBuilder.setEntityResolver(new EntityResolver() {

            @Override
            @NotNull
            public InputSource resolveEntity(String publicId, String systemId) {
                return new InputSource(new CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY));
            }
        });
        ourSaxBuilder.set(new SoftReference<SAXBuilder>(saxBuilder));
    }
    return saxBuilder;
}

17. DefaultSaxParserImpl#getBuilder()

Project: RSSOwl
File: DefaultSaxParserImpl.java
private SAXBuilder getBuilder() {
    SAXBuilder builder = new SAXBuilder();
    /* Support Java Encoding Names */
    builder.setFeature(ALLOW_JAVA_ENCODINGS, true);
    /* Custom Entitiy Resolution */
    builder.setEntityResolver(new EntityResolver2() {

        /*
       * @see
       * org.xml.sax.ext.EntityResolver2#getExternalSubset(java.lang.String,
       * java.lang.String)
       */
        public InputSource getExternalSubset(String name, String baseURI) {
            return new InputSource(getClass().getResourceAsStream(DEFAULT_DTD));
        }

        /*
       * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,
       * java.lang.String)
       */
        public InputSource resolveEntity(String publicId, String systemId) {
            return resolveEntity(null, publicId, null, systemId);
        }

        /*
       * @see org.xml.sax.ext.EntityResolver2#resolveEntity(java.lang.String,
       * java.lang.String, java.lang.String, java.lang.String)
       */
        public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) {
            return new InputSource(getClass().getResourceAsStream(DEFAULT_DTD));
        }
    });
    return builder;
}

18. JDomDriver#createBuilder()

Project: xstream
File: JDomDriver.java
/**
     * Create and initialize the SAX builder.
     * 
     * @return the SAX builder instance.
     * @since 1.4.9
     */
protected SAXBuilder createBuilder() {
    final SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    return builder;
}

19. ConfigLoaderUtil#getFullConfigElement()

Project: tcSlackBuildNotifier
File: ConfigLoaderUtil.java
public static Element getFullConfigElement(File file) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    builder.setIgnoringElementContentWhitespace(true);
    Document doc = builder.build(file);
    return doc.getRootElement();
}

20. SlackNotificationSettingsTest#test_ReadXml()

Project: tcSlackBuildNotifier
File: SlackNotificationSettingsTest.java
@SuppressWarnings("unchecked")
@Test
public void test_ReadXml() throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    //builder.setValidation(true);
    builder.setIgnoringElementContentWhitespace(true);
    Document doc = builder.build("src/test/resources/testdoc1.xml");
    Element root = doc.getRootElement();
    System.out.println(root.toString());
    if (root.getChild("slackNotifications") != null) {
        Element child = root.getChild("slackNotifications");
        if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))) {
            List<Element> namedChildren = child.getChildren("slackNotification");
            for (Iterator<Element> i = namedChildren.iterator(); i.hasNext(); ) {
                Element e = i.next();
                System.out.println(e.toString() + e.getAttributeValue("url"));
                //assertTrue(e.getAttributeValue("url").equals("http://something"));
                if (e.getChild("parameters") != null) {
                    Element eParams = e.getChild("parameters");
                    List<Element> paramsList = eParams.getChildren("param");
                    for (Iterator<Element> j = paramsList.iterator(); j.hasNext(); ) {
                        Element eParam = j.next();
                        System.out.println(eParam.toString() + eParam.getAttributeValue("name"));
                        System.out.println(eParam.toString() + eParam.getAttributeValue("value"));
                    }
                }
            }
        }
    }
}

21. SlackNotificationSettingsTest#test_WebookConfig()

Project: tcSlackBuildNotifier
File: SlackNotificationSettingsTest.java
/*
    @Ignore
	@Test
	public void test_AuthPassNoCredsUsingProxyFromConfig() throws FileNotFoundException, IOException, InterruptedException {
		SlackNotificationTest test = new SlackNotificationTest();
		SlackNotificationMainConfig mainConfig = new SlackNotificationMainConfig();
		mainConfig.setProxyHost(test.proxy);
		mainConfig.setProxyPort(test.proxyPort);
		mainConfig.setProxyShortNames(true);
		String url = "http://" + test.webserverHost + ":" + test.webserverPort + "/200";
		SlackNotification w = new SlackNotificationImpl(url, mainConfig.getProxyConfigForUrl(url));
		SlackNotificationTestServer s = test.startWebServer();
		SlackNotificationTestProxyServer p = test.startProxyServer();
		w.setEnabled(true);
		w.post();
		test.stopWebServer(s);
		test.stopProxyServer(p);
		assertTrue(w.getStatus() == HttpStatus.SC_OK);
	}
	*/
@SuppressWarnings("unchecked")
@Test
public void test_WebookConfig() throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    List<SlackNotificationConfig> configs = new ArrayList<SlackNotificationConfig>();
    builder.setIgnoringElementContentWhitespace(true);
    Document doc = builder.build("src/test/resources/testdoc2.xml");
    Element root = doc.getRootElement();
    if (root.getChild("slackNotifications") != null) {
        Element child = root.getChild("slackNotifications");
        if ((child.getAttribute("enabled") != null) && (child.getAttribute("enabled").equals("true"))) {
            List<Element> namedChildren = child.getChildren("slackNotification");
            for (Iterator<Element> i = namedChildren.iterator(); i.hasNext(); ) {
                Element e = i.next();
                SlackNotificationConfig whConfig = new SlackNotificationConfig(e);
                configs.add(whConfig);
            }
        }
    }
    for (SlackNotificationConfig c : configs) {
        SlackNotification wh = new SlackNotificationImpl(c.getChannel());
        wh.setEnabled(c.getEnabled());
        //slackNotification.addParams(c.getParams());
        System.out.println(wh.getChannel());
        System.out.println(wh.isEnabled().toString());
    }
}

22. XmlUtils#createSAXBuilder()

Project: oozie
File: XmlUtils.java
private static SAXBuilder createSAXBuilder() {
    SAXBuilder saxBuilder = new SAXBuilder();
    //THIS IS NOT WORKING
    //saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false);
    //INSTEAD WE ARE JUST SETTING AN EntityResolver that does not resolve entities
    saxBuilder.setEntityResolver(new NoExternalEntityEntityResolver());
    return saxBuilder;
}

23. FunctionalTestCase#responseXmlDocument()

Project: jsunit
File: FunctionalTestCase.java
protected Document responseXmlDocument() throws JDOMException, IOException {
    String responseXml = webTester.getDialog().getResponseText();
    SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
    Reader stringReader = new StringReader(responseXml);
    return saxBuilder.build(stringReader);
}

24. ContentMatcher#loadXMLPatternDefinitions()

Project: zaproxy
File: ContentMatcher.java
/**
     * Load a pattern list from an XML formatted file.
     * Pattern should be enclosed around a <Patterns> tag and should be
     * defined as <Pattern type="xxx"></Pattern>. Use "regex" to define
     * a Regex formatted pattern or "string" for an exact matching pattern.
     */
protected void loadXMLPatternDefinitions(InputStream xmlInputStream) throws JDOMException, IOException {
    strings = new ArrayList<BoyerMooreMatcher>();
    patterns = new ArrayList<Pattern>();
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(xmlInputStream);
    Element el = doc.getRootElement();
    String value;
    // go ahead for boundaries and tests
    for (Object obj : el.getChildren(TAG_PATTERN)) {
        el = (Element) obj;
        value = el.getText();
        // Check if the pattern has been set to null
        if (value != null && !value.isEmpty()) {
            // Check if a regex expression has been set
            if (el.getAttributeValue(TAG_PATTERN_TYPE).equalsIgnoreCase(TAG_PATTERN_TYPE_REGEX)) {
                patterns.add(Pattern.compile(el.getText()));
            // Otherwise it's by default an exact match model
            } else {
                strings.add(new BoyerMooreMatcher(el.getText()));
            }
        }
    }
}

25. MockTester#parse()

Project: tapestry4
File: MockTester.java
private void parse() throws JDOMException, DocumentParseException, IOException {
    SAXBuilder builder = new SAXBuilder();
    _document = builder.build(_path);
}

26. MockTester#parse()

Project: tapestry3
File: MockTester.java
private void parse() throws JDOMException, DocumentParseException, IOException {
    SAXBuilder builder = new SAXBuilder();
    _document = builder.build(_path);
}

27. SchemaParser#parseSchema()

Project: spacewalk
File: SchemaParser.java
/**
     * <p>
     *  This will do the work of parsing the schema.
     * </p>
     *
     * @throws IOException - when parsing errors occur.
     */
private void parseSchema() throws IOException {
    /**
         * Create builder to generate JDOM representation of XML Schema,
         *   without validation and using Apache Xerces.
         */
    // XXX: Allow validation, and allow alternate parsers
    SAXBuilder builder = new SAXBuilder();
    try {
        Document schemaDoc = builder.build(schemaURL);
        // Handle attributes
        List attributes = schemaDoc.getRootElement().getChildren("attribute", schemaNamespace);
        for (Iterator i = attributes.iterator(); i.hasNext(); ) {
            // Iterate and handle
            Element attribute = (Element) i.next();
            handleAttribute(attribute);
        }
    // Handle attributes nested within complex types
    } catch (JDOMException e) {
        throw new IOException(e.getMessage());
    }
}

28. DefaultSaxParserImpl#parse()

Project: RSSOwl
File: DefaultSaxParserImpl.java
/*
   * @see org.rssowl.core.interpreter.IXMLParser#parse(java.io.InputStream,
   * java.util.Map)
   */
public Document parse(InputStream inS, Map<Object, Object> properties) throws ParserException {
    Document document = null;
    Exception ex = null;
    SAXBuilder builder = getBuilder();
    boolean encodingIssue = false;
    boolean usePlatformEncoding = (properties != null && properties.containsKey(DefaultProtocolHandler.USE_PLATFORM_ENCODING));
    /* Set a Mark to support a 2d Run */
    KeepAliveInputStream keepAliveIns = new KeepAliveInputStream(inS);
    keepAliveIns.mark(0);
    /* First Run */
    try {
        if (!usePlatformEncoding)
            document = builder.build(keepAliveIns);
        else
            document = builder.build(new InputStreamReader(keepAliveIns));
    } catch (JDOMException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    }
    /* Second Run - Try with Platform Default Encoding from existing Stream */
    if (!usePlatformEncoding && isEncodingIssue(ex)) {
        encodingIssue = true;
        /* Try to reset the Stream to 0 */
        boolean reset = false;
        try {
            keepAliveIns.reset();
            reset = true;
        } catch (IOException e) {
        }
        /* In case reset-operation was successfull */
        if (reset) {
            try {
                document = builder.build(new InputStreamReader(keepAliveIns));
            } catch (JDOMException e) {
                ex = e;
            } catch (IOException e) {
                ex = e;
            }
        }
    }
    /* Close Stream */
    try {
        if (ex != null && inS instanceof IAbortable)
            ((IAbortable) inS).abort();
        else
            keepAliveIns.reallyClose();
    } catch (IOException e) {
        ex = e;
    }
    /* In case of an exception */
    if (ex != null && document == null && Activator.getDefault() != null) {
        if (!usePlatformEncoding && encodingIssue)
            throw new EncodingException(Activator.getDefault().createErrorStatus(ex.getMessage(), ex));
        throw new ParserException(Activator.getDefault().createErrorStatus(ex.getMessage(), ex));
    }
    /* Return Document */
    return document;
}

29. XmlUtils#parseXml()

Project: oozie
File: XmlUtils.java
/**
     * Parse a inputstream assuming it is a valid XML document and return an JDOM Element for it.
     *
     * @param is inputstream to parse.
     * @return JDOM element for the parsed XML string.
     * @throws JDOMException thrown if an error happend while XML parsing.
     * @throws IOException thrown if an IO error occurred.
     */
public static Element parseXml(InputStream is) throws JDOMException, IOException {
    ParamChecker.notNull(is, "is");
    SAXBuilder saxBuilder = createSAXBuilder();
    Document document = saxBuilder.build(is);
    return document.getRootElement();
}

30. AbstractEffectiveMojo#addMavenNamespace()

Project: maven-plugins
File: AbstractEffectiveMojo.java
/**
     * Add a Pom/Settings namespaces to the effective XML content.
     *
     * @param effectiveXml not null the effective POM or Settings
     * @param isPom if <code>true</code> add the Pom xsd url, otherwise add the settings xsd url.
     * @return the content of the root element, i.e. <project/> or <settings/> with the Maven namespace or
     *         the original <code>effective</code> if an error occurred.
     * @see #POM_XSD_URL
     * @see #SETTINGS_XSD_URL
     */
protected static String addMavenNamespace(String effectiveXml, boolean isPom) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = builder.build(new StringReader(effectiveXml));
        Element rootElement = document.getRootElement();
        // added namespaces
        Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/4.0.0");
        rootElement.setNamespace(pomNamespace);
        Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.addNamespaceDeclaration(xsiNamespace);
        if (rootElement.getAttribute("schemaLocation", xsiNamespace) == null) {
            rootElement.setAttribute("schemaLocation", "http://maven.apache.org/POM/4.0.0 " + (isPom ? POM_XSD_URL : SETTINGS_XSD_URL), xsiNamespace);
        }
        ElementFilter elementFilter = new ElementFilter(Namespace.getNamespace(""));
        for (Iterator<?> i = rootElement.getDescendants(elementFilter); i.hasNext(); ) {
            Element e = (Element) i.next();
            e.setNamespace(pomNamespace);
        }
        StringWriter w = new StringWriter();
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(document.getRootElement(), w);
        return w.toString();
    } catch (JDOMException e) {
        return effectiveXml;
    } catch (IOException e) {
        return effectiveXml;
    }
}

31. EclipseWtpComponent15WriterTest#testWriteEjbComponentMECLIPSE455()

Project: maven-plugins
File: EclipseWtpComponent15WriterTest.java
/**
     * Tests the creation of the ejb module references in the org.eclipse.wst.common.component file for:
     * <ul>
     * <li>component file of EAR
     * <li>WTP 1.5
     * <li>dep is referenced project
     * </ul>
     * The archivename is expected to be jar - independent from the packaging (ejb).
     * 
     * @throws MojoExecutionException Exception
     * @throws IOException Exception
     * @throws JDOMException Exception
     */
public void testWriteEjbComponentMECLIPSE455() throws MojoExecutionException, IOException, JDOMException {
    TestEclipseWriterConfig config = new TestEclipseWriterConfig();
    config.setWtpVersion(1.5f);
    config.setEclipseProjectName("test-project");
    File basedir = fileManager.createTempDir();
    File pom = new File(basedir, "pom.xml");
    pom.createNewFile();
    MavenProject project = new MavenProject();
    project.setFile(pom);
    config.setProject(project);
    config.setProjectBaseDir(basedir);
    config.setEclipseProjectDirectory(basedir);
    config.setPackaging("ear");
    // add an ejb3 and ejb packaged dependency
    config.setDeps(new IdeDependency[] { createDep("ejb"), createDep("jar") });
    EclipseWtpComponentWriter lWriter = new EclipseWtpComponent15Writer();
    Log log = new TestLog();
    lWriter.init(log, config);
    lWriter.write();
    // now check extension of archivenames to be jar
    SAXBuilder builder = new SAXBuilder(false);
    Document doc = builder.build(new File(basedir, ".settings/org.eclipse.wst.common.component"));
    XPath archiveNames = XPath.newInstance("//dependent-module/@archiveName");
    assertEquals("Must be 2 modules", 2, archiveNames.selectNodes(doc).size());
    for (Object o : archiveNames.selectNodes(doc)) {
        Attribute attribute = (Attribute) o;
        String archiveName = attribute.getValue();
        String extension = archiveName.substring(archiveName.lastIndexOf(".") + 1).toLowerCase();
        assertEquals("Must be of type jar", "jar", extension);
    }
}

32. EclipseClasspathWriterUnitTest#testWrite_ShouldGenerateValidJavadocURLs()

Project: maven-plugins
File: EclipseClasspathWriterUnitTest.java
public void testWrite_ShouldGenerateValidJavadocURLs() throws MojoExecutionException, JDOMException, IOException {
    TestEclipseWriterConfig config = new TestEclipseWriterConfig();
    File basedir = fileManager.createTempDir();
    File repoDir = new File(basedir, "repo");
    config.setLocalRepository(new StubArtifactRepository(repoDir.getPath()));
    config.setProjectBaseDir(basedir);
    config.setEclipseProjectDirectory(basedir);
    String baseOutputDir = "target/classes";
    String maskedOutputDir = "target/classes/main-resources";
    File buildOutputDir = new File(basedir, baseOutputDir);
    buildOutputDir.mkdirs();
    config.setBuildOutputDirectory(buildOutputDir);
    new File(basedir, maskedOutputDir).mkdirs();
    config.setEclipseProjectName("test-project");
    IdeDependency dependency = new IdeDependency();
    dependency.setFile(new File(repoDir, "g/a/v/a-v.jar"));
    dependency.setGroupId("g");
    dependency.setArtifactId("a");
    dependency.setVersion("v");
    dependency.setAddedToClasspath(true);
    dependency.setJavadocAttachment(new File(System.getProperty("user.home"), ".m2/some.jar"));
    config.setDeps(new IdeDependency[] { dependency });
    TestLog log = new TestLog();
    EclipseClasspathWriter classpathWriter = new EclipseClasspathWriter();
    classpathWriter.init(log, config);
    classpathWriter.write();
    SAXBuilder builder = new SAXBuilder(false);
    Document doc = builder.build(new File(basedir, ".classpath"));
    XPath javadocUrls = XPath.newInstance("//attribute/@value");
    for (Object o : javadocUrls.selectNodes(doc)) {
        Attribute attribute = (Attribute) o;
        URL jarUrl = new URL(attribute.getValue());
        URL fileUrl = ((JarURLConnection) jarUrl.openConnection()).getJarFileURL();
        String host = fileUrl.getHost();
        assertTrue("Unexpected host: \"" + host + "\"", "".equals(host) || "localhost".equals(host));
    }
}

33. EclipseClasspathWriterUnitTest#testWrite_ShouldMaskOutputDirsNestedWithinAnExistingOutputDir()

Project: maven-plugins
File: EclipseClasspathWriterUnitTest.java
public void testWrite_ShouldMaskOutputDirsNestedWithinAnExistingOutputDir() throws MojoExecutionException, JDOMException, IOException {
    TestEclipseWriterConfig config = new TestEclipseWriterConfig();
    File basedir = fileManager.createTempDir();
    config.setProjectBaseDir(basedir);
    config.setEclipseProjectDirectory(basedir);
    String baseOutputDir = "target/classes";
    String maskedOutputDir = "target/classes/main-resources";
    File buildOutputDir = new File(basedir, baseOutputDir);
    buildOutputDir.mkdirs();
    config.setBuildOutputDirectory(buildOutputDir);
    new File(basedir, maskedOutputDir).mkdirs();
    EclipseSourceDir dir = new EclipseSourceDir("src/main/resources", "target/classes", true, false, null, null, false);
    EclipseSourceDir testDir = new EclipseSourceDir("src\\test\\resources", "target/classes/test-resources", true, true, null, null, false);
    EclipseSourceDir[] dirs = { dir, testDir };
    config.setSourceDirs(dirs);
    config.setEclipseProjectName("test-project");
    TestLog log = new TestLog();
    EclipseClasspathWriter classpathWriter = new EclipseClasspathWriter();
    classpathWriter.init(log, config);
    classpathWriter.write();
    SAXBuilder builder = new SAXBuilder(false);
    Document doc = builder.build(new File(basedir, ".classpath"));
    XPath resourcePath = XPath.newInstance("//classpathentry[@path='src/main/resources']");
    assertTrue("resources classpath entry not found.", resourcePath.selectSingleNode(doc) != null);
    XPath testResourcePath = XPath.newInstance("//classpathentry[@path='src/test/resources']");
    assertTrue("test resources (minus custom output dir) classpath entry not found.", testResourcePath.selectSingleNode(doc) != null);
    XPath stdOutputPath = XPath.newInstance("//classpathentry[@kind='output' && @path='target/classes']");
    assertTrue("standard output classpath entry not found.", stdOutputPath.selectSingleNode(doc) != null);
}

34. ComponentsXmlArchiverFileFilterTest#testAddToArchive_ShouldWriteTwoComponentToArchivedFile()

Project: maven-plugins
File: ComponentsXmlArchiverFileFilterTest.java
public void testAddToArchive_ShouldWriteTwoComponentToArchivedFile() throws IOException, ArchiverException, JDOMException {
    filter.components = new LinkedHashMap<String, Xpp3Dom>();
    final Xpp3Dom dom = createComponentDom(new ComponentDef("role", "hint", "impl"));
    filter.components.put("rolehint", dom);
    final Xpp3Dom dom2 = createComponentDom(new ComponentDef("role", "hint2", "impl"));
    filter.components.put("rolehint2", dom2);
    final ZipArchiver archiver = new ZipArchiver();
    final File archiveFile = fileManager.createTempFile();
    archiver.setDestFile(archiveFile);
    final File descriptorFile = fileManager.createTempFile();
    archiver.setArchiveFinalizers(Collections.<ArchiveFinalizer>singletonList(filter));
    archiver.createArchive();
    ZipFile zf = null;
    FileOutputStream out = null;
    try {
        zf = new ZipFile(archiveFile);
        final ZipEntry ze = zf.getEntry(ComponentsXmlArchiverFileFilter.COMPONENTS_XML_PATH);
        assertNotNull(ze);
        out = new FileOutputStream(descriptorFile);
        IOUtil.copy(zf.getInputStream(ze), out);
        out.close();
        out = null;
        zf.close();
        zf = null;
    } finally {
        IOUtil.close(out);
        try {
            if (zf != null) {
                zf.close();
            }
        } catch (final IOException e) {
        }
    }
    final SAXBuilder builder = new SAXBuilder(false);
    final Document doc = builder.build(descriptorFile);
    final XPath role = XPath.newInstance("//component[position()=1]/role/text()");
    final XPath hint = XPath.newInstance("//component[position()=1]/role-hint/text()");
    final XPath implementation = XPath.newInstance("//component[position()=1]/implementation/text()");
    assertEquals("role", ((Text) role.selectSingleNode(doc)).getText());
    assertEquals("hint", ((Text) hint.selectSingleNode(doc)).getText());
    assertEquals("impl", ((Text) implementation.selectSingleNode(doc)).getText());
    final XPath role2 = XPath.newInstance("//component[position()=2]/role/text()");
    final XPath hint2 = XPath.newInstance("//component[position()=2]/role-hint/text()");
    final XPath implementation2 = XPath.newInstance("//component[position()=2]/implementation/text()");
    assertEquals("role", ((Text) role2.selectSingleNode(doc)).getText());
    assertEquals("hint2", ((Text) hint2.selectSingleNode(doc)).getText());
    assertEquals("impl", ((Text) implementation2.selectSingleNode(doc)).getText());
}

35. ComponentsXmlArchiverFileFilterTest#testAddToArchive_ShouldWriteTwoComponentToFile()

Project: maven-plugins
File: ComponentsXmlArchiverFileFilterTest.java
public void testAddToArchive_ShouldWriteTwoComponentToFile() throws IOException, ArchiverException, JDOMException {
    filter.components = new LinkedHashMap<String, Xpp3Dom>();
    final Xpp3Dom dom = createComponentDom(new ComponentDef("role", "hint", "impl"));
    filter.components.put("rolehint", dom);
    final Xpp3Dom dom2 = createComponentDom(new ComponentDef("role", "hint2", "impl"));
    filter.components.put("rolehint2", dom2);
    final FileCatchingArchiver fca = new FileCatchingArchiver();
    filter.finalizeArchiveCreation(fca);
    assertEquals(ComponentsXmlArchiverFileFilter.COMPONENTS_XML_PATH, fca.getDestFileName());
    final SAXBuilder builder = new SAXBuilder(false);
    final Document doc = builder.build(fca.getFile());
    final XPath role = XPath.newInstance("//component[position()=1]/role/text()");
    final XPath hint = XPath.newInstance("//component[position()=1]/role-hint/text()");
    final XPath implementation = XPath.newInstance("//component[position()=1]/implementation/text()");
    assertEquals("role", ((Text) role.selectSingleNode(doc)).getText());
    assertEquals("hint", ((Text) hint.selectSingleNode(doc)).getText());
    assertEquals("impl", ((Text) implementation.selectSingleNode(doc)).getText());
    final XPath role2 = XPath.newInstance("//component[position()=2]/role/text()");
    final XPath hint2 = XPath.newInstance("//component[position()=2]/role-hint/text()");
    final XPath implementation2 = XPath.newInstance("//component[position()=2]/implementation/text()");
    assertEquals("role", ((Text) role2.selectSingleNode(doc)).getText());
    assertEquals("hint2", ((Text) hint2.selectSingleNode(doc)).getText());
    assertEquals("impl", ((Text) implementation2.selectSingleNode(doc)).getText());
}

36. ComponentsXmlArchiverFileFilterTest#testAddToArchive_ShouldWriteComponentWithHintToFile()

Project: maven-plugins
File: ComponentsXmlArchiverFileFilterTest.java
public void testAddToArchive_ShouldWriteComponentWithHintToFile() throws IOException, ArchiverException, JDOMException {
    final Xpp3Dom dom = createComponentDom(new ComponentDef("role", "hint", "impl"));
    filter.components = new LinkedHashMap<String, Xpp3Dom>();
    filter.components.put("rolehint", dom);
    final FileCatchingArchiver fca = new FileCatchingArchiver();
    filter.finalizeArchiveCreation(fca);
    assertEquals(ComponentsXmlArchiverFileFilter.COMPONENTS_XML_PATH, fca.getDestFileName());
    final SAXBuilder builder = new SAXBuilder(false);
    final Document doc = builder.build(fca.getFile());
    final XPath role = XPath.newInstance("//component[position()=1]/role/text()");
    final XPath hint = XPath.newInstance("//component[position()=1]/role-hint/text()");
    final XPath implementation = XPath.newInstance("//component[position()=1]/implementation/text()");
    assertEquals("role", ((Text) role.selectSingleNode(doc)).getText());
    assertEquals("hint", ((Text) hint.selectSingleNode(doc)).getText());
    assertEquals("impl", ((Text) implementation.selectSingleNode(doc)).getText());
}

37. ComponentsXmlArchiverFileFilterTest#testAddToArchive_ShouldWriteComponentWithoutHintToFile()

Project: maven-plugins
File: ComponentsXmlArchiverFileFilterTest.java
public void testAddToArchive_ShouldWriteComponentWithoutHintToFile() throws IOException, ArchiverException, JDOMException {
    final Xpp3Dom dom = createComponentDom(new ComponentDef("role", null, "impl"));
    filter.components = new LinkedHashMap<String, Xpp3Dom>();
    filter.components.put("role", dom);
    final FileCatchingArchiver fca = new FileCatchingArchiver();
    filter.finalizeArchiveCreation(fca);
    assertEquals(ComponentsXmlArchiverFileFilter.COMPONENTS_XML_PATH, fca.getDestFileName());
    final SAXBuilder builder = new SAXBuilder(false);
    final Document doc = builder.build(fca.getFile());
    final XPath role = XPath.newInstance("//component[position()=1]/role/text()");
    final XPath hint = XPath.newInstance("//component[position()=1]/role-hint/text()");
    final XPath implementation = XPath.newInstance("//component[position()=1]/implementation/text()");
    assertEquals("role", ((Text) role.selectSingleNode(doc)).getText());
    assertNull(hint.selectSingleNode(doc));
    assertEquals("impl", ((Text) implementation.selectSingleNode(doc)).getText());
}

38. ParseXMLFile#main()

Project: maven-framework-project
File: ParseXMLFile.java
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = (Document) builder.build(ClassLoader.getSystemResource("file.xml"));
        Element rootNode = document.getRootElement();
        List<Element> list = rootNode.getChildren("staff");
        for (int i = 0; i < list.size(); i++) {
            Element node = (Element) list.get(i);
            System.out.println("First Name : " + node.getChildText("firstname"));
            System.out.println("Last Name : " + node.getChildText("lastname"));
            System.out.println("Nick Name : " + node.getChildText("nickname"));
            System.out.println("Salary : " + node.getChildText("salary"));
            System.out.println();
        }
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }
}

39. MavenEffectivePomDumper#addMavenNamespace()

Project: intellij-community
File: MavenEffectivePomDumper.java
/**
   * Copy/pasted from org.apache.maven.plugins.help.AbstractEffectiveMojo
   */
protected static String addMavenNamespace(String effectiveXml, boolean isPom) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = builder.build(new StringReader(effectiveXml));
        Element rootElement = document.getRootElement();
        // added namespaces
        Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/4.0.0");
        rootElement.setNamespace(pomNamespace);
        Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.addNamespaceDeclaration(xsiNamespace);
        if (rootElement.getAttribute("schemaLocation", xsiNamespace) == null) {
            rootElement.setAttribute("schemaLocation", "http://maven.apache.org/POM/4.0.0 " + (isPom ? POM_XSD_URL : SETTINGS_XSD_URL), xsiNamespace);
        }
        ElementFilter elementFilter = new ElementFilter(Namespace.getNamespace(""));
        for (Iterator i = rootElement.getDescendants(elementFilter); i.hasNext(); ) {
            Element e = (Element) i.next();
            e.setNamespace(pomNamespace);
        }
        addLineBreaks(document, pomNamespace);
        StringWriter w = new StringWriter();
        Format format = Format.getRawFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(document.getRootElement(), w);
        return w.toString();
    } catch (JDOMException e) {
        return effectiveXml;
    } catch (IOException e) {
        return effectiveXml;
    }
}

40. MartServiceXMLHandlerTest#setUp()

Project: incubator-taverna-plugin-bioinformatics
File: MartServiceXMLHandlerTest.java
/*
	 * @see TestCase#setUp()
	 */
protected void setUp() throws Exception {
    super.setUp();
    xmlOutputter = new XMLOutputter();
    saxBuilder = new SAXBuilder();
    namespace = Namespace.getNamespace("test-namespace");
    martService = MartService.getMartService("url-location");
    martServiceXML = "<MartService xmlns=\"test-namespace\" location=\"url-location\" />";
    martUrlLocation = new MartURLLocation();
    martUrlLocation.setDefault(true);
    martUrlLocation.setDisplayName("location-display-name");
    martUrlLocation.setHost("host");
    martUrlLocation.setName("location-name");
    martUrlLocation.setPort(42);
    martUrlLocation.setServerVirtualSchema("server-virtual-schema");
    martUrlLocation.setVirtualSchema("virtual-schema");
    martUrlLocation.setVisible(false);
    martUrlLocation.setRedirect(true);
    martUrlLocationXML = "<MartURLLocation xmlns=\"test-namespace\" default=\"1\" displayName=\"location-display-name\" host=\"host\" name=\"location-name\" port=\"42\" serverVirtualSchema=\"server-virtual-schema\" virtualSchema=\"virtual-schema\" visible=\"0\" redirect=\"1\" />";
    martDataset = new MartDataset();
    martDataset.setDisplayName("dataset-display-name");
    martDataset.setInitialBatchSize(1);
    martDataset.setMartURLLocation(martUrlLocation);
    martDataset.setMaximumBatchSize(2);
    martDataset.setName("dataset-name");
    martDataset.setType("type");
    martDataset.setVisible(true);
    martDataset.setInterface("interface");
    martDataset.setModified("modified");
    martDatasetXML = "<MartDataset xmlns=\"test-namespace\" displayName=\"dataset-display-name\" name=\"dataset-name\" type=\"type\" initialBatchSize=\"1\" maximumBatchSize=\"2\" visible=\"true\" interface=\"interface\" modified=\"modified\"><MartURLLocation default=\"1\" displayName=\"location-display-name\" host=\"host\" name=\"location-name\" port=\"42\" serverVirtualSchema=\"server-virtual-schema\" virtualSchema=\"virtual-schema\" visible=\"0\" redirect=\"1\" /></MartDataset>";
    martRegistry = new MartRegistry();
    martRegistry.addMartURLLocation(martUrlLocation);
    martRegistryXML = "<MartRegistry xmlns=\"test-namespace\" ><virtualSchema xmlns=\"test-namespace\" name=\"virtual-schema\" visible=\"0\"><MartURLLocation xmlns=\"test-namespace\" default=\"1\" displayName=\"location-display-name\" host=\"host\" name=\"location-name\" port=\"42\" serverVirtualSchema=\"server-virtual-schema\" visible=\"0\" redirect=\"1\" /></virtualSchema></MartRegistry>";
    martRegistryXML2 = "<MartRegistry xmlns=\"test-namespace\" ><virtualSchema xmlns=\"test-namespace\" name=\"default\" visible=\"0\"><MartURLLocation xmlns=\"test-namespace\" default=\"1\" displayName=\"location-display-name\" host=\"host\" name=\"location-name\" port=\"42\" serverVirtualSchema=\"server-virtual-schema\" visible=\"0\" redirect=\"1\" /></virtualSchema></MartRegistry>";
}

41. TestBiomartActivityContextualView#getQueryElement()

Project: incubator-taverna-plugin-bioinformatics
File: TestBiomartActivityContextualView.java
private Element getQueryElement(String resourceName) throws Exception {
    InputStream inStream = TestBiomartActivityContextualView.class.getResourceAsStream("/" + resourceName);
    if (inStream == null)
        throw new IOException("Unable to find resource for:" + resourceName);
    SAXBuilder builder = new SAXBuilder();
    return builder.build(inStream).detachRootElement();
}

42. AnnotationsLoader#getAnnotations()

Project: incubator-taverna-engine
File: AnnotationsLoader.java
/**
	 * @param annotationFile
	 *            by convention we use <workflow file name>+"annotations"
	 * @return a map pname -> annotation so that the lineage query alg can use
	 *         the annotation when processing pname
	 */
@SuppressWarnings("unchecked")
public Map<String, List<String>> getAnnotations(String annotationFile) {
    Map<String, List<String>> procAnnotations = new HashMap<>();
    // load XML file as doc
    //		parse the event into DOM
    SAXBuilder b = new SAXBuilder();
    try {
        Document d = b.build(new FileReader(annotationFile));
        if (d == null)
            return null;
        // look for all processor elements
        for (Element el : (List<Element>) d.getRootElement().getChildren()) {
            String pName = el.getAttributeValue("name");
            logger.info("processor name: " + pName);
            List<String> annotations = new ArrayList<>();
            for (Element annotElement : (List<Element>) el.getChildren()) {
                String annot = annotElement.getAttributeValue("type");
                logger.info("annotation: " + annot);
                // add this annotation
                annotations.add(annot);
            }
            procAnnotations.put(pName, annotations);
        }
    } catch (JDOMExceptionIOException |  e) {
        logger.error("Problem getting annotations from: " + annotationFile, e);
    }
    return procAnnotations;
}

43. ToolDescriptionParser#readDescriptionsFromStream()

Project: incubator-taverna-common-activities
File: ToolDescriptionParser.java
public static List<ToolDescription> readDescriptionsFromStream(InputStream is) {
    List<ToolDescription> ret = new ArrayList<ToolDescription>();
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        doc = builder.build(is);
        is.close();
    } catch (JDOMException e1) {
        logger.error(e1);
        return ret;
    } catch (IOException e1) {
        logger.error(e1);
        return ret;
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            logger.error(e);
        }
    }
    Element usecases = doc.getRootElement();
    for (Object ochild : usecases.getChildren()) {
        Element child = (Element) ochild;
        if (child.getName().equalsIgnoreCase("program")) {
            try {
                ret.add(new ToolDescription(child));
            } catch (DeserializationException e) {
                logger.error(e);
            }
        }
    }
    return ret;
}

44. CassandraMappingManager#loadConfiguration()

Project: gora
File: CassandraMappingManager.java
/**
   * Primary class for loading Cassandra configuration from the 'MAPPING_FILE'.
   * 
   * @throws JDOMException
   * @throws IOException
   */
@SuppressWarnings("unchecked")
public void loadConfiguration() throws JDOMException, IOException {
    SAXBuilder saxBuilder = new SAXBuilder();
    // get mapping file
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(MAPPING_FILE);
    if (inputStream == null) {
        LOG.warn("Mapping file '" + MAPPING_FILE + "' could not be found!");
        throw new IOException("Mapping file '" + MAPPING_FILE + "' could not be found!");
    }
    Document document = saxBuilder.build(inputStream);
    if (document == null) {
        LOG.warn("Mapping file '" + MAPPING_FILE + "' could not be found!");
        throw new IOException("Mapping file '" + MAPPING_FILE + "' could not be found!");
    }
    Element root = document.getRootElement();
    // find cassandra keyspace element
    List<Element> keyspaces = root.getChildren(KEYSPACE_ELEMENT);
    if (keyspaces == null || keyspaces.size() == 0) {
        LOG.error("Error locating Cassandra Keyspace element!");
    } else {
        for (Element keyspace : keyspaces) {
            // log name, cluster and host for given keyspace(s)
            String keyspaceName = keyspace.getAttributeValue(NAME_ATTRIBUTE);
            String clusterName = keyspace.getAttributeValue(CLUSTER_ATTRIBUTE);
            String hostName = keyspace.getAttributeValue(HOST_ATTRIBUTE);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Located Cassandra Keyspace: '" + keyspaceName + "' in cluster '" + clusterName + "' on host '" + hostName + "'.");
            }
            if (keyspaceName == null) {
                LOG.error("Error locating Cassandra Keyspace name attribute!");
                continue;
            }
            keyspaceMap.put(keyspaceName, keyspace);
        }
    }
    // load column definitions    
    List<Element> mappings = root.getChildren(MAPPING_ELEMENT);
    if (mappings == null || mappings.size() == 0) {
        LOG.error("Error locating Cassandra Mapping class element!");
    } else {
        for (Element mapping : mappings) {
            // associate persistent and class names for keyspace(s)
            String className = mapping.getAttributeValue(NAME_ATTRIBUTE);
            String keyClassName = mapping.getAttributeValue(KEYCLASS_ATTRIBUTE);
            String keyspaceName = mapping.getAttributeValue(KEYSPACE_ELEMENT);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Located Cassandra Mapping: keyClass: '" + keyClassName + "' in storage class '" + className + "' for Keyspace '" + keyspaceName + "'.");
            }
            if (className == null) {
                LOG.error("Error locating Cassandra Mapping class name attribute!");
                continue;
            }
            mappingMap.put(className, mapping);
        }
    }
}

45. UniqueOnCancelValidatorTest#elementFor()

Project: gocd
File: UniqueOnCancelValidatorTest.java
private Element elementFor(String content) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    return builder.build(new ByteArrayInputStream(content.getBytes())).getRootElement();
}

46. SvnCommand#getBuilder()

Project: gocd
File: SvnCommand.java
private SAXBuilder getBuilder() {
    SAXBuilder saxBuilder = saxBuilderThreadLocal.get();
    if (saxBuilder == null) {
        saxBuilder = new SAXBuilder();
        saxBuilderThreadLocal.set(saxBuilder);
    }
    return saxBuilder;
}

47. SvnCommand#parseSvnLog()

Project: gocd
File: SvnCommand.java
private List<Modification> parseSvnLog(String output) {
    SAXBuilder builder = getBuilder();
    SvnInfo svnInfo = remoteInfo(builder);
    return svnLogXmlParser.parse(output, svnInfo.getPath(), builder);
}

48. EffectivePomWriter#addMavenNamespace()

Project: che
File: EffectivePomWriter.java
/**
     * method from org.apache.maven.plugins.help.AbstractEffectiveMojo
     * Add a Pom/Settings namespaces to the effective XML content.
     *
     * @param effectiveXml not null the effective POM or Settings
     * @param isPom if <code>true</code> add the Pom xsd url, otherwise add the settings xsd url.
     * @return the content of the root element, i.e. <project/> or <settings/> with the Maven namespace or
     *         the original <code>effective</code> if an error occurred.
     * @see #POM_XSD_URL
     * @see #SETTINGS_XSD_URL
     */
protected static String addMavenNamespace(String effectiveXml, boolean isPom) {
    SAXBuilder builder = new SAXBuilder();
    try {
        Document document = builder.build(new StringReader(effectiveXml));
        Element rootElement = document.getRootElement();
        // added namespaces
        Namespace pomNamespace = Namespace.getNamespace("", "http://maven.apache.org/POM/4.0.0");
        rootElement.setNamespace(pomNamespace);
        Namespace xsiNamespace = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElement.addNamespaceDeclaration(xsiNamespace);
        if (rootElement.getAttribute("schemaLocation", xsiNamespace) == null) {
            rootElement.setAttribute("schemaLocation", "http://maven.apache.org/POM/4.0.0 " + (isPom ? POM_XSD_URL : SETTINGS_XSD_URL), xsiNamespace);
        }
        ElementFilter elementFilter = new ElementFilter(Namespace.getNamespace(""));
        for (Iterator<?> i = rootElement.getDescendants(elementFilter); i.hasNext(); ) {
            Element e = (Element) i.next();
            e.setNamespace(pomNamespace);
        }
        StringWriter w = new StringWriter();
        Format format = Format.getPrettyFormat();
        XMLOutputter out = new XMLOutputter(format);
        out.output(document.getRootElement(), w);
        return w.toString();
    } catch (JDOMException e) {
        return effectiveXml;
    } catch (IOException e) {
        return effectiveXml;
    }
}