You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tomee.apache.org by rm...@apache.org on 2012/03/16 14:41:08 UTC

svn commit: r1301509 - in /openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb: assembler/classic/ resource/jdbc/

Author: rmannibucau
Date: Fri Mar 16 13:41:07 2012
New Revision: 1301509

URL: http://svn.apache.org/viewvc?rev=1301509&view=rev
Log:
OPENEJB-1799 small refactoring to be able to use auto import of sql file for datasources too

Added:
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ImportSql.java
Modified:
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/EntityManagerFactoryCallable.java
    openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/DataSourceFactory.java

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java?rev=1301509&r1=1301508&r2=1301509&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/Assembler.java Fri Mar 16 13:41:07 2012
@@ -117,6 +117,7 @@ import javax.resource.spi.ResourceAdapte
 import javax.resource.spi.ResourceAdapterInternalException;
 import javax.resource.spi.XATerminator;
 import javax.resource.spi.work.WorkManager;
+import javax.sql.DataSource;
 import javax.transaction.TransactionManager;
 import javax.transaction.TransactionSynchronizationRegistry;
 import javax.validation.ValidationException;
@@ -1579,6 +1580,18 @@ public class Assembler extends Assembler
             // service becomes a ConnectorReference which merges connection manager and mcf
             service = new ConnectorReference(connectionManager, managedConnectionFactory);
         } else {
+            if (service instanceof DataSource) {
+                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+                if (classLoader == null) {
+                    classLoader = getClass().getClassLoader();
+                }
+
+                final ImportSql importer = new ImportSql(classLoader, serviceInfo.id, (DataSource) service);
+                if (importer.hasSomethingToImport()) {
+                    importer.doImport();
+                }
+            }
+
             logUnusedProperties(serviceRecipe, serviceInfo);
         }
 

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/EntityManagerFactoryCallable.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/EntityManagerFactoryCallable.java?rev=1301509&r1=1301508&r2=1301509&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/EntityManagerFactoryCallable.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/EntityManagerFactoryCallable.java Fri Mar 16 13:41:07 2012
@@ -16,34 +16,15 @@
  */
 package org.apache.openejb.assembler.classic;
 
-import org.apache.openejb.OpenEJBRuntimeException;
 import org.apache.openejb.persistence.PersistenceUnitInfoImpl;
-import org.apache.openejb.util.LogCategory;
-import org.apache.openejb.util.Logger;
 
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.spi.PersistenceProvider;
-import javax.sql.DataSource;
-import java.io.BufferedInputStream;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.sql.Statement;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.concurrent.Callable;
 
 public class EntityManagerFactoryCallable implements Callable<EntityManagerFactory> {
-    private static final Logger LOGGER = Logger.getInstance(LogCategory.OPENEJB, EntityManagerFactoryCallable.class.getName());
-
-    public static final String IMPORT_FILE_PREFIX = "import-";
-    public static final String IMPORT_FILE_EXTENSION = ".sql";
-
     private final String persistenceProviderClassName;
     private final PersistenceUnitInfoImpl unitInfo;
 
@@ -63,105 +44,14 @@ public class EntityManagerFactoryCallabl
         properties.put("javax.persistence.validator.ValidatorFactory", new ValidatorFactoryWrapper());
         EntityManagerFactory emf = persistenceProvider.createContainerEntityManagerFactory(unitInfo, properties);
 
-        importSqlScripts(appClassLoader, emf);
-
-        return emf;
-    }
-
-    private void importSqlScripts(final ClassLoader cl, final EntityManagerFactory emf) {
-        final Enumeration<URL> imports;
-        try {
-            imports = cl.getResources(IMPORT_FILE_PREFIX.concat(unitInfo.getPersistenceUnitName()).concat(IMPORT_FILE_EXTENSION));
-        } catch (IOException e) {
-            throw new OpenEJBRuntimeException("can't look for init sql script", e);
-        }
-
-        Statement statement;
-        if (imports.hasMoreElements()) {
-            // force OpenJPA to initialize the database if configured this way
-            // doing it this way let us be provider independent
-            emf.createEntityManager().close();
-
-            final DataSource ds = unitInfo.getNonJtaDataSource();
-            if (ds == null) {
-                LOGGER.error("no non jta datasource for unit " + unitInfo.getPersistenceUnitName() + "; import script will be ignored.");
-                return;
-            }
-
-            Connection connection = null;
-            try {
-                connection = ds.getConnection();
-                statement = connection.createStatement();
-            } catch (SQLException e) {
-                LOGGER.error("can't create a statement, import scripts will be ignored", e);
-                if (connection != null) {
-                    try {
-                        connection.close();
-                    } catch (SQLException ignored) {
-                        // no-op
-                    }
-                }
-                return;
-            }
-
-            try {
-                while (imports.hasMoreElements()) {
-                    final URL scriptToImport = imports.nextElement();
-                    LOGGER.info("importing " + scriptToImport.toExternalForm());
-
-                    importSql(scriptToImport, statement);
-                }
-            } finally {
-                try {
-                    connection.close();
-                } catch (SQLException e) {
-                    // ignored
-                }
-            }
-        }
-    }
 
