polishing

This commit is contained in:
Juergen Hoeller 2009-12-15 21:37:59 +00:00
parent fd1bfeefe4
commit f208988563
3 changed files with 66 additions and 53 deletions

View File

@ -19,6 +19,8 @@ package org.springframework.jdbc.config;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.w3c.dom.Element;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
@ -28,7 +30,6 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils; import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/** /**
* {@link org.springframework.beans.factory.xml.BeanDefinitionParser} that parses {@code embedded-database} element and * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} that parses {@code embedded-database} element and
@ -36,6 +37,7 @@ import org.w3c.dom.Element;
* configures a {@link ResourceDatabasePopulator} for them. * configures a {@link ResourceDatabasePopulator} for them.
* *
* @author Oliver Gierke * @author Oliver Gierke
* @since 3.0
*/ */
public class EmbeddedDatabaseBeanDefinitionParser extends AbstractBeanDefinitionParser { public class EmbeddedDatabaseBeanDefinitionParser extends AbstractBeanDefinitionParser {
@ -62,15 +64,11 @@ public class EmbeddedDatabaseBeanDefinitionParser extends AbstractBeanDefinition
} }
private BeanDefinition createDatabasePopulator(List<Element> scripts, ParserContext context) { private BeanDefinition createDatabasePopulator(List<Element> scripts, ParserContext context) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ResourceDatabasePopulator.class);
List<String> locations = new ArrayList<String>(); List<String> locations = new ArrayList<String>();
for (Element scriptElement : scripts) { for (Element scriptElement : scripts) {
String location = scriptElement.getAttribute("location"); locations.add(scriptElement.getAttribute("location"));
locations.add(location);
} }
// Use a factory bean for the resources so they can be given an order if a pattern is used // Use a factory bean for the resources so they can be given an order if a pattern is used
BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder BeanDefinitionBuilder resourcesFactory = BeanDefinitionBuilder
.genericBeanDefinition(SortedResourcesFactoryBean.class); .genericBeanDefinition(SortedResourcesFactoryBean.class);
@ -79,11 +77,11 @@ public class EmbeddedDatabaseBeanDefinitionParser extends AbstractBeanDefinition
builder.addPropertyValue("scripts", resourcesFactory.getBeanDefinition()); builder.addPropertyValue("scripts", resourcesFactory.getBeanDefinition());
return builder.getBeanDefinition(); return builder.getBeanDefinition();
} }
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, private AbstractBeanDefinition getSourcedBeanDefinition(
ParserContext context) { BeanDefinitionBuilder builder, Element source, ParserContext context) {
AbstractBeanDefinition definition = builder.getBeanDefinition(); AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(context.extractSource(source)); definition.setSource(context.extractSource(source));
return definition; return definition;

View File

@ -1,6 +1,19 @@
/** /*
* * Copyright 2002-2009 the original author or authors.
*
* Licensed 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.springframework.jdbc.config; package org.springframework.jdbc.config;
import java.io.IOException; import java.io.IOException;
@ -10,42 +23,32 @@ import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver;
/**
* @author Dave Syer
* @author Juergen Hoeller
* @since 3.0
*/
public class SortedResourcesFactoryBean implements FactoryBean<Resource[]> { public class SortedResourcesFactoryBean implements FactoryBean<Resource[]> {
private static final Log logger = LogFactory.getLog(SortedResourcesFactoryBean.class); private final Resource[] resources;
private ResourceLoader resourceLoader;
private List<String> locations;
public SortedResourcesFactoryBean(ResourceLoader resourceLoader, List<String> locations) { public SortedResourcesFactoryBean(ResourceLoader resourceLoader, List<String> locations) throws IOException {
super();
this.resourceLoader = resourceLoader;
this.locations = locations;
}
public Resource[] getObject() throws Exception {
List<Resource> scripts = new ArrayList<Resource>(); List<Resource> scripts = new ArrayList<Resource>();
for (String location : locations) { for (String location : locations) {
if (logger.isDebugEnabled()) {
logger.debug("Adding resources from pattern: "+location);
}
if (resourceLoader instanceof ResourcePatternResolver) { if (resourceLoader instanceof ResourcePatternResolver) {
List<Resource> resources = new ArrayList<Resource>(Arrays List<Resource> resources = new ArrayList<Resource>(
.asList(((ResourcePatternResolver) resourceLoader).getResources(location))); Arrays.asList(((ResourcePatternResolver) resourceLoader).getResources(location)));
Collections.<Resource> sort(resources, new Comparator<Resource>() { Collections.sort(resources, new Comparator<Resource>() {
public int compare(Resource o1, Resource o2) { public int compare(Resource o1, Resource o2) {
try { try {
return o1.getURL().toString().compareTo(o2.getURL().toString()); return o1.getURL().toString().compareTo(o2.getURL().toString());
} catch (IOException e) { }
catch (IOException ex) {
return 0; return 0;
} }
} }
@ -53,23 +56,24 @@ public class SortedResourcesFactoryBean implements FactoryBean<Resource[]> {
for (Resource resource : resources) { for (Resource resource : resources) {
scripts.add(resource); scripts.add(resource);
} }
}
} else { else {
scripts.add(resourceLoader.getResource(location)); scripts.add(resourceLoader.getResource(location));
} }
} }
return scripts.toArray(new Resource[scripts.size()]); this.resources = scripts.toArray(new Resource[scripts.size()]);
}
public Resource[] getObject() {
return this.resources;
} }
public Class<? extends Resource[]> getObjectType() { public Class<? extends Resource[]> getObjectType() {
// TODO Auto-generated method stub return Resource[].class;
return null;
} }
public boolean isSingleton() { public boolean isSingleton() {
// TODO Auto-generated method stub return true;
return false;
} }
} }

View File

@ -28,6 +28,7 @@ import java.util.List;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -44,8 +45,11 @@ import org.springframework.util.StringUtils;
*/ */
public class ResourceDatabasePopulator implements DatabasePopulator { public class ResourceDatabasePopulator implements DatabasePopulator {
private static String COMMENT_PREFIX = "--";
private static final Log logger = LogFactory.getLog(ResourceDatabasePopulator.class); private static final Log logger = LogFactory.getLog(ResourceDatabasePopulator.class);
private List<Resource> scripts = new ArrayList<Resource>(); private List<Resource> scripts = new ArrayList<Resource>();
private String sqlScriptEncoding; private String sqlScriptEncoding;
@ -54,14 +58,13 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
private boolean ignoreFailedDrops = false; private boolean ignoreFailedDrops = false;
private static String COMMENT_PREFIX = "--";
/** /**
* Add a script to execute to populate the database. * Add a script to execute to populate the database.
* @param script the path to a SQL script * @param script the path to a SQL script
*/ */
public void addScript(Resource script) { public void addScript(Resource script) {
scripts.add(script); this.scripts.add(script);
} }
/** /**
@ -100,7 +103,8 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
public void setIgnoreFailedDrops(boolean ignoreFailedDrops) { public void setIgnoreFailedDrops(boolean ignoreFailedDrops) {
this.ignoreFailedDrops = ignoreFailedDrops; this.ignoreFailedDrops = ignoreFailedDrops;
} }
public void populate(Connection connection) throws SQLException { public void populate(Connection connection) throws SQLException {
for (Resource script : this.scripts) { for (Resource script : this.scripts) {
executeSqlScript(connection, applyEncodingIfNecessary(script), this.continueOnError, this.ignoreFailedDrops); executeSqlScript(connection, applyEncodingIfNecessary(script), this.continueOnError, this.ignoreFailedDrops);
@ -110,7 +114,8 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
private EncodedResource applyEncodingIfNecessary(Resource script) { private EncodedResource applyEncodingIfNecessary(Resource script) {
if (script instanceof EncodedResource) { if (script instanceof EncodedResource) {
return (EncodedResource) script; return (EncodedResource) script;
} else { }
else {
return new EncodedResource(script, this.sqlScriptEncoding); return new EncodedResource(script, this.sqlScriptEncoding);
} }
} }
@ -134,8 +139,9 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
String script; String script;
try { try {
script = readScript(resource); script = readScript(resource);
} catch (IOException e) { }
throw new CannotReadScriptException(resource, e); catch (IOException ex) {
throw new CannotReadScriptException(resource, ex);
} }
char delimiter = ';'; char delimiter = ';';
if (!containsSqlScriptDelimiters(script, delimiter)) { if (!containsSqlScriptDelimiters(script, delimiter)) {
@ -152,21 +158,25 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " rows affected by SQL: " + statement); logger.debug(rowsAffected + " rows affected by SQL: " + statement);
} }
} catch (SQLException ex) { }
catch (SQLException ex) {
boolean dropStatement = statement.trim().toLowerCase().startsWith("drop"); boolean dropStatement = statement.trim().toLowerCase().startsWith("drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) { if (continueOnError || (dropStatement && ignoreFailedDrops)) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Line " + lineNumber + " statement failed: " + statement, ex); logger.debug("Line " + lineNumber + " statement failed: " + statement, ex);
} }
} else { }
else {
throw ex; throw ex;
} }
} }
} }
} finally { }
finally {
try { try {
stmt.close(); stmt.close();
} catch (Throwable ex) { }
catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex); logger.debug("Could not close JDBC Statement", ex);
} }
} }
@ -237,7 +247,8 @@ public class ResourceDatabasePopulator implements DatabasePopulator {
statements.add(sb.toString()); statements.add(sb.toString());
sb = new StringBuilder(); sb = new StringBuilder();
} }
} else { }
else {
sb.append(content[i]); sb.append(content[i]);
} }
} }