cayenne-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From aadamc...@apache.org
Subject svn commit: r1299264 - in /cayenne/main/trunk: docs/docbook/cayenne-guide/src/docbkx/ framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/ framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/
Date Sat, 10 Mar 2012 20:12:50 GMT
Author: aadamchik
Date: Sat Mar 10 20:12:49 2012
New Revision: 1299264

URL: http://svn.apache.org/viewvc?rev=1299264&view=rev
Log:
docbook - cdbimport

also cleaning up the Mojo and the Ant task to avoid deprecated API and map file creation redundancy

Modified:
    cayenne/main/trunk/docs/docbook/cayenne-guide/src/docbkx/including-cayenne-in-project.xml
    cayenne/main/trunk/framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/DbImporterTask.java
    cayenne/main/trunk/framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/DbImporterMojo.java

Modified: cayenne/main/trunk/docs/docbook/cayenne-guide/src/docbkx/including-cayenne-in-project.xml
URL: http://svn.apache.org/viewvc/cayenne/main/trunk/docs/docbook/cayenne-guide/src/docbkx/including-cayenne-in-project.xml?rev=1299264&r1=1299263&r2=1299264&view=diff
==============================================================================
--- cayenne/main/trunk/docs/docbook/cayenne-guide/src/docbkx/including-cayenne-in-project.xml
(original)
+++ cayenne/main/trunk/docs/docbook/cayenne-guide/src/docbkx/including-cayenne-in-project.xml
Sat Mar 10 20:12:49 2012
@@ -239,9 +239,9 @@
 		</section>
 		<section xml:id="mvn-cdbgen">
 			<title>cdbgen</title>
-			<para><code>cdbgen</code> is a <code>maven-cayenne-plugin</code>
goal that that drops
-				and/or generates tables in a database on Cayenne DataMap. By default, it is bound to
-				the pre-integration-test phase.<table frame="void">
+			<para><code>cdbgen</code> is a <code>maven-cayenne-plugin</code>
goal that drops and/or generates
+				tables in a database on Cayenne DataMap. By default, it is bound to the
+				pre-integration-test phase.<table frame="void">
 					<caption>cdbgen required parameters</caption>
 					<col width="14%"/>
 					<col width="6%"/>
@@ -364,6 +364,110 @@
 		</section>
 		<section xml:id="mvn-cdbimport">
 			<title>cdbimport</title>
+			<para><code>cdbimport</code> is a <code>maven-cayenne-plugin</code>
goal that generates
+				a DataMap based on an existing database schema. By default, it is bound to the
+				generate-sources phase. This allows you to generate your DataMap prior to building
+				your project, which may be necessary if you are also using the cgen task.<table
+					frame="void">
+					<caption>cdbimport required parameters</caption>
+					<col width="14%"/>
+					<col width="6%"/>
+					<col width="80%"/>
+					<thead>
+						<tr>
+							<th>Name</th>
+							<th>Type</th>
+							<th>Description</th>
+						</tr>
+					</thead>
+					<tbody>
+						<tr>
+							<td><code>map</code>
+							</td>
+							<td>File</td>
+							<td>DataMap XML file which is the destination of the schema import.
+								Maybe an existing file. If this file does not exist, it is created
+								when cdbimport is executed. E.g.
+									<code>${project.basedir}/src/main/resources/my.map.xml</code></td>
+						</tr>
+						<tr>
+							<td><code>driver</code></td>
+							<td>String</td>
+							<td>A class of JDBC driver to use for the target database.</td>
+						</tr>
+						<tr>
+							<td><code>url</code></td>
+							<td>String</td>
+							<td>JDBC connection URL of a target database.</td>
+						</tr>
+					</tbody>
+				</table></para>
+			<para>
+				<table frame="void" width="792">
+					<caption>cdbimport optional parameters</caption>
+					<col width="18%"/>
+					<col width="7%"/>
+					<col width="79%"/>
+					<thead>
+						<tr>
+							<th>Name</th>
+							<th>Type</th>
+							<th>Description</th>
+						</tr>
+					</thead>
+					<tbody>
+						<tr>
+							<td><code>adapter</code>
+							</td>
+							<td>String</td>
+							<td>Java class name implementing org.apache.cayenne.dba.DbAdapter. While
+								this attribute is optional (a generic JdbcAdapter is used if not
+								set), it is highly recommended to specify correct target
+								adapter.</td>
+						</tr>
+						<tr>
+							<td><code>createFK</code></td>
+							<td>boolean</td>
+							<td>Defines whether cdbgen should create foreign key constraints.
+								Default is "true".</td>
+						</tr>
+						<tr>
+							<td><code>createPK</code></td>
+							<td>boolean</td>
+							<td>Defines whether cdbgen should create Cayenne-specific auto PK
+								objects. Default is "true".</td>
+						</tr>
+						<tr>
+							<td><code>createTables</code></td>
+							<td>boolean</td>
+							<td>Defines whether cdbgen should create new tables. Default is
+								"true".</td>
+						</tr>
+						<tr>
+							<td><code>dropPK</code></td>
+							<td>boolean</td>
+							<td>Defines whether cdbgen should drop Cayenne primary key support
+								objects. Default is "false".</td>
+						</tr>
+						<tr>
+							<td><code>dropTables</code></td>
+							<td>boolean</td>
+							<td>Defines whether cdbgen should drop the tables before attempting to
+								create new ones. Default is "false".</td>
+						</tr>
+						<tr>
+							<td><code>password</code></td>
+							<td>String</td>
+							<td>Database user password.</td>
+						</tr>
+						<tr>
+							<td><code>username</code></td>
+							<td>String</td>
+							<td>Database user name.</td>
+						</tr>
+					</tbody>
+				</table>
+			</para>
 		</section>
 	</section>
 	<section xml:id="ant-projects">