-    private void importSql(final URL script, final Statement statement) {
-        final BufferedReader bufferedReader;
-        try {
-            bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(script.openStream())));
-        } catch (IOException e) {
-            LOGGER.error("can't open " + script.toExternalForm(), e);
-            return;
+        final ImportSql importer = new ImportSql(appClassLoader, unitInfo.getPersistenceUnitName(), unitInfo.getNonJtaDataSource());
+        if (importer.hasSomethingToImport()) {
+            emf.createEntityManager().close(); // to let OpenJPA create the database if configured this way
+            importer.doImport();
         }
 
-        try {
-            for (String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine()) {
-                String trimmedSql = sql.trim();
-
-                // empty or comment
-                if (trimmedSql.isEmpty() || trimmedSql.startsWith("--") || trimmedSql.startsWith("//") || trimmedSql.startsWith("/*")) {
-                    continue;
-                }
-
-                if (trimmedSql.endsWith(";")) {
-                    trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1);
-                }
-
-                try {
-                    if (!trimmedSql.toLowerCase().startsWith("select")) {
-                        statement.executeUpdate(trimmedSql);
-                    } else { // why could it be the case?
-                        statement.executeQuery(trimmedSql);
-                    }
-
-                    SQLWarning warnings = statement.getWarnings();
-                    while (warnings != null) {
-                        LOGGER.warning(warnings.getMessage());
-                        warnings = warnings.getNextWarning();
-                    }
-                } catch (SQLException e) {
-                    LOGGER.error("error importing script " + script.toExternalForm(), e);
-                }
-            }
-        } catch (IOException e) {
-            LOGGER.error("can't import " + script.toExternalForm(), e);
-        }
+        return emf;
     }
 
     public PersistenceUnitInfoImpl getUnitInfo() {

Added: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ImportSql.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ImportSql.java?rev=1301509&view=auto
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ImportSql.java (added)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/ImportSql.java Fri Mar 16 13:41:07 2012
@@ -0,0 +1,127 @@
+package org.apache.openejb.assembler.classic;
+
+import org.apache.openejb.OpenEJBRuntimeException;
+import org.apache.openejb.util.LogCategory;
+import org.apache.openejb.util.Logger;
+
+import javax.sql.DataSource;
+import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.util.Enumeration;
+
+public class ImportSql {
+    private static final Logger LOGGER = Logger.getInstance(LogCategory.OPENEJB, EntityManagerFactoryCallable.class.getName());
+
+    public static final String IMPORT_FILE_PREFIX = "import-";
+    public static final String IMPORT_FILE_EXTENSION = ".sql";
+
+    private final DataSource dataSource;
+    private boolean done;
+    private final Enumeration<URL> imports;
+
+    public ImportSql(final ClassLoader cl, final String resource, final DataSource ds) {
+        dataSource = ds;
+        done = false;
+
+        if (dataSource == null) {
+            throw new NullPointerException("datasource can't be null");
+        }
+
+        try {
+            imports = cl.getResources(IMPORT_FILE_PREFIX.concat(resource).concat(IMPORT_FILE_EXTENSION));
+        } catch (IOException e) {
+            throw new OpenEJBRuntimeException("can't look for init sql script", e);
+        }
+    }
+
+    public boolean hasSomethingToImport() {
+        return !done && imports != null && imports.hasMoreElements();
+    }
+
+    public void doImport() {
+        Statement statement;
+        if (hasSomethingToImport()) {
+            Connection connection = null;
+            try {
+                connection = dataSource.getConnection();
+                statement = connection.createStatement();
+            } catch (SQLException e) {
+                LOGGER.error("can't create a statement, import scripts will be ignored", e);
+                if (connection != null) {
+                    try {
+                        connection.close();
+                    } catch (SQLException ignored) {
+                        // no-op
+                    }
+                }
+                return;
+            }
+
+            try {
+                while (imports.hasMoreElements()) {
+                    final URL scriptToImport = imports.nextElement();
+                    LOGGER.info("importing " + scriptToImport.toExternalForm());
+
+                    importSql(scriptToImport, statement);
+                }
+            } finally {
+                try {
+                    connection.close();
+                } catch (SQLException e) {
+                    // ignored
+                }
+                done = true;
+            }
+        }
+    }
+
+    private void importSql(final URL script, final Statement statement) {
+        final BufferedReader bufferedReader;
+        try {
+            bufferedReader = new BufferedReader(new InputStreamReader(new BufferedInputStream(script.openStream())));
+        } catch (IOException e) {
+            LOGGER.error("can't open " + script.toExternalForm(), e);
+            return;
+        }
+
+        try {
+            for (String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine()) {
+                String trimmedSql = sql.trim();
+
+                // empty or comment
+                if (trimmedSql.isEmpty() || trimmedSql.startsWith("--") || trimmedSql.startsWith("//") || trimmedSql.startsWith("/*")) {
+                    continue;
+                }
+
+                if (trimmedSql.endsWith(";")) {
+                    trimmedSql = trimmedSql.substring(0, trimmedSql.length() - 1);
+                }
+
+                try {
+                    if (!trimmedSql.toLowerCase().startsWith("select")) {
+                        statement.executeUpdate(trimmedSql);
+                    } else { // why could it be the case?
+                        statement.executeQuery(trimmedSql);
+                    }
+
+                    SQLWarning warnings = statement.getWarnings();
+                    while (warnings != null) {
+                        LOGGER.warning(warnings.getMessage());
+                        warnings = warnings.getNextWarning();
+                    }
+                } catch (SQLException e) {
+                    LOGGER.error("error importing script " + script.toExternalForm(), e);
+                }
+            }
+        } catch (IOException e) {
+            LOGGER.error("can't import " + script.toExternalForm(), e);
+        }
+    }
+}

Modified: openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/DataSourceFactory.java
URL: http://svn.apache.org/viewvc/openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/DataSourceFactory.java?rev=1301509&r1=1301508&r2=1301509&view=diff
==============================================================================
--- openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/DataSourceFactory.java (original)
+++ openejb/trunk/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/jdbc/DataSourceFactory.java Fri Mar 16 13:41:07 2012
@@ -30,7 +30,6 @@ import org.apache.xbean.recipe.Option;
 
 import javax.sql.DataSource;
 import javax.sql.XADataSource;
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;