1 2 12 package com.versant.core.jdo.tools.ant; 13 14 import org.apache.tools.ant.BuildException; 15 16 import java.io.*; 17 import java.sql.Connection ; 18 import java.sql.Statement ; 19 import java.sql.SQLException ; 20 import java.util.ArrayList ; 21 import java.util.Iterator ; 22 23 import com.versant.core.common.BindingSupportImpl; 24 import com.versant.core.jdbc.JdbcStorageManagerFactory; 25 26 30 public class ExecuteScriptTask extends JdoTaskBase { 31 32 private String scriptFile; 33 private String sqlCommand = ""; 34 35 39 public void addText(String sql) { 40 this.sqlCommand += sql ; 41 } 42 43 public void setDatastore(String datastore) { 44 } 46 47 public void setScriptFile(String scriptFile) { 48 this.scriptFile = scriptFile; 49 } 50 51 public void execute() throws BuildException { 52 super.execute(); 53 File file = null; 54 55 if (isSqlCommandEmpty() && scriptFile == null) { 56 throw BindingSupportImpl.getInstance().illegalArgument("scriptFile property or sql statement must be set!"); 57 } 58 59 60 if (scriptFile != null){ 61 file = new File(scriptFile); 62 if (!file.exists()){ 63 throw BindingSupportImpl.getInstance().illegalArgument("File "+file.toString() +" does not exist"); 64 } 65 } 66 67 try { 68 if (!isSqlCommandEmpty()) { 69 runScript(sqlCommand); 70 } 71 72 if (file != null){ 73 runScript(getText(file)); 74 } 75 } catch (Exception e) { 76 throw new BuildException(e); 77 } 78 } 79 80 public void runScript(String script) throws Exception { 81 Connection con = null; 82 JdbcStorageManagerFactory smf = (JdbcStorageManagerFactory)getSmf(); 83 try { 84 con = smf.getConnectionSource().getConnection(false, true); 85 SQLScriptParser shredder = new SQLScriptParser(); 86 ArrayList list = shredder.parse(script, true); 87 for (Iterator iter = list.iterator(); iter.hasNext();) { 88 SQLScriptParser.SQLScriptPart scriptPart = (SQLScriptParser.SQLScriptPart) iter.next(); 89 log("Executing: "+scriptPart.getSql()); 90 Statement stat = null; 91 try { 92 stat = con.createStatement(); 93 stat.execute(scriptPart.getSql()); 94 } finally { 95 try { 96 stat.close(); 97 } catch (SQLException e) { 98 } 100 } 101 } 102 } finally { 103 if (con != null) { 104 try { 105 smf.getConnectionSource().returnConnection(con); 106 } catch (SQLException e) { 107 } 109 } 110 } 111 } 112 113 private String getText(File file) throws IOException { 114 int size = (int) file.length(); 115 int chars_read = 0; 116 FileReader in = new FileReader(file); 117 char[] data = new char[size]; 118 while (in.ready()) { 119 chars_read += in.read(data, chars_read, size - chars_read); 120 } 121 in.close(); 122 return new String (data, 0, chars_read); 123 } 124 125 private boolean isSqlCommandEmpty(){ 126 return sqlCommand.trim().equals(""); 127 } 128 } 129 | Popular Tags |