File Source: SQLScriptRunner.java

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   *  contributor license agreements.  The ASF licenses this file to You
     4   * under the Apache License, Version 2.0 (the "License"); you may not
     5   * 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.  For additional information regarding
    15   * copyright in this work, please see the NOTICE file in the top level
    16   * directory of this distribution.
    17   */
    18  
    19  package org.apache.roller.weblogger.business.startup;
    20  
    21  import java.io.BufferedReader;
    22  import java.io.FileInputStream;
    23  import java.io.IOException;
    24  import java.io.InputStream;
    25  import java.io.InputStreamReader;
    26  import java.io.PrintWriter;
    27  import java.io.StringWriter;
    28  import java.sql.Connection;
    29  import java.sql.SQLException;
    30  import java.sql.Statement;
    31  import java.util.ArrayList;
    32  import java.util.List;
    33  import org.apache.commons.logging.Log;
    34  import org.apache.commons.logging.LogFactory;
    35  
    36  
    37  /**
    38   * SQL script runner, parses script and allows you to run it. 
    39   * You can run the script multiple times if necessary.
    40   * Assumes that anything on an input line after "--" or ";" can be ignored.
    41   */
    42  public class SQLScriptRunner {
    43      
             /* 
    P/P       *  Method: org.apache.roller.weblogger.business.startup.SQLScriptRunner__static_init
              * 
              *  Postconditions:
              *    init'ed(log)
              */
    44      private static Log   log = LogFactory.getLog(SQLScriptRunner.class);
    45      
    46      private List<String> commands = new ArrayList<String>();
    47      private List<String> messages = new ArrayList<String>();
    48      private boolean      failed = false;
    49      private boolean      errors = false;
    50          
    51      
    52      /** Creates a new instance of SQLScriptRunner */
             /* 
    P/P       *  Method: void org.apache.roller.weblogger.business.startup.SQLScriptRunner(InputStream)
              * 
              *  Preconditions:
              *    log != null
              * 
              *  Postconditions:
              *    this.commands == &new ArrayList(SQLScriptRunner#1)
              *    this.errors == 0
              *    this.failed == 0
              *    this.messages == &new ArrayList(SQLScriptRunner#2)
              *    new ArrayList(SQLScriptRunner#1) num objects == 1
              *    new ArrayList(SQLScriptRunner#2) num objects == 1
              * 
              *  Test Vectors:
              *    java.io.BufferedReader:readLine(...)@60: Addr_Set{null}, Inverse{null}
              *    java.lang.String:endsWith(...)@73: {0}, {1}
              *    java.lang.String:indexOf(...)@66: {-231..0}, {1..232-1}
              *    java.lang.String:startsWith(...)@64: {1}, {0}
              */
    53      public SQLScriptRunner(InputStream is) throws IOException {
    54          
    55          log.debug("instantiated");
    56          
    57          BufferedReader in = new BufferedReader(new InputStreamReader(is));
    58          String command = ""; 
    59          String line;
    60          while ((line = in.readLine()) != null) {
    61              line = line.trim();
    62              log.debug(line);
    63              
    64              if (!line.startsWith("--")) { // ignore lines starting with "--"    
    65                  
    66                  if (line.indexOf("--") > 0) {
    67                      // trim comment off end of line
    68                      line = line.substring(0, line.indexOf("--")).trim();
    69                  }
    70                  
    71                  // add line to current command
    72                  command += line.trim();
    73                  if (command.endsWith(";")) { 
    74                      // ";" is end of command, so add completed command to list
    75                      commands.add(command.substring(0, command.length() - 1));   
    76                      command = "";
    77                  } else {
    78                      command += " "; // still more command coming so add space
    79                  }
    80              } else {
    81                  successMessage(line);
    82              }
    83          }
    84          in.close();    
    85      }
    86      
    87      
    88      /** Creates a new instance of SQLScriptRunner */
    89      public SQLScriptRunner(String scriptPath) throws IOException {
                 /* 
    P/P           *  Method: void org.apache.roller.weblogger.business.startup.SQLScriptRunner(String)
                  * 
                  *  Preconditions:
                  *    log != null
                  * 
                  *  Postconditions:
                  *    this.commands == &new ArrayList(SQLScriptRunner#1)
                  *    this.errors == 0
                  *    this.failed == 0
                  *    this.messages == &new ArrayList(SQLScriptRunner#2)
                  *    new ArrayList(SQLScriptRunner#1) num objects == 1
                  *    new ArrayList(SQLScriptRunner#2) num objects == 1
                  */
    90          this(new FileInputStream(scriptPath));
    91      }
    92      
    93      
    94      /** Number of SQL commands in script */
    95      public int getCommandCount() {
                 /* 
    P/P           *  Method: int getCommandCount()
                  * 
                  *  Preconditions:
                  *    this.commands != null
                  * 
                  *  Postconditions:
                  *    init'ed(return_value)
                  */
    96          return commands.size();
    97      }
    98      
    99      
   100      /** Return messages from last run of script, empty if no previous run */
   101      public List<String> getMessages() {
                 /* 
    P/P           *  Method: List getMessages()
                  * 
                  *  Preconditions:
                  *    init'ed(this.messages)
                  * 
                  *  Postconditions:
                  *    return_value == this.messages
                  *    init'ed(return_value)
                  */
   102          return messages;
   103      }
   104      
   105      
   106      /** Returns true if last call to runScript() threw an exception */
   107      public boolean getFailed() {
                 /* 
    P/P           *  Method: bool getFailed()
                  * 
                  *  Preconditions:
                  *    init'ed(this.failed)
                  * 
                  *  Postconditions:
                  *    return_value == this.failed
                  *    init'ed(return_value)
                  */
   108          return failed;
   109      }
   110      
   111      
   112      /** Returns true if last run had any errors */
   113      public boolean getErrors() {
                 /* 
    P/P           *  Method: bool getErrors()
                  * 
                  *  Preconditions:
                  *    init'ed(this.errors)
                  * 
                  *  Postconditions:
                  *    return_value == this.errors
                  *    init'ed(return_value)
                  */
   114          return errors;
   115      }
   116      
   117      
   118      /** Run script, logs messages, and optionally throws exception on error */
   119      public void runScript(
   120              Connection con, boolean stopOnError) throws SQLException {
                 /* 
    P/P           *  Method: void runScript(Connection, bool)
                  * 
                  *  Preconditions:
                  *    this.commands != null
                  *    (soft) con != null
                  *    (soft) stopOnError == 0
                  *    (soft) this.messages != null
                  * 
                  *  Presumptions:
                  *    java.sql.Connection:createStatement(...)@127 != null
                  * 
                  *  Postconditions:
                  *    this.errors == 0
                  *    this.failed == 0
                  * 
                  *  Test Vectors:
                  *    java.sql.Connection:getAutoCommit(...)@129: {1}, {0}
                  *    java.util.Iterator:hasNext(...)@123: {0}, {1}
                  */
   121          failed = false;
   122          errors = false;
   123          for (String command : commands) {
   124              
   125              // run each command
   126              try {
   127                  Statement stmt = con.createStatement();
   128                  stmt.executeUpdate(command);
   129                  if (!con.getAutoCommit()) con.commit();
   130                  
   131                  // on success, echo command to messages
   132                  successMessage(command);
   133                  
   134              } catch (SQLException ex) {
   135                  // add error message with text of SQL command to messages
   136                  errorMessage("ERROR: SQLException executing SQL [" + command 
   137                          + "] : " + ex.getLocalizedMessage());
   138                  // add stack trace to messages
   139                  StringWriter sw = new StringWriter();
   140                  ex.printStackTrace(new PrintWriter(sw));
   141                  errorMessage(sw.toString());
   142                  if (stopOnError) {
   143                      failed = true;
   144                      throw ex;
   145                  }
   146              }
   147          }
   148      }
   149      
   150      
   151      private void errorMessage(String msg) {
                 /* 
    P/P           *  Method: void errorMessage(String)
                  * 
                  *  Preconditions:
                  *    this.messages != null
                  */
   152          messages.add(msg);
   153      }    
   154      
   155      
   156      private void successMessage(String msg) {
                 /* 
    P/P           *  Method: void successMessage(String)
                  * 
                  *  Preconditions:
                  *    this.messages != null
                  */
   157          messages.add(msg);
   158      }
   159      
   160  }








SofCheck Inspector Build Version : 2.18479
SQLScriptRunner.java 2009-Jan-02 14:25:18
SQLScriptRunner.class 2009-Sep-04 03:12:31