⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmldbtestcase.java

📁 Java的面向对象数据库系统的源代码
💻 JAVA
字号:
/*
 *  The XML:DB Initiative Software License, Version 1.0
 *
 *
 * Copyright (c) 2000-2001 The XML:DB Initiative.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        XML:DB Initiative (http://www.xmldb.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The name "XML:DB Initiative" must not be used to endorse or
 *    promote products derived from this software without prior written
 *    permission. For written permission, please contact info@xmldb.org.
 *
 * 5. Products derived from this software may not be called "XML:DB",
 *    nor may "XML:DB" appear in their name, without prior written
 *    permission of the XML:DB Initiative.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the XML:DB Initiative. For more information
 * on the XML:DB Initiative, please see <http://www.xmldb.org/>.
 */
package test.xmldb;

import java.io.*;

import junit.framework.*;

import org.xmldb.api.base.*;

import java.util.Properties;
import java.net.URL;

import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMImplementation;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xerces.dom.DOMImplementationImpl;
import org.apache.log4j.Logger;


/**
 * This is the fixture for the other tests
 */
public class XMLDBTestCase extends TestCase {
    /** the <code>Collection</code> that we use in all tests */
    protected Collection col;

    /** File containing the XML to be used for SAX tests*/
    protected String xmlFileName = "LevelZeroTest.xml";

    /** a starting <code>Document</code> corresponding to the fileName for DOM tests*/
    protected Document document;

    /** the collection used for testing */
    protected String collectionName;

    private CollectionStorageHelper collectionStorageHelper;

    private Logger logger = Logger.getLogger(XMLDBTestCase.class);

    public XMLDBTestCase(String name) {
        super(name);
    }

    public void setUp() throws Exception {
        logger.debug("******************** set up ********************");
        Properties props;
        if (XMLDBTestSuite.propertiesFileName == null) {
            // Load the props file from the jar
            String defaultPropsFileLocation = "test/xmldb/XMLDBTestSuite.properties";
            URL url = this.getClass().getClassLoader().getResource(defaultPropsFileLocation);
            if (url == null) {
                throw new Exception("failed to find default props file at " + defaultPropsFileLocation);
            }
            props = loadProps(url.openConnection().getInputStream());

        } else {
            props = loadProps(XMLDBTestSuite.propertiesFileName);
        }
        String driver = props.getProperty("driverName");
        collectionName = props.getProperty("collectionName");
        String collectionURI = props.getProperty("URI") + collectionName;
        String dbURI = props.getProperty("dbURI");

        //create and store a new collection in the XML database
        collectionStorageHelper = new CollectionStorageHelper(dbURI);
        collectionStorageHelper.createCollection(collectionName);

        Database database = (Database) Class.forName(driver).newInstance();
        // No need to register since this is done automatically when loading the driver
        //DatabaseManager.registerDatabase(database);

        // get the root collection
        col = database.getCollection(collectionURI);
        assertNotNull("XMLDBTestCase.setUp() - Collection could not be created", col);

        document = createXMLFile(xmlFileName);
        assertNotNull("XMLDBTestCase.setUp() - failed to create XML file", document);
    }

    public void tearDown() {
        logger.debug("******************** tear down ********************");
        collectionStorageHelper.deleteCollection(collectionName);
        col.close();
        assertTrue("XMLDBTestCase.tearDown() - failed to delete XML file", deleteXMLFile(xmlFileName));
    }

    /** convert a <code>Document</code>into a String */
    protected String toString(Document document) throws Exception {
        StringWriter writer = new StringWriter();
        XMLSerializer serializer = new XMLSerializer(writer, new OutputFormat("xml", "UTF-8", true));
        serializer.serialize(document);
        writer.flush();
        return writer.toString();
    }

    /** convert a <code>Node</code>into a String */
    protected String toString(Node node) throws Exception {
        try {
            // getOwnerDocument returns null if it is a Document so we check first
            if (node instanceof Document) {
                return toString((Document) node);
            } else {
                Document doc = node.getOwnerDocument();
                return toString(doc);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    protected void deleteResource(String id) throws Exception {
        col.removeResource(col.getResource(id));
    }

    private Properties loadProps(InputStream in) {
        Properties props = createDefaultProps();
        try {
            props.load(in);
        } catch (Exception e) {
            logger.warn("Didn't find props file, using defaults");
            props.list(System.out);
        }
        return props;

    }

    private Properties loadProps(String iniFileName) {
        Properties props = createDefaultProps();
        // now load the props file
        try {
            props.load(new FileInputStream(new File(iniFileName)));
        } catch (Exception e) {
            logger.warn("Didn't find props file, using defaults");
            props.list(System.out);
        }
        return props;
    }

    /**
     *  Helper method to load the XMLDBTestCase.properties file
     *
     *  @return the loaded properties
     */
    private Properties createDefaultProps() {
        Properties defaultProps = new Properties();

        // load the default parameters for the reference implementation
        defaultProps.put("driverName", "org.xmldb.api.reference.DatabaseImpl");
        defaultProps.put("URI", "xmldb:ref:///child1");

        // TODO: how about userid and password?
        //defaultProps.put("userId", "foo");
        //defaultProps.put("passWord", "bar");

        Properties props = new Properties(defaultProps);
        return props;
    }

    protected Document createXMLFile(String fileName) throws Exception {
        logger.debug("XMLDBTestCase.createXMLFile() - Writing file= " + fileName);
        FileWriter out = new FileWriter(fileName);

        DOMImplementation documentCreator = new DOMImplementationImpl();
        Document doc = documentCreator.createDocument(null, "XMLDBTests", null);

        Element root = doc.getDocumentElement();

        Element levelZeroTests = doc.createElement("levelZeroTests");
        levelZeroTests.setAttribute("complianceLevel", "0");
        root.appendChild(levelZeroTests);

        Element testName = doc.createElement("testName");
        levelZeroTests.appendChild(testName);

        Node name = doc.createTextNode("testBinary");
        testName.appendChild(name);

        testName = doc.createElement("testName");
        levelZeroTests.appendChild(testName);

        name = doc.createTextNode("testDOM");
        testName.appendChild(name);

        OutputFormat format = new OutputFormat(doc, "UTF-8", true);
        XMLSerializer serializer = new XMLSerializer(out, format);

        serializer.serialize(doc);
        out.close();

        return doc;
    }

    protected boolean deleteXMLFile(String xmlFileName) {
        File file = new File(xmlFileName);
        return file.delete();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -