You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@empire-db.apache.org by fr...@apache.org on 2009/11/19 08:08:38 UTC

svn commit: r882059 - in /incubator/empire-db/trunk/empire-db-codegen/src: main/java/org/apache/empire/db/codegen/ test/java/org/apache/empire/db/codegen/ test/resources/

Author: francisdb
Date: Thu Nov 19 07:08:35 2009
New Revision: 882059

URL: http://svn.apache.org/viewvc?rev=882059&view=rev
Log:
added initial unit test for codegen

Added:
    incubator/empire-db/trunk/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/CodeGenTest.java
    incubator/empire-db/trunk/empire-db-codegen/src/test/resources/log4j.properties
    incubator/empire-db/trunk/empire-db-codegen/src/test/resources/testconfig.xml
Modified:
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenApp.java
    incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenParser.java

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java?rev=882059&r1=882058&r2=882059&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGen.java Thu Nov 19 07:08:35 2009
@@ -22,14 +22,13 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.Writer;
-import java.sql.Connection;
-import java.sql.DriverManager;
+import java.util.ArrayList;
+import java.util.List;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.empire.db.DBDatabase;
 import org.apache.empire.db.DBTable;
-import org.apache.empire.db.codegen.util.DBUtil;
 import org.apache.empire.db.codegen.util.FileUtils;
 import org.apache.empire.db.codegen.util.ParserUtil;
 import org.apache.velocity.Template;
@@ -96,90 +95,30 @@
 	}
 
 	/**
-	 * Generates the code according to the provided configuration file
-	 * @param config
+	 * Generates the java code files for the database
+	 * @param db the DBDatabase to generate files for
 	 */
