package org.exolab.castor.tests;

import junit.framework.TestCase;
import org.exolab.castor.jdo.*;

import java.util.Date;

/**
 * Unit Test case to demonstrate error:
 * org.exolab.castor.mapping.MappingException: Field element, "java.sql.Time"  not found!.
 *
 * <p/>
 * Relies on the "unit-test.db" named database specified either by {@link #CASTOR_CONFIG_SYS_PROP}
 * system property or a file named "unit-test-database.xml" present in the same directory as
 * this .class file.
 * <p/>
 * MySQL user can be created with :
 * GRANT ALL
 * ON ${db.sid}.*
 * TO ${db.user}@'localhost' IDENTIFIED BY '${db.user.pwd}'
 */
public class SqlTimePropertyTest extends TestCase {
    public static final String CASTOR_CONFIG_SYS_PROP = "castor.config.path";

    Database db = null;

    public SqlTimePropertyTest(String s) {
        super(s);
    }

    protected void setUp() throws Exception {
    	JDO jdo = getJDOForTest();
		db = jdo.getDatabase();
		db.begin();
    }

    protected void tearDown() throws Exception {
		db.commit();
 		db.close();
    }

    /**
     * Ensures Castor can support the java.sql.Time data type without throwing a MappingException when the class is
     * Loaded.
     * <p/>
     * Test Case uses the Clock object in this package.
     */
    public void testObjectWithTimeProperty() throws Exception {

		//try loading the Clock that contains a java.sql.Time property
		Query oql = db.getOQLQuery( "SELECT c FROM Clock c");
		QueryResults results = oql.execute();

    }

    private String stackTraceToString(StackTraceElement[] stackTrace) {
        int stackLength = stackTrace.length;
        StringBuffer stringBuffer = new StringBuffer(400 * stackLength);
        for (int i=0; i<stackLength; i++) {
            stringBuffer.append(stackTrace[i].toString());
            if (i + 1 < stackLength) {
                stringBuffer.append("\n\t");
            }
        }
        return stringBuffer.toString();
    }

    /**
     * Retrieve the JDO object from the classpath.  Expects the Castor database/mapping files to be in the same directory
     * as this class file.  May be overriden with the {@link #CASTOR_CONFIG_SYS_PROP} system property.
     * (i.e. -Dcastor.config.path=file:///<path>)
     *
     * @return The JDO object encapsulating the Castor configuration for use with this test case.
     */
    private JDO getJDOForTest() {
        JDO jdo = new JDO("unit-test.db");
        String castorConfigPath = System.getProperty(CASTOR_CONFIG_SYS_PROP);
        if (castorConfigPath == null) {
            castorConfigPath = getClass().getResource("./unit-test-database.xml").getPath();
            System.out.println("Loading Castor Database file=" + castorConfigPath);
        }
        jdo.setConfiguration(castorConfigPath);

        return jdo;
    }

}