View Javadoc

1   /*
2    * Copyright 2002-2006 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springbyexample.jdbc.core;
18  
19  import java.io.BufferedReader;
20  import java.io.IOException;
21  import java.io.InputStreamReader;
22  import java.util.List;
23  
24  import javax.sql.DataSource;
25  
26  import org.slf4j.Logger;
27  import org.slf4j.LoggerFactory;
28  import org.springframework.beans.factory.InitializingBean;
29  import org.springframework.context.ResourceLoaderAware;
30  import org.springframework.core.io.Resource;
31  import org.springframework.core.io.ResourceLoader;
32  import org.springframework.jdbc.core.JdbcTemplate;
33  import org.springframework.util.StringUtils;
34  
35  /**
36   * Processes sql scripts.  A list of scripts 
37   * or script locations can be set.  Spring <code>ResourceLoader</code> 
38   * is used so valid scripts locations are classpath, file, http, ftp. etc.
39   * 
40   * @author David Winterfeldt
41   */
42  public class SqlScriptProcessor implements InitializingBean, ResourceLoaderAware {
43  
44      final Logger logger = LoggerFactory.getLogger(SqlScriptProcessor.class);
45  
46      protected JdbcTemplate template = null;
47      protected ResourceLoader resourceLoader = null;
48      
49      protected boolean initOnStartup = false;
50      protected List<String> lSqlScripts = null;
51      protected String charset = null;
52  
53      /**
54       * Sets <code>DataSource</code>.
55       */
56      public void setDataSource(DataSource dataSource) {
57          template = new JdbcTemplate(dataSource);
58      }
59      
60      /**
61       * Whether or not SQL scripts on startup.
62       * Default is <code>false</code>.
63       */
64      public boolean isInitOnStartup() {
65          return initOnStartup;
66      }
67  
68      /**
69       * Sets whether or not SQL scripts run on statup.
70       * Default is <code>false</code>.
71       */
72      public void setInitOnStartup(boolean initOnStartup) {
73          this.initOnStartup = initOnStartup;
74      }
75  
76      /**
77       * Gets SQL scripts.
78       */
79      public List<String> getSqlScripts() {
80          return lSqlScripts;
81      }
82  
83      /**
84       * Sets SQL scripts.
85       */
86      public void setSqlScripts(List<String> lSqlScripts) {
87          this.lSqlScripts = lSqlScripts;
88      }
89  
90      /**
91       * Gets charset used to process a sql script file (ex: 'UTF-8').
92       * If not set, default character set of the JVM is used.
93       */
94      public String getCharset() {
95          return charset;
96      }
97  
98      /**
99       * Sets charset used to process a sql script file (ex: 'UTF-8').  
100      * If not set, default character set of the JVM is used.
101      */
102     public void setCharset(String charset) {
103         this.charset = charset;
104     }
105 
106     /**
107      * Implementation of <code>IntializingBean</code>.
108      */
109     public void afterPropertiesSet() throws Exception {
110         if (initOnStartup) {
111             process();
112         }
113     }
114 
115     /**
116      * Implementation of <code>ResourceLoaderAware</code>.
117      */
118     public void setResourceLoader(ResourceLoader resourceLoader) {
119         this.resourceLoader = resourceLoader;
120     }
121     
122     /**
123      * Initializes SQL scripts.
124      */
125     public void process() throws IOException {
126         if (lSqlScripts != null) {
127             for (String sqlScript : lSqlScripts) {
128                 String sql =  null;
129                 
130                 Resource resource = resourceLoader.getResource(sqlScript);
131                 
132                 if (!resource.exists()) {
133                     sql = sqlScript;
134                 } else {
135                     BufferedReader br = null;
136 
137                     try {
138                         if (charset == null) {
139                             br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
140                         } else {
141                             br = new BufferedReader(new InputStreamReader(resource.getInputStream(), charset));
142                         }
143                         
144                         StringBuilder sb = new StringBuilder();
145                         String line = null;
146     
147                         while ((line = br.readLine()) != null) {
148                             sb.append(line);
149                             sb.append("\n");
150                         }
151                         
152                         sql = sb.toString();
153                     } finally {
154                         try { br.close(); } catch (Exception e) {}
155                     }
156                 }
157                 
158                 if (StringUtils.hasLength(sql)) {
159                     logger.debug("Initializing db with '" + sql +"'.");
160                     
161                     // execute sql
162                     template.execute(sql);
163                 }
164             }
165         }
166     }
167 
168 }