scriptPatches,
boolean apply) throws Exception
{
// first check if there have been any applied patches
int appliedPatchCount = countAppliedPatches(connection);
if (appliedPatchCount == 0)
{
// This is a new schema, so upgrade scripts are irrelevant
// and patches will not have been applied yet
return;
}
for (SchemaUpgradeScriptPatch patch : scriptPatches)
{
final String patchId = patch.getId();
final String scriptUrl = patch.getScriptUrl();
// check if the script was successfully executed
boolean wasSuccessfullyApplied = didPatchSucceed(connection, patchId);
if (wasSuccessfullyApplied)
{
// Either the patch was executed before or the system was bootstrapped
// with the patch bean present.
continue;
}
else if (!apply)
{
// the script was not run and may not be run automatically
throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_RUN, scriptUrl);
}
// it wasn't run and it can be run now
executeScriptUrl(cfg, connection, scriptUrl);
}
}
private void executeScriptUrl(Configuration cfg, Connection connection, String scriptUrl) throws Exception
{
Dialect dialect = Dialect.getDialect(cfg.getProperties());
String dialectStr = dialect.getClass().getName();
InputStream scriptInputStream = getScriptInputStream(dialect.getClass(), scriptUrl);
// check that it exists
if (scriptInputStream == null)
{
throw AlfrescoRuntimeException.create(ERR_SCRIPT_NOT_FOUND, scriptUrl);
}
// write the script to a temp location for future and failure reference
File tempFile = null;
try
{
tempFile = TempFileProvider.createTempFile("AlfrescoSchemaUpdate-" + dialectStr + "-", ".sql");
ContentWriter writer = new FileContentWriter(tempFile);
writer.putContent(scriptInputStream);
}
finally
{
try { scriptInputStream.close(); } catch (Throwable e) {} // usually a duplicate close
}
// now execute it
executeScriptFile(cfg, connection, tempFile, scriptUrl);
}
/**
* Replaces the dialect placeholder in the script URL and attempts to find a file for
* it. If not found, the dialect hierarchy will be walked until a compatible script is
* found. This makes it possible to have scripts that are generic to all dialects.
*
* @return Returns an input stream onto the script, otherwise null
*/
private InputStream getScriptInputStream(Class dialectClazz, String scriptUrl) throws Exception
{
// replace the dialect placeholder
String dialectScriptUrl = scriptUrl.replaceAll(PLACEHOLDER_SCRIPT_DIALECT, dialectClazz.getName());
// get a handle on the resource
ResourcePatternResolver rpr = new PathMatchingResourcePatternResolver(this.getClass().getClassLoader());
Resource resource = rpr.getResource(dialectScriptUrl);
if (!resource.exists())
{
// it wasn't found. Get the superclass of the dialect and try again
Class superClazz = dialectClazz.getSuperclass();
if (Dialect.class.isAssignableFrom(superClazz))
{
// we still have a Dialect - try again
return getScriptInputStream(superClazz, scriptUrl);
}
else
{
// we have exhausted all options
return null;
}
}
else
{
// we have a handle to it
return resource.getInputStream();
}
}
private void executeScriptFile(
Configuration cfg,
Connection connection,
File scriptFile,
String scriptUrl) throws Exception
{
logger.info(I18NUtil.getMessage(MSG_EXECUTING_SCRIPT, scriptUrl));
InputStream scriptInputStream = new FileInputStream(scriptFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(scriptInputStream, "UTF8"));
try
{
int line = 0;
// loop through all statements
StringBuilder sb = new StringBuilder(1024);
while(true)
{
String sql = reader.readLine();
line++;
if (sql == null)
{
// nothing left in the file
break;
}
// trim it
sql = sql.trim();
if (sql.length() == 0 ||
sql.startsWith( "--" ) ||
sql.startsWith( "//" ) ||
sql.startsWith( "/*" ) )
{
if (sb.length() > 0)
{
// we have an unterminated statement
throw AlfrescoRuntimeException.create(ERR_STATEMENT_TERMINATOR, (line - 1), scriptUrl);
}
// there has not been anything to execute - it's just a comment line
continue;
}
// have we reached the end of a statement?
boolean execute = false;
boolean optional = false;
if (sql.endsWith(";"))
{
sql = sql.substring(0, sql.length() - 1);
execute = true;
optional = false;
}
else if (sql.endsWith(";(optional)"))
{
sql = sql.substring(0, sql.length() - 11);
execute = true;
optional = true;
}
// append to the statement being built up
sb.append(" ").append(sql);
// execute, if required
if (execute)
{
sql = sb.toString();
executeStatement(connection, sql, optional, line, scriptFile);
sb = new StringBuilder(1024);
}
}
}
finally
{
try { reader.close(); } catch (Throwable e) {}
try { scriptInputStream.close(); } catch (Throwable e) {}
}
}
/**
* Execute the given SQL statement, absorbing exceptions that we expect during
* schema creation or upgrade.
*/
private void executeStatement(Connection connection, String sql, boolean optional, int line, File file) throws Exception
{
Statement stmt = connection.createStatement();
try
{
if (logger.isDebugEnabled())
{
logger.debug("Executing statement: " + sql);
}
stmt.execute(sql);
}
catch (SQLException e)
{
if (optional)
{
// it was marked as optional, so we just ignore it
String msg = I18NUtil.getMessage(MSG_OPTIONAL_STATEMENT_FAILED, sql, e.getMessage(), file.getAbsolutePath(), line);
logger.debug(msg);
}
else
{
String err = I18NUtil.getMessage(ERR_STATEMENT_FAILED, sql, e.getMessage(), file.getAbsolutePath(), line);
logger.error(err);
throw e;
}
}
finally
{
try { stmt.close(); } catch (Throwable e) {}
}
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
// do everything in a transaction
Session session = getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
try
{
// make sure that we don't autocommit
Connection connection = session.connection();
connection.setAutoCommit(false);
Configuration cfg = localSessionFactory.getConfiguration();
// Ensure that our static connection provider is used
String defaultConnectionProviderFactoryClass = cfg.getProperty(Environment.CONNECTION_PROVIDER);
cfg.setProperty(Environment.CONNECTION_PROVIDER, SchemaBootstrapConnectionProvider.class.getName());
SchemaBootstrapConnectionProvider.setBootstrapConnection(connection);
// dump the schema, if required
if (schemaOuputFilename != null)
{
File schemaOutputFile = new File(schemaOuputFilename);
dumpSchemaCreate(cfg, schemaOutputFile);
}
// update the schema, if required
if (updateSchema)
{
updateSchema(cfg, session, connection);
}
// verify that all patches have been applied correctly
checkSchemaPatchScripts(cfg, session, connection, validateUpdateScriptPatches, false); // check scripts
checkSchemaPatchScripts(cfg, session, connection, preUpdateScriptPatches, false); // check scripts
checkSchemaPatchScripts(cfg, session, connection, postUpdateScriptPatches, false); // check scripts
// Reset the configuration
cfg.setProperty(Environment.CONNECTION_PROVIDER, defaultConnectionProviderFactoryClass);
// all done successfully
transaction.commit();
}
catch (Throwable e)
{
try { transaction.rollback(); } catch (Throwable ee) {}
if (updateSchema)
{
throw new AlfrescoRuntimeException(ERR_UPDATE_FAILED, e);
}
else
{
throw new AlfrescoRuntimeException(ERR_VALIDATION_FAILED, e);
}
}
finally
{
// Remove the connection reference from the threadlocal boostrap
SchemaBootstrapConnectionProvider.setBootstrapConnection(null);
}
}
@Override
protected void onShutdown(ApplicationEvent event)
{
// NOOP
}
/**
* This is a workaround for the odd Spring-Hibernate interaction during configuration.
* The Hibernate code assumes that schema scripts will be generated during context
* initialization. We want to do it afterwards and have a little more control. Hence this class.
*
* The connection that is used will not be closed or manipulated in any way. This class
* merely serves to give the connection to Hibernate.
*
* @author Derek Hulley
*/
public static class SchemaBootstrapConnectionProvider extends UserSuppliedConnectionProvider
{
private static ThreadLocal threadLocalConnection = new ThreadLocal();
public SchemaBootstrapConnectionProvider()
{
}
/**
* Set the connection for Hibernate to use for schema generation.
*/
public static void setBootstrapConnection(Connection connection)
{
threadLocalConnection.set(connection);
}
/**
* Unsets the connection.
*/
@Override
public void close()
{
// Leave the connection well alone, just remove it
threadLocalConnection.set(null);
}
/**
* Does nothing. The connection was given by a 3rd party and they can close it.
*/
@Override
public void closeConnection(Connection conn)
{
}
/**
* Does nothing.
*/
@Override
public void configure(Properties props) throws HibernateException
{
}
/**
* @see #setBootstrapConnection(Connection)
*/
@Override
public Connection getConnection()
{
return threadLocalConnection.get();
}
@Override
public boolean supportsAggressiveRelease()
{
return false;
}
}
private static final String DIR_SCHEMAS = "schemas";
/**
* Dump a set of creation files for all known Hibernate dialects. These will be
* dumped into the default temporary location in a subdirectory named schemas.
*/
public static void main(String[] args)
{
int exitCode = 0;
try
{
exitCode = dumpDialects(args);
}
catch (Throwable e)
{
logger.error("SchemaBootstrap script dump failed", e);
exitCode = 1;
}
// We can exit
System.exit(exitCode);
}
private static int dumpDialects(String[] dialectClassNames)
{
if (dialectClassNames.length == 0)
{
System.out.println(
"\n" +
" ERROR: A list of fully qualified class names is required");
return 1;
}
ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
SchemaBootstrap schemaBootstrap = (SchemaBootstrap) ctx.getBean("schemaBootstrap");
LocalSessionFactoryBean localSessionFactoryBean = schemaBootstrap.getLocalSessionFactory();
Configuration configuration = localSessionFactoryBean.getConfiguration();
ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
DescriptorService descriptorService = serviceRegistry.getDescriptorService();
Descriptor descriptor = descriptorService.getServerDescriptor();
File tempDir = TempFileProvider.getTempDir();
File schemasDir = new File(tempDir, DIR_SCHEMAS);
if (!schemasDir.exists())
{
schemasDir.mkdir();
}
File dumpDir = new File(schemasDir, descriptor.getVersion());
if (!dumpDir.exists())
{
dumpDir.mkdir();
}
for (String dialectClassName : dialectClassNames)
{
Class dialectClazz = null;
try
{
dialectClazz = Class.forName(dialectClassName);
}
catch (ClassNotFoundException e)
{
System.out.println(
"\n" +
" ERROR: Class not found: " + dialectClassName);
continue;
}
if (!Dialect.class.isAssignableFrom(dialectClazz))
{
System.out.println(
"\n" +
" ERROR: The class name is not a valid dialect: " + dialectClassName);
continue;
}
dumpDialectScript(configuration, dialectClazz, dumpDir);
}
// Done
return 0;
}
private static void dumpDialectScript(Configuration configuration, Class dialectClazz, File directory)
{
// Set the dialect
configuration.setProperty("hibernate.dialect", dialectClazz.getName());
// First dump the dialect's schema
String filename = "default-schema-create-" + dialectClazz.getName() + ".sql";
File dumpFile = new File(directory, filename);
// Write the file
SchemaBootstrap.dumpSchemaCreate(configuration, dumpFile);
}
}