-	public void generate(){
-
-		Connection conn = null;
-		try {			
-			// Get a JDBC Connection
-			conn = getJDBCConnection();
-			
-			// create the database in memory
-			DBDatabase db = parseDataModel(conn);
-			
-			// create the source-code for that database
-			generateCodeFiles(db);
-			
-			log.info("Code generation completed sucessfully!");
-		} 
-		catch (Exception e) 
-		{
-			log.error(e.getMessage(), e);
-		} 
-		finally 
-		{
-			DBUtil.close(conn, log);
-		}
-	}
-	
-	/**
-	 * <PRE>
-	 * Opens and returns a JDBC-Connection.
-	 * JDBC url, user and password for the connection are obained from the SampleConfig bean
-	 * Please use the config.xml file to change connection params.
-	 * </PRE>
-	 */
-	private Connection getJDBCConnection() {
-		// Establish a new database connection
-		Connection conn = null;
-		log.info("Connecting to Database'" + config.getJdbcURL() + "' / User="
-				+ config.getJdbcUser());
-		try {
-			// Connect to the databse
-			Class.forName(config.getJdbcClass()).newInstance();
-			conn = DriverManager.getConnection(config.getJdbcURL(), config
-					.getJdbcUser(), config.getJdbcPwd());
-			log.info("Connected successfully");
-			// set the AutoCommit to false this session. You must commit
-			// explicitly now
-			conn.setAutoCommit(true);
-			log.info("AutoCommit is " + conn.getAutoCommit());
-
-		} catch (Exception e) {
-			log.fatal("Failed to connect directly to '" + config.getJdbcURL()
-					+ "' / User=" + config.getJdbcUser(), e);
-			throw new RuntimeException(e);
-		}
-		return conn;
-	}
-
-	public DBDatabase parseDataModel(Connection conn) {
-		CodeGenParser cgp = new CodeGenParser(conn, config);
-		DBDatabase memoryDB = cgp.getDb();
-		return memoryDB;
-	}
-
-	public void generateCodeFiles(DBDatabase db) {
+	public List<File> generateCodeFiles(DBDatabase db) {
+	    List<File> generatedFiles = new ArrayList<File>();
 
 		// Prepare directories for generated source files
 		this.initDirectories(config.getTargetFolder(), config.getPackageName());
 
 		// Create the DB class
-		this.createDatabaseClass(db);
+		generatedFiles.add(this.createDatabaseClass(db));
 
 		// Create base table class
-		this.createBaseTableClass(db);
+		generatedFiles.add(this.createBaseTableClass(db));
 
 		// Create base record class
-		this.createBaseRecordClass(db);
+		generatedFiles.add(this.createBaseRecordClass(db));
 		// Create table classes, record interfaces and record classes
 		for (DBTable table : db.getTables()) 
 		{
-			this.createTableClass(db, table);
-			this.createRecordClass(db, table);
+		    generatedFiles.add(this.createTableClass(db, table));
+		    generatedFiles.add(this.createRecordClass(db, table));
 		}
+		return generatedFiles;
 	}
 
 	private void initDirectories(String srcLocation, String packageName) {
@@ -208,7 +147,7 @@
 		this.recordDir.mkdir();
 	}
 
-	private void createDatabaseClass(DBDatabase db) {
+	private File createDatabaseClass(DBDatabase db) {
 		File file = new File(baseDir, config.getDbClassName() + ".java");
 		VelocityContext context = new VelocityContext();
 		context.put("parser", pUtil);
@@ -218,17 +157,19 @@
 		context.put("tableSubPackage", "tables");
 		context.put("database", db);
 		writeFile(file, TEMPLATE_PATH + "/" + DATABASE_TEMPLATE, context);
+		return file;
 	}
 
-	private void createBaseTableClass(DBDatabase db) {
+	private File createBaseTableClass(DBDatabase db) {
 		File file = new File(tableDir, config.getTableBaseName() + ".java");
 		VelocityContext context = new VelocityContext();
 		context.put("tablePackageName", config.getPackageName() + ".tables");
 		context.put("baseTableClassName", config.getTableBaseName());
 		writeFile(file, TEMPLATE_PATH + "/" + BASE_TABLE_TEMPLATE, context);
+		return file;
 	}
 
-	private void createTableClass(DBDatabase db, DBTable table) {
+	private File createTableClass(DBDatabase db, DBTable table) {
 		File file = new File(tableDir, pUtil.getTableClassName(table.getName())
 				+ ".java");
 		VelocityContext context = new VelocityContext();
@@ -239,9 +180,10 @@
 		context.put("dbClassName", config.getDbClassName());
 		context.put("table", table);
 		writeFile(file, TEMPLATE_PATH + "/" + TABLE_TEMPLATE, context);
+		return file;
 	}
 
-	private void createBaseRecordClass(DBDatabase db) {
+	private File createBaseRecordClass(DBDatabase db) {
 		File file = new File(recordDir, config.getRecordBaseName() + ".java");
 		VelocityContext context = new VelocityContext();
 		context.put("baseRecordClassName", config.getRecordBaseName());
@@ -250,9 +192,10 @@
 		context.put("recordPackageName", config.getPackageName() + ".records");
 		context.put("baseTableClassName", config.getTableBaseName());
 		writeFile(file, TEMPLATE_PATH + "/" + BASE_RECORD_TEMPLATE, context);
+		return file;
 	}
 
-	private void createRecordClass(DBDatabase db, DBTable table) {
+	private File createRecordClass(DBDatabase db, DBTable table) {
 		File file = new File(recordDir, pUtil.getRecordClassName(table
 				.getName())
 				+ ".java");
@@ -269,6 +212,7 @@
 
 		context.put("table", table);
 		writeFile(file, TEMPLATE_PATH + "/" + RECORD_TEMPLATE, context);
+		return file;
 	}
 
 	private static void writeFile(File file, String templatePath,

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenApp.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenApp.java?rev=882059&r1=882058&r2=882059&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenApp.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenApp.java Thu Nov 19 07:08:35 2009
@@ -21,6 +21,7 @@
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.empire.commons.ErrorObject;
+import org.apache.empire.db.DBDatabase;
 
 /**
  * Console code generator application, takes the config file as first argument.
@@ -55,8 +56,15 @@
 		// log all options
 		listOptions(config);
 		
+		// read the database model
+		CodeGenParser parser = new CodeGenParser(config);
+		DBDatabase db = parser.loadDbModel();
+		
+		// create the source-code for that database
 		CodeGen codeGen = new CodeGen(config);
-		codeGen.generate();
+		codeGen.generateCodeFiles(db);
+		
+		log.info("Code generation completed sucessfully!");
 	}
 	
 	/**
@@ -98,4 +106,6 @@
 		log.info("NestViews=" + config.isNestViews());
 		log.info("CreateRecordProperties=" + config.isCreateRecordProperties());
 	}
+	
+
 }

Modified: incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenParser.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenParser.java?rev=882059&r1=882058&r2=882059&view=diff
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenParser.java (original)
+++ incubator/empire-db/trunk/empire-db-codegen/src/main/java/org/apache/empire/db/codegen/CodeGenParser.java Thu Nov 19 07:08:35 2009
@@ -16,11 +16,11 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-
 package org.apache.empire.db.codegen;
 
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
+import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Types;
@@ -48,6 +48,7 @@
 	}
 
 	private static final Log log = LogFactory.getLog(CodeGenParser.class);
+	
 	private DatabaseMetaData dbMeta;
 	private Connection con;
 	private CodeGenConfig config;
@@ -56,28 +57,73 @@
 	/**
 	 * create a empty in memory Database and populates it
 	 */
-	public CodeGenParser(Connection conn, CodeGenConfig config) {
-
-		this.con = conn;
-		this.db = new InMemoryDatabase();
-		this.config = config;
-		try {
-			this.dbMeta = con.getMetaData();
-			populateDatabase();
-		} catch (SQLException e) {
-			throw new RuntimeException("Unable to read database metadata!", e);
-		}
+	public CodeGenParser(CodeGenConfig config) {
+	    this.config = config;
 	}
 
 	/**
 	 * returns the populated DBDatabase
 	 */
-	public DBDatabase getDb() {
+	public DBDatabase loadDbModel() {
+	    this.db = new InMemoryDatabase();
+	    try {           
+            // Get a JDBC Connection
+            con = getJDBCConnection(config);
+            
+            // create the database in memory
+
+            this.dbMeta = con.getMetaData();
+            populateDatabase();
+                        
+        } 
+        catch (SQLException e) 
+        {
+            throw new RuntimeException("Unable to read database metadata!", e);
+        }
+        catch (Exception e) 
+        {
+            log.error(e.getMessage(), e);
+        } 
+        finally 
+        {
+            DBUtil.close(con, log);
+        }
 		return db;
 	}
 
 	// ----------- private members
 
+	   /**
+     * <PRE>
+     * Opens and returns a JDBC-Connection.
+     * JDBC url, user and password for the connection are obained from the SampleConfig bean
+     * Please use the config.xml file to change connection params.
+     * </PRE>
+     */
+    private Connection getJDBCConnection(CodeGenConfig config) {
+        // Establish a new database connection
+        Connection conn = null;
+        log.info("Connecting to Database'" + config.getJdbcURL() + "' / User="
+                + config.getJdbcUser());
+        try {
+            // Connect to the databse
+            Class.forName(config.getJdbcClass()).newInstance();
+            conn = DriverManager.getConnection(config.getJdbcURL(), config
+                    .getJdbcUser(), config.getJdbcPwd());
+            log.info("Connected successfully");
+            // set the AutoCommit to false this session. You must commit
+            // explicitly now
+            conn.setAutoCommit(true);
+            log.info("AutoCommit is " + conn.getAutoCommit());
+
+        } catch (Exception e) {
+            log.fatal("Failed to connect directly to '" + config.getJdbcURL()
+                    + "' / User=" + config.getJdbcUser(), e);
+            throw new RuntimeException(e);
+        }
+        return conn;
+    }
+	
 	/**
 	 * queries the metadata of the database for tables and populates the
 	 * database with those

Added: incubator/empire-db/trunk/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/CodeGenTest.java
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/CodeGenTest.java?rev=882059&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/CodeGenTest.java (added)
+++ incubator/empire-db/trunk/empire-db-codegen/src/test/java/org/apache/empire/db/codegen/CodeGenTest.java Thu Nov 19 07:08:35 2009
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.empire.db.codegen;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.empire.db.DBDatabase;
+import org.apache.empire.db.codegen.util.FileUtils;
+import org.junit.After;
+import org.junit.Test;
+
+public class CodeGenTest
+{
+	@After
+	public void cleanup(){
+		File generated = new File("target/generated");
+		FileUtils.deleteDirectory(generated);
+	}
+
+    @Test
+    public void testCodeGen()
+    {
+        CodeGenConfig config = new CodeGenConfig();
+        config.init("testconfig.xml", true, false);
+        CodeGen codeGen = new CodeGen(config);
+        
+        DBDatabase db = new DBDatabase()
+        {
+        };
+        
+        List<File> files = codeGen.generateCodeFiles(db);
+        assertEquals(3, files.size());
+        for(File file:files){
+        	System.out.println(file);
+        }
+        
+        // TODO try to compile the resulting files???
+        
+        // Commons jci 1.0 seems not able to handle java 5
+//        List<String> arguments = new ArrayList<String>();
+//        String strFile;
+//        for(File file:files){
+//        	strFile = file.getPath().replace(config.getTargetFolder()+"/", "");
+//            arguments.add(strFile);
+//            System.out.println(strFile);
+//        }
+//        JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
+//        JavaCompilerSettings settings = new JavaCompilerSettings();
+//        settings.setSourceVersion("1.5");
+//        settings.setTargetVersion("1.5");
+//        settings.setVerbose(true);
+//        CompilationResult result = compiler.compile(
+//        		arguments.toArray(new String[arguments.size()]), 
+//        		new FileResourceReader(new File(config.getTargetFolder())), 
+//        		new FileResourceStore(new File("target/compiledsources.test")),
+//        		getClass().getClassLoader(),
+//        		settings);
+//
+//        System.out.println( result.getErrors().length + " errors");
+//        for(CompilationProblem problem:result.getErrors()){
+//        	System.out.println( problem);
+//        }
+//        System.out.println( result.getWarnings().length + " warnings");
+//        for(CompilationProblem warning:result.getWarnings()){
+//        	System.out.println( warning);
+//        }
+        
+        // ONLY for java 6
+//        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+//        arguments.add("-classpath");
+//        arguments.add(System.getProperty("java.class.path"));
+//        for(File file:files){
+//            System.out.println(file);
+//            arguments.add(file.getAbsolutePath());
+//        }
+//
+//        int compilationResult = compiler.run(null, null, null, arguments.toArray(new String[arguments.size()]));
+//        assertEquals("Compilation Failed", 0, compilationResult);
+        
+    }
+
+}

Added: incubator/empire-db/trunk/empire-db-codegen/src/test/resources/log4j.properties
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/test/resources/log4j.properties?rev=882059&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/test/resources/log4j.properties (added)
+++ incubator/empire-db/trunk/empire-db-codegen/src/test/resources/log4j.properties Thu Nov 19 07:08:35 2009
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#  http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+log4j.rootCategory=DEBUG, console
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.conversionPattern = %d{ISO8601} %-5p [%c] - %m%n

Added: incubator/empire-db/trunk/empire-db-codegen/src/test/resources/testconfig.xml
URL: http://svn.apache.org/viewvc/incubator/empire-db/trunk/empire-db-codegen/src/test/resources/testconfig.xml?rev=882059&view=auto
==============================================================================
--- incubator/empire-db/trunk/empire-db-codegen/src/test/resources/testconfig.xml (added)
+++ incubator/empire-db/trunk/empire-db-codegen/src/test/resources/testconfig.xml Thu Nov 19 07:08:35 2009
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+ --> 
+<config>
+
+	<properties>
+		<!-- provider name must match the property-section containing the connection data -->
+		<jdbcClass>oracle.jdbc.driver.OracleDriver</jdbcClass>
+		<jdbcURL>jdbc:oracle:thin:@192.168.0.2:1521:ora10</jdbcURL>
+		<jdbcUser>DBSAMPLE</jdbcUser>
+		<jdbcPwd>DBSAMPLE</jdbcPwd>
+
+		<!-- Schema options -->
+		<dbCatalog></dbCatalog>
+		<dbSchema>DBSAMPLE</dbSchema>
+		<dbTablePattern></dbTablePattern>
+		<timestampColumn>CREATIONDATE</timestampColumn>
+		
+		<!-- generation options -->
+		<targetFolder>target/generated/dbsample</targetFolder>
+		<packageName>org.apache.empire.db.samples.dbsample</packageName>
+		<dbClassName>SampleDB</dbClassName>
+		<tableBaseName>SampleTable</tableBaseName>
+		<viewBaseName>SampleView</viewBaseName>
+		<recordBaseName>SampleRecord</recordBaseName>
+		<tableClassPrefix>T</tableClassPrefix>
+		<tableClassSuffix>Table</tableClassSuffix>
+		<viewClassPrefix>V</viewClassPrefix>
+		<nestTables>True</nestTables>
+		<nestViews>False</nestViews>
+		<createRecordProperties>true</createRecordProperties>
+	</properties>
+	
+	<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
+
+		<appender name="default" class="org.apache.log4j.ConsoleAppender">
+			<!-- layout class="org.apache.log4j.TTCCLayout"/ -->
+			<layout class="org.apache.log4j.PatternLayout">
+				<!-- param name="ConversionPattern" value="NSB(%c) %-5p %m	at %l%n"/ -->
+				<param name="ConversionPattern" value="%-5p [%d{yyyy/MM/dd HH:mm}]: %m		at %l %n"/>
+			</layout>
+		</appender>
+	
+		<!-- log detail configuration -->
+		<logger name="org.apache.empire.commons" additivity="false">
+			<level value="warn"/>
+			<appender-ref ref="default"/>
+		</logger>
+	
+		<root>
+			<priority value="info"/>
+			<appender-ref ref="default"/>
+		</root>
+
+	</log4j:configuration>
+	
+</config>