Modified: cayenne/main/trunk/framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/DbImporterTask.java
URL: http://svn.apache.org/viewvc/cayenne/main/trunk/framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/DbImporterTask.java?rev=1299264&r1=1299263&r2=1299264&view=diff
==============================================================================
--- cayenne/main/trunk/framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/DbImporterTask.java
(original)
+++ cayenne/main/trunk/framework/cayenne-tools/src/main/java/org/apache/cayenne/tools/DbImporterTask.java
Sat Mar 10 20:12:49 2012
@@ -28,6 +28,7 @@ import org.apache.cayenne.map.ObjEntity;
 import org.apache.cayenne.map.DbEntity;
 import org.apache.cayenne.util.DeleteRuleUpdater;
 import org.apache.cayenne.util.Util;
+import org.apache.cayenne.util.XMLEncoder;
 import org.apache.cayenne.CayenneException;
 import org.apache.tools.ant.BuildException;
 import org.apache.tools.ant.Project;
@@ -49,25 +50,47 @@ public class DbImporterTask extends Caye
     @Override
     public void execute() {
 
-        log(String.format("connection settings - [driver: %s, url: %s, username: %s, password:
%s]", driver, url, userName, password), Project.MSG_VERBOSE);
-
-        log(String.format("importer options - [map: %s, overwriteExisting: %s, schemaName:
%s, tablePattern: %s, importProcedures: %s, procedurePattern: %s, meaningfulPk: %s, namingStrategy:
%s]",
-                map, overwriteExisting, schemaName, tablePattern, importProcedures, procedurePattern,
meaningfulPk, namingStrategy), Project.MSG_VERBOSE);
+        log(
+                String.format(
+                        "connection settings - [driver: %s, url: %s, username: %s, password:
%s]",
+                        driver,
+                        url,
+                        userName,
+                        password),
+                Project.MSG_VERBOSE);
+
+        log(
+                String.format(
+                        "importer options - [map: %s, overwriteExisting: %s, schemaName:
%s, tablePattern: %s, importProcedures: %s, procedurePattern: %s, meaningfulPk: %s, namingStrategy:
%s]",
+                        map,
+                        overwriteExisting,
+                        schemaName,
+                        tablePattern,
+                        importProcedures,
+                        procedurePattern,
+                        meaningfulPk,
+                        namingStrategy),
+                Project.MSG_VERBOSE);
 
         validateAttributes();
 
         try {
 
             // load driver taking custom CLASSPATH into account...
-            DriverDataSource dataSource = new DriverDataSource((Driver) Class.forName(driver).newInstance(),
url, userName, password);
+            DriverDataSource dataSource = new DriverDataSource((Driver) Class.forName(
+                    driver).newInstance(), url, userName, password);
 
             // Load the data map and run the db importer.
             final LoaderDelegate loaderDelegate = new LoaderDelegate();
-            final DbLoader loader = new DbLoader(dataSource.getConnection(), adapter, loaderDelegate);
+            final DbLoader loader = new DbLoader(
+                    dataSource.getConnection(),
+                    adapter,
+                    loaderDelegate);
             loader.setCreatingMeaningfulPK(meaningfulPk);
 
             if (namingStrategy != null) {
-                final NamingStrategy namingStrategyInst = (NamingStrategy) Class.forName(namingStrategy).newInstance();
+                final NamingStrategy namingStrategyInst = (NamingStrategy) Class.forName(
+                        namingStrategy).newInstance();
                 loader.setNamingStrategy(namingStrategyInst);
             }
 
@@ -85,9 +108,14 @@ public class DbImporterTask extends Caye
             // Write the new DataMap out to disk.
             map.delete();
             PrintWriter pw = new PrintWriter(map);
-            dataMap.encodeAsXML(pw);
+            
+            XMLEncoder encoder = new XMLEncoder(pw, "\t");
+            encoder.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
+            dataMap.encodeAsXML(encoder);
+
             pw.close();
-        } catch (final Exception ex) {
+        }
+        catch (final Exception ex) {
             final Throwable th = Util.unwindException(ex);
 
             String message = "Error importing database schema";
@@ -155,25 +183,30 @@ public class DbImporterTask extends Caye
 
     final class LoaderDelegate extends AbstractDbLoaderDelegate {
 
+        @Override
         public boolean overwriteDbEntity(final DbEntity ent) throws CayenneException {
             return overwriteExisting;
         }
 
+        @Override
         public void dbEntityAdded(final DbEntity ent) {
             super.dbEntityAdded(ent);
             log("Added DB entity: " + ent.getName());
         }
 
+        @Override
         public void dbEntityRemoved(final DbEntity ent) {
             super.dbEntityRemoved(ent);
             log("Removed DB entity: " + ent.getName());
         }
 
+        @Override
         public void objEntityAdded(final ObjEntity ent) {
             super.objEntityAdded(ent);
             log("Added obj entity: " + ent.getName());
         }
 
+        @Override
         public void objEntityRemoved(final ObjEntity ent) {
             super.objEntityRemoved(ent);
             log("Removed obj entity: " + ent.getName());

Modified: cayenne/main/trunk/framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/DbImporterMojo.java
URL: http://svn.apache.org/viewvc/cayenne/main/trunk/framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/DbImporterMojo.java?rev=1299264&r1=1299263&r2=1299264&view=diff
==============================================================================
--- cayenne/main/trunk/framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/DbImporterMojo.java
(original)
+++ cayenne/main/trunk/framework/maven-cayenne-plugin/src/main/java/org/apache/cayenne/tools/DbImporterMojo.java
Sat Mar 10 20:12:49 2012
@@ -19,256 +19,275 @@
 
 package org.apache.cayenne.tools;
 
-import org.apache.maven.plugin.AbstractMojo;
-import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
-import org.apache.cayenne.configuration.ToolModule;
-import org.apache.cayenne.map.DataMap;
-import org.apache.cayenne.map.DbEntity;
-import org.apache.cayenne.map.ObjEntity;
-import org.apache.cayenne.map.MapLoader;
-import org.apache.cayenne.map.naming.NamingStrategy;
-import org.apache.cayenne.access.DbLoader;
+import java.io.File;
+import java.io.PrintWriter;
+import java.sql.Driver;
+
+import org.apache.cayenne.CayenneException;
 import org.apache.cayenne.access.AbstractDbLoaderDelegate;
+import org.apache.cayenne.access.DbLoader;
+import org.apache.cayenne.configuration.ToolModule;
+import org.apache.cayenne.conn.DriverDataSource;
 import org.apache.cayenne.dba.DbAdapter;
 import org.apache.cayenne.dba.JdbcAdapter;
 import org.apache.cayenne.di.AdhocObjectFactory;
 import org.apache.cayenne.di.DIBootstrap;
 import org.apache.cayenne.di.Injector;
-import org.apache.cayenne.util.Util;
+import org.apache.cayenne.map.DataMap;
+import org.apache.cayenne.map.DbEntity;
+import org.apache.cayenne.map.MapLoader;
+import org.apache.cayenne.map.ObjEntity;
+import org.apache.cayenne.map.naming.NamingStrategy;
 import org.apache.cayenne.util.DeleteRuleUpdater;
-import org.apache.cayenne.conn.DriverDataSource;
-import org.apache.cayenne.CayenneException;
+import org.apache.cayenne.util.Util;
+import org.apache.cayenne.util.XMLEncoder;
 import org.apache.commons.logging.Log;
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
 import org.xml.sax.InputSource;
 
-import java.io.File;
-import java.io.PrintWriter;
-import java.sql.Driver;
-
 /**
  * Maven mojo to reverse engineer datamap from DB.
- *
+ * 
  * @since 3.0
- *
+ * 
  * @phase generate-sources
  * @goal cdbimport
  */
 public class DbImporterMojo extends AbstractMojo {
 
-    /**
+	/**
 	 * DataMap XML file to use as a base for DB importing.
-	 *
+	 * 
 	 * @parameter expression="${cdbimport.map}"
 	 * @required
 	 */
-	private String map;
+	private File map;
+
+	/**
+	 * Indicates whether existing DB and object entities should be overwritten.
+	 * This is an all-or-nothing setting. If you need finer granularity, please
+	 * use the Cayenne Modeler.
+	 * 
+	 * Default is <code>true</code>.
+	 * 
+	 * @parameter expression="${cdbimport.overwriteExisting}"
+	 *            default-value="true"
+	 */
+	private boolean overwriteExisting;
+
+	/**
+	 * DB schema to use for DB importing.
+	 * 
+	 * @parameter expression="${cdbimport.schemaName}"
+	 */
+	private String schemaName;
+
+	/**
+	 * Pattern for tables to import from DB.
+	 * 
+	 * The default is to match against all tables.
+	 * 
+	 * @parameter expression="${cdbimport.tablePattern}"
+	 */
+	private String tablePattern;
+
+	/**
+	 * Indicates whether stored procedures should be imported.
+	 * 
+	 * Default is <code>false</code>.
+	 * 
+	 * @parameter expression="${cdbimport.importProcedures}"
+	 *            default-value="false"
+	 */
+	private boolean importProcedures;
+
+	/**
+	 * Pattern for stored procedures to import from DB. This is only meaningful
+	 * if <code>importProcedures</code> is set to <code>true</code>.
+	 * 
+	 * The default is to match against all stored procedures.
+	 * 
+	 * @parameter expression="${cdbimport.procedurePattern}"
+	 */
+	private String procedurePattern;
+
+	/**
+	 * Indicates whether primary keys should be mapped as meaningful attributes
+	 * in the object entities.
+	 * 
+	 * Default is <code>false</code>.
+	 * 
+	 * @parameter expression="${cdbimport.meaningfulPk}" default-value="false"
+	 */
+	private boolean meaningfulPk;
+
+	/**
+	 * Java class implementing org.apache.cayenne.map.naming.NamingStrategy.
+	 * This is used to specify how ObjEntities will be mapped from the imported
+	 * DB schema.
+	 * 
+	 * The default is a basic naming strategy.
+	 * 
+	 * @parameter expression="${cdbimport.namingStrategy}"
+	 *            default-value="org.apache.cayenne.map.naming.SmartNamingStrategy"
+	 */
+	private String namingStrategy;
+
+	/**
+	 * Java class implementing org.apache.cayenne.dba.DbAdapter. While this
+	 * attribute is optional (a generic JdbcAdapter is used if not set), it is
+	 * highly recommended to specify correct target adapter.
+	 * 
+	 * @parameter expression="${cdbimport.adapter}"
+	 */
+	private String adapter;
+
+	/**
+	 * A class of JDBC driver to use for the target database.
+	 * 
+	 * @parameter expression="${cdbimport.driver}"
+	 * @required
+	 */
+	private String driver;
+
+	/**
+	 * JDBC connection URL of a target database.
+	 * 
+	 * @parameter expression="${cdbimport.url}"
+	 * @required
+	 */
+	private String url;
+
+	/**
+	 * Database user name.
+	 * 
+	 * @parameter expression="${cdbimport.username}"
+	 */
+	private String username;
+
+	/**
+	 * Database user password.
+	 * 
+	 * @parameter expression="${cdbimport.password}"
+	 */
+	private String password;
+
+	/**
+	 * Maven logger.
+	 */
+	private Log logger;
+
+	public void execute() throws MojoExecutionException, MojoFailureException {
 
-    /**
-     * Indicates whether existing DB and object entities should be overwritten.
-     * This is an all-or-nothing setting.  If you need finer granularity, please
-     * use the Cayenne Modeler.
-     *
-     * Default is <code>true</code>.
-     *
-     * @parameter expression="${cdbimport.overwriteExisting}" default-value="true"
-     */
-    private boolean overwriteExisting;
-
-    /**
-     * DB schema to use for DB importing.
-     *
-     * @parameter expression="${cdbimport.schemaName}"
-     */
-    private String schemaName;
-
-    /**
-     * Pattern for tables to import from DB.
-     *
-     * The default is to match against all tables.
-     *
-     * @parameter expression="${cdbimport.tablePattern}"
-     */
-    private String tablePattern;
-
-    /**
-     * Indicates whether stored procedures should be imported.
-     *
-     * Default is <code>false</code>.
-     *
-     * @parameter expression="${cdbimport.importProcedures}" default-value="false"
-     */
-    private boolean importProcedures;
-
-    /**
-     * Pattern for stored procedures to import from DB.  This is only meaningful if
-     * <code>importProcedures</code> is set to <code>true</code>.
-     *
-     * The default is to match against all stored procedures.
-     *
-     * @parameter expression="${cdbimport.procedurePattern}"
-     */
-    private String procedurePattern;
-
-    /**
-     * Indicates whether primary keys should be mapped as meaningful attributes in the object
entities.
-     *
-     * Default is <code>false</code>.
-     *
-     * @parameter expression="${cdbimport.meaningfulPk}" default-value="false"
-     */
-    private boolean meaningfulPk;
-
-    /**
-     * Java class implementing org.apache.cayenne.map.naming.NamingStrategy.
-     * This is used to specify how ObjEntities will be mapped from the imported DB schema.
-     *
-     * The default is a basic naming strategy.
-     *
-     * @parameter expression="${cdbimport.namingStrategy}" default-value="org.apache.cayenne.map.naming.SmartNamingStrategy"
-     */
-    private String namingStrategy;
-
-    /**
-     * Java class implementing org.apache.cayenne.dba.DbAdapter.
-     * While this attribute is optional (a generic JdbcAdapter is used if not set),
-     * it is highly recommended to specify correct target adapter.
-     *
-     * @parameter expression="${cdbimport.adapter}"
-     */
-    private String adapter;
-    
-    /**
-     * A class of JDBC driver to use for the target database.
-     *
-     * @parameter expression="${cdbimport.driver}"
-     * @required
-     */
-    private String driver;
-
-    /**
-     * JDBC connection URL of a target database.
-     *
-     * @parameter expression="${cdbimport.url}"
-     * @required
-     */
-    private String url;
-
-    /**
-     * Database user name.
-     *
-     * @parameter expression="${cdbimport.username}"
-     */
-    private String username;
-
-    /**
-     * Database user password.
-     *
-     * @parameter expression="${cdbimport.password}"
-     */
-    private String password;
-
-    /**
-     * Maven logger.
-     */
-    private Log logger;
-
-    /**
-     * The DataMap file to use for importing.
-     */
-    private File mapFile;
-
-    public void execute() throws MojoExecutionException, MojoFailureException {
-    	
-    	Injector injector = DIBootstrap.createInjector(new ToolModule());
-    	AdhocObjectFactory objectFactory = injector.getInstance(AdhocObjectFactory.class);
-
-        logger = new MavenLogger(this);
-
-        logger.debug(String.format("connection settings - [driver: %s, url: %s, username:
%s, password: %s]", driver, url, username, password));
-
-        logger.info(String.format("importer options - [map: %s, overwriteExisting: %s, schemaName:
%s, tablePattern: %s, importProcedures: %s, procedurePattern: %s, meaningfulPk: %s, namingStrategy:
%s]",
-                map, overwriteExisting, schemaName, tablePattern, importProcedures, procedurePattern,
meaningfulPk, namingStrategy));
-
-        try {
-            final DbAdapter adapterInst = (adapter == null) ? 
-                    (DbAdapter)objectFactory.newInstance(DbAdapter.class, JdbcAdapter.class.getName())
: 
-                    (DbAdapter)objectFactory.newInstance(DbAdapter.class, adapter);
-
-            // load driver taking custom CLASSPATH into account...
-            DriverDataSource dataSource = new DriverDataSource((Driver) Class.forName(driver).newInstance(),
url, username, password);
-
-            // Load the data map and run the db importer.
-            final LoaderDelegate loaderDelegate = new LoaderDelegate();
-            final DbLoader loader = new DbLoader(dataSource.getConnection(), adapterInst,
loaderDelegate);
-            loader.setCreatingMeaningfulPK(meaningfulPk);
-
-            if (namingStrategy != null) {
-                final NamingStrategy namingStrategyInst = (NamingStrategy) Class.forName(namingStrategy).newInstance();
-                loader.setNamingStrategy(namingStrategyInst);
-            }
-
-            mapFile = new File(map);
-            final DataMap dataMap = mapFile.exists() ? loadDataMap() : new DataMap();
-            loader.loadDataMapFromDB(schemaName, tablePattern, dataMap);
-
-            for (ObjEntity addedObjEntity : loaderDelegate.getAddedObjEntities()) {
-                DeleteRuleUpdater.updateObjEntity(addedObjEntity);
-            }
-
-            if (importProcedures) {
-                loader.loadProceduresFromDB(schemaName, procedurePattern, dataMap);
-            }
-
-            // Write the new DataMap out to disk.
-            mapFile.delete();
-            PrintWriter pw = new PrintWriter(mapFile);
-            dataMap.encodeAsXML(pw);
-            pw.close();
-        } catch (final Exception ex) {
-            final Throwable th = Util.unwindException(ex);
-
-            String message = "Error importing database schema";
-
-            if (th.getLocalizedMessage() != null) {
-                message += ": " + th.getLocalizedMessage();
-            }
-
-            logger.error(message);
-            throw new MojoExecutionException(message, th);
-        }
-    }
-
-    final class LoaderDelegate extends AbstractDbLoaderDelegate {
-       
-        public boolean overwriteDbEntity(final DbEntity ent) throws CayenneException {
-            return overwriteExisting;
-        }
-
-        public void dbEntityAdded(final DbEntity ent) {
-            super.dbEntityAdded(ent);
-            logger.info("Added DB entity: " + ent.getName());
-        }
-
-        public void dbEntityRemoved(final DbEntity ent) {
-            super.dbEntityRemoved(ent);
-            logger.info("Removed DB entity: " + ent.getName());
-        }
-
-        public void objEntityAdded(final ObjEntity ent) {
-            super.objEntityAdded(ent);
-            logger.info("Added obj entity: " + ent.getName());
-        }
-
-        public void objEntityRemoved(final ObjEntity ent) {
-            super.objEntityRemoved(ent);
-            logger.info("Removed obj entity: " + ent.getName());
-        }
-    }
-
-    /** Loads and returns DataMap based on <code>map</code> attribute. */
-    protected DataMap loadDataMap() throws Exception {
-        final InputSource in = new InputSource(mapFile.getCanonicalPath());
-        return new MapLoader().loadDataMap(in);
-    }
+		Injector injector = DIBootstrap.createInjector(new ToolModule());
+		AdhocObjectFactory objectFactory = injector
+				.getInstance(AdhocObjectFactory.class);
+
+		logger = new MavenLogger(this);
+
+		logger.debug(String
+				.format("connection settings - [driver: %s, url: %s, username: %s, password: %s]",
+						driver, url, username, password));
+
+		logger.info(String
+				.format("importer options - [map: %s, overwriteExisting: %s, schemaName: %s, tablePattern:
%s, importProcedures: %s, procedurePattern: %s, meaningfulPk: %s, namingStrategy: %s]",
+						map, overwriteExisting, schemaName, tablePattern,
+						importProcedures, procedurePattern, meaningfulPk,
+						namingStrategy));
+
+		try {
+			final DbAdapter adapterInst = (adapter == null) ? (DbAdapter) objectFactory
+					.newInstance(DbAdapter.class, JdbcAdapter.class.getName())
+					: (DbAdapter) objectFactory.newInstance(DbAdapter.class,
+							adapter);
+
+			// load driver taking custom CLASSPATH into account...
+			DriverDataSource dataSource = new DriverDataSource((Driver) Class
+					.forName(driver).newInstance(), url, username, password);
+
+			// Load the data map and run the db importer.
+			final LoaderDelegate loaderDelegate = new LoaderDelegate();
+			final DbLoader loader = new DbLoader(dataSource.getConnection(),
+					adapterInst, loaderDelegate);
+			loader.setCreatingMeaningfulPK(meaningfulPk);
+
+			if (namingStrategy != null) {
+				final NamingStrategy namingStrategyInst = (NamingStrategy) Class
+						.forName(namingStrategy).newInstance();
+				loader.setNamingStrategy(namingStrategyInst);
+			}
+
+			final DataMap dataMap = map.exists() ? loadDataMap()
+					: new DataMap();
+			loader.loadDataMapFromDB(schemaName, tablePattern, dataMap);
+
+			for (ObjEntity addedObjEntity : loaderDelegate
+					.getAddedObjEntities()) {
+				DeleteRuleUpdater.updateObjEntity(addedObjEntity);
+			}
+
+			if (importProcedures) {
+				loader.loadProceduresFromDB(schemaName, procedurePattern,
+						dataMap);
+			}
+
+			// Write the new DataMap out to disk.
+			map.delete();
+
+			PrintWriter pw = new PrintWriter(map);
+			XMLEncoder encoder = new XMLEncoder(pw, "\t");
+
+			encoder.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
+			dataMap.encodeAsXML(encoder);
+
+			pw.close();
+		} catch (Exception ex) {
+			Throwable th = Util.unwindException(ex);
+
+			String message = "Error importing database schema";
+
+			if (th.getLocalizedMessage() != null) {
+				message += ": " + th.getLocalizedMessage();
+			}
+
+			logger.error(message);
+			throw new MojoExecutionException(message, th);
+		}
+	}
+
+	final class LoaderDelegate extends AbstractDbLoaderDelegate {
+
+		public boolean overwriteDbEntity(final DbEntity ent)
+				throws CayenneException {
+			return overwriteExisting;
+		}
+
+		public void dbEntityAdded(final DbEntity ent) {
+			super.dbEntityAdded(ent);
+			logger.info("Added DB entity: " + ent.getName());
+		}
+
+		public void dbEntityRemoved(final DbEntity ent) {
+			super.dbEntityRemoved(ent);
+			logger.info("Removed DB entity: " + ent.getName());
+		}
+
+		public void objEntityAdded(final ObjEntity ent) {
+			super.objEntityAdded(ent);
+			logger.info("Added obj entity: " + ent.getName());
+		}
+
+		public void objEntityRemoved(final ObjEntity ent) {
+			super.objEntityRemoved(ent);
+			logger.info("Removed obj entity: " + ent.getName());
+		}
+	}
+
+	/** Loads and returns DataMap based on <code>map</code> attribute. */
+	protected DataMap loadDataMap() throws Exception {
+		final InputSource in = new InputSource(map.getCanonicalPath());
+		return new MapLoader().loadDataMap(in);
+	}
 }



Mime
View raw message