Ejemplo n.º 1
0
 /**
  * Parse some input string and translate all special tokens. This is similar to a string template
  * engine: it extracts <em>key</em> from <tt>${key}</tt> sequences in the input string and uses
  * {@link #getString(String)} to translate it. Contents in between <tt>${}</tt> sequences are
  * copied as-is.
  *
  * @param input The input string.
  * @return String with all special tokens replaced.
  */
 public static String processTemplate(String input) {
   if (input == null || input.trim().length() == 0) return input;
   StringBuilder sb = new StringBuilder();
   int last = 0;
   for (int i = 0; i < input.length(); i++) {
     if (i <= input.length() - 3 && input.charAt(i) == '$' && input.charAt(i + 1) == '{') {
       int j;
       for (j = i + 2; j < input.length() && input.charAt(j) != '}'; j++) ;
       if (i > 0) sb.append(input.substring(last, i));
       String key = input.substring(i + 2, j);
       String text = null;
       try {
         text = getString(key);
       } catch (Exception e) {
       }
       if (text == null || text.contains(key)) {
         logger.error("Failed to lookup key [" + key + "]");
         sb.append("${" + key + "}");
       } else sb.append(text);
       last = j + 1;
     }
   }
   sb.append(input.substring(last));
   logger.debug("Template string [" + input + "] turns out as [" + sb + "]");
   return sb.toString();
 }
 /**
  * @see
  *     net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.IDataTypeComponent#getDefaultValue(java.lang.String)
  */
 public Object getDefaultValue(String dbDefaultValue) {
   // At the moment, no default value
   if (s_log.isInfoEnabled()) {
     s_log.info("getDefaultValue: not yet implemented");
   }
   return null;
 }
Ejemplo n.º 3
0
 /** Application is shutting down so save preferences. */
 public void unload() {
   try {
     savePrefs(fileWrapperFactory.create(_userSettingsFolder, USER_PREFS_FILE_NAME));
   } catch (IOException ex) {
     s_log.error("Error occured writing to preferences file: " + USER_PREFS_FILE_NAME, ex);
   } catch (XMLException ex) {
     s_log.error("Error occured writing to preferences file: " + USER_PREFS_FILE_NAME, ex);
   }
   super.unload();
 }
Ejemplo n.º 4
0
  private void createEmptyRequiredUserFiles() {
    _userExtraLAFFolder.mkdirs();

    FileWrapper file =
        fileWrapperFactory.create(_userExtraLAFFolder, ILAFConstants.USER_EXTRA_LAFS_PROPS_FILE);
    try {
      boolean result = file.createNewFile();
      if (!result) {
        s_log.warn("Failed to create empty required user files");
      }
    } catch (IOException ex) {
      s_log.error("Error creating file " + file.getAbsolutePath(), ex);
    }
  }
Ejemplo n.º 5
0
  private void secureAddTab(ExplainTab tab) {
    SessionProperties props = _session.getProperties();

    if (s_log.isDebugEnabled()) {
      s_log.debug("secureAddTab - TabCount: " + _tabbedExecutionsPanel.getTabCount());
      s_log.debug("secureAddTab - Limited?: " + props.getLimitSQLResultTabs());
      s_log.debug("secureAddTab - TabLimit: " + props.getSqlResultTabLimit());
    }

    if (props.getLimitSQLResultTabs()
        && props.getSqlResultTabLimit() <= _tabbedExecutionsPanel.getTabCount()) {
      closeTabAt(0);
    }
    _tabbedExecutionsPanel.addTab(tab.getTitle(), null, tab, tab.getToolTip());
    _tabbedExecutionsPanel.setSelectedComponent(tab);
  }
  public void executeSQL(String sql) {
    if (sql != null && sql.trim().length() > 0) {
      removeErrorPanels();

      String origSQL = sql;
      sql = fireSQLToBeExecutedEvent(sql);

      // This can happen if an impl of ISQLExecutionListener returns null
      // from the statementExecuting API method, to indicate that the SQL
      // shouldn't be executed.
      if (sql == null) {
        s_log.info(
            "executeSQL: An ISQLExecutionListener veto'd execution of "
                + "the following SQL: "
                + origSQL);
        return;
      }

      ISQLExecutionListener[] executionListeners =
          _listeners.getListeners(ISQLExecutionListener.class);

      ISQLExecutionHandlerListener executionHandlerListener = createSQLExecutionHandlerListener();

      new SQLExecutionHandler(
          (IResultTab) null, _session, sql, executionHandlerListener, executionListeners);
    }
  }
Ejemplo n.º 7
0
 /**
  * Load preferences from the new file format.
  *
  * @param newPerfsFile FileWrapper containing the preferences information.
  * @throws XMLException Thrown if error reading preferences file.
  */
 private void loadNewPrefs(FileWrapper newPrefsFile) throws XMLException {
   try {
     try {
       _settingsCache.load(newPrefsFile.getPath(), getClass().getClassLoader());
     } catch (DuplicateObjectException ex) {
       s_log.error("Cache should have been empty", ex);
     }
     Iterator<LAFPreferences> it = _settingsCache.getAllForClass(LAFPreferences.class);
     if (it.hasNext()) {
       _lafPrefs = it.next();
     } else {
       s_log.error("LAFPreferences object not loaded");
     }
   } catch (FileNotFoundException ignore) {
     // property file not found for user - first time user ran pgm.
   }
 }
Ejemplo n.º 8
0
 private String getExplainSql(String sql) {
   StringBuilder result = new StringBuilder();
   IQueryTokenizer tokenizer = _session.getQueryTokenizer();
   tokenizer.setScriptToTokenize(sql);
   while (tokenizer.hasQuery()) {
     String query = tokenizer.nextQuery();
     result.append("BEGIN").append(tokenizer.getSQLStatementSeparator());
     result.append(EXPLAIN_PREFIX).append(query).append(tokenizer.getSQLStatementSeparator());
     result.append("ROLLBACK").append(tokenizer.getSQLStatementSeparator());
   }
   if (s_log.isDebugEnabled()) {
     s_log.debug("getExplainSql - Input: " + sql);
     s_log.debug("getExplainSql - Querys: " + tokenizer.getQueryCount());
     s_log.debug("getExplainSql - Result: " + result);
   }
   return result.toString();
 }
 private void closeResultTab(ResultTab tab) {
   if (tab == null) {
     throw new IllegalArgumentException("Null ResultTab passed");
   }
   s_log.debug("SQLPanel.closeResultTab(" + tab.getIdentifier().toString() + ")");
   tab.closeTab();
   _tabbedExecutionsPanel.remove(tab);
 }
 private void deleteTempFiles(List<File> files) {
   for (int i = 0, limit = files.size(); i < limit; ++i) {
     if (!(files.get(i)).delete()) {
       // i18n[DumpApplicationCommand.error.deletetempfile=Couldn't delete temporary DumpSession
       // file]
       s_log.error(s_stringMgr.getString("DumpApplicationCommand.error.deletetempfile"));
     }
   }
 }
  /**
   * Link from fw to check on whether there are any unusual conditions in the current data that the
   * user needs to be aware of before updating.
   */
  public String getWarningOnCurrentData(
      Object[] values, ColumnDisplayDefinition[] colDefs, int col, Object oldValue) {

    // if we could not identify which table to edit, tell user
    if (ti == null) return TI_ERROR_MESSAGE;

    List<IWhereClausePart> whereClauseParts = getWhereClause(values, colDefs, col, oldValue);

    // It is possible for a table to contain only columns of types that
    // we cannot process or do selects on, so check for that.
    // Since this check is on the structure of the table rather than the contents,
    // we only need to do it once (ie: it is not needed in getWarningOnProjectedUpdate)
    if (whereClausePartUtil.hasUsableWhereClause(whereClauseParts) == false) {
      // i18n[DataSetUpdateableTableModelImpl.confirmupdateallrows=The table has no columns that can
      // be SELECTed on.\nAll rows will be updated.\nDo you wish to proceed?]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.confirmupdateallrows");
    }

    final ISession session = _session;
    final ISQLConnection conn = session.getSQLConnection();

    int count = -1; // start with illegal number of rows matching query

    try {
      count = count(whereClauseParts, conn);
    } catch (SQLException ex) {
      // i18n[DataSetUpdateableTableModelImpl.error.exceptionduringcheck=Exception
      // seen during check on DB.  Exception was:\n{0}\nUpdate is probably not
      // safe to do.\nDo you wish to proceed?]
      String msg =
          s_stringMgr.getString(
              "DataSetUpdateableTableModelImpl.error.exceptionduringcheck", ex.getMessage());
      s_log.error(msg, ex);
      return msg;
    }

    if (count == -1) {
      // i18n[DataSetUpdateableTableModelImpl.error.unknownerror=Unknown error during check on DB.
      // Update is probably not safe.\nDo you wish to proceed?]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.error.unknownerror");
    }
    if (count == 0) {
      // i18n[DataSetUpdateableTableModelImpl.error.staleupdaterow=This row in the Database has been
      // changed since you refreshed the data.\nNo rows will be updated by this operation.\nDo you
      // wish to proceed?]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.error.staleupdaterow");
    }
    if (count > 1) {
      // i18n[DataSetUpdateableTableModelImpl.info.updateidenticalrows=This operation will update
      // {0} identical rows.\nDo you wish to proceed?]
      return s_stringMgr.getString(
          "DataSetUpdateableTableModelImpl.info.updateidenticalrows", Long.valueOf(count));
    }
    // no problems found, so do not return a warning message.
    return null; // nothing for user to worry about
  }
Ejemplo n.º 12
0
 /** Save preferences to disk. */
 private void savePrefs() {
   try {
     final XMLBeanWriter wtr = new XMLBeanWriter(_newSessionPrefs);
     wtr.save(fileWrapperFactory.create(_userSettingsFolder, IConstants.USER_PREFS_FILE_NAME));
   } catch (Exception ex) {
     final String msg =
         "Error occured writing to preferences file: " + IConstants.USER_PREFS_FILE_NAME;
     s_log.error(msg, ex);
   }
 }
 /** Save preferences to disk. */
 public void savePrefs() {
   if (!_initialized) {
     throw new IllegalStateException("initialize() must be called first");
   }
   try {
     XMLBeanWriter wtr = new XMLBeanWriter(_prefs);
     wtr.save(fileWrapperFactory.create(_userSettingsFolder, USER_PREFS_FILE_NAME));
   } catch (Exception ex) {
     s_log.error("Error occurred writing to preferences file: " + USER_PREFS_FILE_NAME, ex);
   }
 }
 /** Get the full name of this table, creating that name the first time we are called */
 public String getFullTableName() {
   if (fullTableName == null) {
     try {
       final String name = ti.getQualifiedName();
       fullTableName = getUnambiguousTableName(_session, name);
     } catch (Exception e) {
       s_log.error("getFullTableName: Unexpected exception - " + e.getMessage(), e);
     }
   }
   return fullTableName;
 }
 /**
  * @see
  *     net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.IDataTypeComponent#setPreparedStatementValue(java.sql.PreparedStatement,
  *     java.lang.Object, int)
  */
 public void setPreparedStatementValue(PreparedStatement pstmt, Object value, int position)
     throws SQLException {
   if (value == null || "".equals(value)) {
     pstmt.setNull(position, java.sql.Types.OTHER, "xml");
   } else {
     try {
       pstmt.setString(position, value.toString());
     } catch (Exception e) {
       s_log.error("setPreparedStatementValue: Unexpected exception - " + e.getMessage(), e);
     }
   }
 }
Ejemplo n.º 16
0
 public void moveToFront(final JInternalFrame fr) {
   if (fr != null) {
     GUIUtils.processOnSwingEventThread(
         new Runnable() {
           public void run() {
             GUIUtils.moveToFront(fr);
           }
         });
   } else {
     s_log.debug("JInternalFrame == null");
   }
 }
Ejemplo n.º 17
0
  /** Load from preferences file. */
  private void loadPrefs() {
    final FileWrapper oldPrefsFile =
        fileWrapperFactory.create(_userSettingsFolder, OLD_USER_PREFS_FILE_NAME);
    final FileWrapper newPrefsFile =
        fileWrapperFactory.create(_userSettingsFolder, USER_PREFS_FILE_NAME);
    final boolean oldExists = oldPrefsFile.exists();
    final boolean newExists = newPrefsFile.exists();

    try {
      if (oldExists) {
        loadOldPrefs(oldPrefsFile);
        try {
          _settingsCache.add(_lafPrefs);
        } catch (DuplicateObjectException ex) {
          s_log.error("LAFPreferences object already in cache", ex);
        }
        savePrefs(newPrefsFile);
        if (!oldPrefsFile.delete()) {
          s_log.error("Unable to delete old LAF preferences file");
        }

      } else if (newExists) {
        loadNewPrefs(newPrefsFile);
      }
    } catch (IOException ex) {
      s_log.error("Error occured in preferences file", ex);
    } catch (XMLException ex) {
      s_log.error("Error occured in preferences file", ex);
    }

    if (_lafPrefs == null) {
      _lafPrefs = new LAFPreferences(IdentifierFactory.getInstance().createIdentifier());
      _lafPrefs.setLookAndFeelClassName(MetalLookAndFeelController.METAL_LAF_CLASS_NAME);
      try {
        _settingsCache.add(_lafPrefs);
      } catch (DuplicateObjectException ex) {
        s_log.error("LAFPreferences object already in cache", ex);
      }
    }
  }
Ejemplo n.º 18
0
 public void actionPerformed(ActionEvent evt) {
   if (_session != null) {
     try {
       // new InQuotesCommand(_session.getSQLPanelAPI(_plugin)).execute();
       new InQuotesCommand(FrameWorkAcessor.getSQLPanelAPI(_session, _plugin)).execute();
     } catch (Throwable ex) {
       // i18n[editextras.errorQuoteSql=Error processing Quote SQL command: {0}]
       final String msg = s_stringMgr.getString("editextras.errorQuoteSql", ex);
       _session.showErrorMessage(msg);
       s_log.error(msg, ex);
     }
   }
 }
  /** Load from preferences file. */
  private void loadPrefs() {
    try {
      XMLBeanReader doc = new XMLBeanReader();

      FileWrapper prefFile = PreferenceUtil.getPreferenceFileToReadFrom(plugin);

      doc.load(prefFile, _prefs.getClass().getClassLoader());

      Iterator<Object> it = doc.iterator();

      if (it.hasNext()) {
        _prefs = (IQueryTokenizerPreferenceBean) it.next();
      }
    } catch (FileNotFoundException ignore) {
      s_log.info(USER_PREFS_FILE_NAME + " not found - will be created");
    } catch (Exception ex) {
      s_log.error("Error occurred reading from preferences file: " + USER_PREFS_FILE_NAME, ex);
    }

    _prefs.setClientName(Version.getApplicationName() + "/" + plugin.getDescriptiveName());
    _prefs.setClientVersion(Version.getShortVersion() + "/" + plugin.getVersion());
  }
 /**
  * This class relies on reflection to get a handle to Oracle's XMLType which is made available
  * separately from the JDBC driver, so we cannot just assume the user will always have, nor can we
  * depend on it to compile SQuirreL code. So we remove this dependency here by using reflection
  * which doesn't require this library in order to just compile the code.
  *
  * @see
  *     net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.IDataTypeComponent#readResultSet(java.sql.ResultSet,
  *     int, boolean)
  */
 public Object readResultSet(ResultSet rs, int idx, boolean limitDataRead) throws SQLException {
   Object result = null;
   try {
     result = rs.getString(idx);
     if (result == null || "".equals(result)) {
       return NULL_VALUE_PATTERN;
     }
   } catch (Exception e) {
     s_log.error("Unexpected exception while attempting to read PostgreSQL XML column", e);
   }
   if (result == null) {
     result = i18n.CELL_ERROR_MSG;
   }
   return result;
 }
  /**
   * Return the passed tab back into the tabbed pane.
   *
   * @param tab <TT>Resulttab</TT> to be returned
   * @throws IllegalArgumentException Thrown if a <TT>null</TT> <TT>ResultTab</TT> passed.
   */
  private void returnToTabbedPane(ResultTab tab) {
    if (tab == null) {
      throw new IllegalArgumentException("Null ResultTab passed");
    }

    s_log.debug("SQLPanel.returnToTabbedPane(" + tab.getIdentifier().toString() + ")");

    for (ResultFrame sqlResultFrame : _sqlResultFrames) {
      if (tab == sqlResultFrame.getTab()) {
        _sqlResultFrames.remove(sqlResultFrame);
        break;
      }
    }

    addResultsTab(tab, null);
  }
Ejemplo n.º 22
0
  /** Render a value into text for this DataType. */
  public String renderObject(Object value) {
    // use the Java default date-to-string
    if (useJavaDefaultFormat == true || value == null)
      return (String) _renderer.renderObject(value);

    // use a date formatter
    try {
      return (String) _renderer.renderObject(dateFormat.format(value));
    } catch (Exception e) {
      if (false == _renderExceptionHasBeenLogged) {
        _renderExceptionHasBeenLogged = true;
        s_log.error("Could not format \"" + value + "\" as date type", e);
      }
      return (String) _renderer.renderObject(value);
    }
  }
Ejemplo n.º 23
0
 public void execute() {
   ValidateSQLCommand cmd =
       new ValidateSQLCommand(
           _valProps._prefs,
           _valProps._sessionProps,
           _valProps._sql,
           _valProps._stmtSepChar,
           _valProps._solComment);
   try {
     cmd.execute();
     _valProps._msgHandler.showMessage(cmd.getResults());
   } catch (Throwable th) {
     final String msg = "Error occured when talking to the web service";
     s_log.error(msg, th);
     _app.showErrorDialog(msg, th);
   }
 }
  /**
   * Create an internal frame for the specified tab and display the tab in the internal frame after
   * removing it from the tabbed pane.
   *
   * @param tab <TT>ResultTab</TT> to be displayed in an internal frame.
   * @throws IllegalArgumentException Thrown if a <TT>null</TT> <TT>ResultTab</TT> passed.
   */
  private void createSQLResultFrame(ResultTab tab) {
    if (tab == null) {
      throw new IllegalArgumentException("Null ResultTab passed");
    }
    s_log.debug("SQLPanel.createSQLResultFrame(" + tab.getIdentifier().toString() + ")");
    _tabbedExecutionsPanel.remove(tab);

    ResultFrameListener resultFrameListener =
        new ResultFrameListener() {
          @Override
          public void frameReplaced(ResultFrame oldFrame, ResultFrame newFrame) {
            onFrameReplaced(oldFrame, newFrame);
          }
        };

    ResultFrame frame =
        new ResultFrame(_session, tab, _resultTabFactory, resultFrameListener, true, false);
    _sqlResultFrames.add(frame);
  }
Ejemplo n.º 25
0
 /**
  * Retrieve an icon from the passed action for the specified key.
  *
  * @param action Action to retrieve icon from.
  * @param key Key that specified the icon.
  * @return The requested Icon or null.
  */
 protected Icon getIconFromAction(Action action, String key) {
   // Object obj = action.getValue(BaseAction.IBaseActionPropertyNames.ROLLOVER_ICON);
   Object obj = action.getValue(key);
   if (obj != null) {
     if (obj instanceof Icon) {
       return (Icon) obj;
     }
     StringBuffer msg = new StringBuffer();
     msg.append("Non icon object of type ")
         .append(obj.getClass().getName())
         .append(" was stored in an Action of type ")
         .append(action.getClass().getName())
         .append(" using the key ")
         .append(key)
         .append(".");
     s_log.error(msg.toString());
   }
   return null;
 }
 private void combineTempFiles(List<String> titles, List<File> files) {
   try {
     PrintWriter wtr = new PrintWriter(new FileWriter(_outFile));
     try {
       // i18n[DumpApplicationCommand.header=SQuirreL SQL Client Application Dump {0}]
       String header =
           s_stringMgr.getString(
               "DumpApplicationCommand.header", Calendar.getInstance().getTime());
       wtr.println(header);
       for (int i = 0, limit = files.size(); i < limit; ++i) {
         wtr.println();
         wtr.println();
         wtr.println(SEP);
         wtr.println(titles.get(i));
         wtr.println(SEP);
         BufferedReader rdr = new BufferedReader(new FileReader(files.get(i)));
         try {
           String line = null;
           while ((line = rdr.readLine()) != null) {
             wtr.println(line);
           }
         } finally {
           rdr.close();
         }
       }
     } finally {
       wtr.close();
     }
   } catch (IOException ex) {
     // i18n[DumpApplicationCommand.error.combiningtempfiles=Error combining temp files into dump
     // file]
     final String msg = s_stringMgr.getString("DumpApplicationCommand.error.combiningtempfiles");
     _msgHandler.showMessage(msg);
     _msgHandler.showMessage(ex.toString());
     s_log.error(msg, ex);
   }
 }
Ejemplo n.º 27
0
  /** Load from preferences file. */
  private void loadPrefs() {
    try {
      final XMLBeanReader doc = new XMLBeanReader();
      final FileWrapper file =
          fileWrapperFactory.create(_userSettingsFolder, IConstants.USER_PREFS_FILE_NAME);
      doc.load(file, getClass().getClassLoader());

      Iterator<?> it = doc.iterator();

      if (it.hasNext()) {
        _newSessionPrefs = (SyntaxPreferences) it.next();
      }
    } catch (FileNotFoundException ignore) {
      // property file not found for user - first time user ran pgm.
    } catch (Exception ex) {
      final String msg =
          "Error occured reading from preferences file: " + IConstants.USER_PREFS_FILE_NAME;
      s_log.error(msg, ex);
    }

    if (_newSessionPrefs == null) {
      _newSessionPrefs = new SyntaxPreferences();
    }
  }
  /** Insert a row into the DB. If the insert succeeds this returns a null string. */
  public String insertRow(Object[] values, ColumnDisplayDefinition[] colDefs) {

    // if we could not identify which table to edit, tell user
    if (ti == null) {
      return TI_ERROR_MESSAGE;
    }

    final ISession session = _session;
    final ISQLConnection conn = session.getSQLConnection();

    int count = -1;

    try {
      // start the string for use in the prepared statment
      StringBuilder buf = new StringBuilder("INSERT INTO ");
      buf.append(ti.getQualifiedName());

      // Add the list of column names we will be inserting into - be sure
      // to skip the rowId column and any auto increment columns.
      buf.append(" ( ");
      for (int i = 0; i < colDefs.length; i++) {
        if (i == _rowIDcol) {
          continue;
        }
        if (colDefs[i].isAutoIncrement()) {
          if (s_log.isInfoEnabled()) {
            s_log.info("insertRow: skipping auto-increment column " + colDefs[i].getColumnName());
          }
          continue;
        }
        buf.append(colDefs[i].getColumnName());
        buf.append(",");
      }
      buf.setCharAt(buf.length() - 1, ')');
      buf.append(" VALUES (");

      // add a variable position for each of the columns
      for (int i = 0; i < colDefs.length; i++) {
        if (i != _rowIDcol && !colDefs[i].isAutoIncrement()) buf.append(" ?,");
      }

      // replace the last "," with ")"
      buf.setCharAt(buf.length() - 1, ')');

      String pstmtSQL = buf.toString();
      if (s_log.isInfoEnabled()) {
        s_log.info("insertRow: pstmt sql = " + pstmtSQL);
      }
      final PreparedStatement pstmt = conn.prepareStatement(pstmtSQL);

      try {
        // We need to keep track of the bind var index separately, since
        // the number of column defs may not be the number of bind vars
        // (For example: auto-increment columns are excluded)
        int bindVarIdx = 1;

        // have the DataType object fill in the appropriate kind of value
        // into the appropriate variable position in the prepared stmt
        for (int i = 0; i < colDefs.length; i++) {
          if (i != _rowIDcol && !colDefs[i].isAutoIncrement()) {
            CellComponentFactory.setPreparedStatementValue(
                colDefs[i], pstmt, values[i], bindVarIdx);
            bindVarIdx++;
          }
        }
        count = pstmt.executeUpdate();
      } finally {
        pstmt.close();
      }
    } catch (SQLException ex) {
      // i18n[DataSetUpdateableTableModelImpl.error.duringInsert=Exception seen during check on DB.
      // Exception was:\n{0}\nInsert was probably not completed correctly.  DB may be corrupted!]
      return s_stringMgr.getString(
          "DataSetUpdateableTableModelImpl.error.duringInsert", ex.getMessage());
    }

    if (count != 1)
      // i18n[DataSetUpdateableTableModelImpl.error.unknownerrorupdate=Unknown problem during
      // update.\nNo count of inserted rows was returned.\nDatabase may be corrupted!]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.error.unknownerrorupdate");

    // insert succeeded
    try {
      IObjectTreeAPI api = _session.getObjectTreeAPIOfActiveSessionWindow();
      api.refreshSelectedTab();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  /** Let fw get the list of default values for the columns to be used when creating a new row */
  public String[] getDefaultValues(ColumnDisplayDefinition[] colDefs) {

    // we return something valid even if there is a DB error
    final String[] defaultValues = new String[colDefs.length];

    // if we could not identify which table to edit, just return
    if (ti == null) {
      return defaultValues;
    }

    final ISession session = _session;
    final ISQLConnection conn = session.getSQLConnection();

    try {
      SQLDatabaseMetaData md = conn.getSQLMetaData();
      TableColumnInfo[] infos = md.getColumnInfo(ti);

      // read the DB MetaData info and fill in the value, if any
      // Note that the ResultSet info and the colDefs should be
      // in the same order, but we cannot guarantee that.
      int expectedColDefIndex = 0;

      for (int idx = 0; idx < infos.length; idx++) {
        String colName = infos[idx].getColumnName();
        String defValue = infos[idx].getDefaultValue();

        // if value was null, we do not need to do
        // anything else with this column.
        // Also assume that a value of "" is equivilent to null
        if (defValue != null && defValue.length() > 0) {
          // find the entry in colDefs matching this column
          if (colDefs[expectedColDefIndex].getColumnName().equals(colName)) {
            // DB cols are in same order as colDefs
            defaultValues[expectedColDefIndex] = defValue;
          } else {
            // colDefs not in same order as DB, so search for
            // matching colDef entry
            // Note: linear search here will NORMALLY be not too bad
            // because most tables do not have huge numbers of columns.
            for (int i = 0; i < colDefs.length; i++) {
              if (colDefs[i].getColumnName().equals(colName)) {
                defaultValues[i] = defValue;
                break;
              }
            }
          }
        }

        // assuming that the columns in table match colDefs,
        // bump the index to point to the next colDef entry
        expectedColDefIndex++;
      }
    } catch (Exception ex) {
      // i18n[DataSetUpdateableTableModelImpl.error.retrievingdefaultvalues=Error retrieving default
      // column values]
      s_log.error(
          s_stringMgr.getString("DataSetUpdateableTableModelImpl.error.retrievingdefaultvalues"),
          ex);
    }

    return defaultValues;
  }
  /** link from fw to this for updating data */
  public String updateTableComponent(
      Object[] values,
      ColumnDisplayDefinition[] colDefs,
      int col,
      Object oldValue,
      Object newValue) {
    // if we could not identify which table to edit, tell user
    if (ti == null) return TI_ERROR_MESSAGE;

    // get WHERE clause using original value
    List<IWhereClausePart> whereClauseParts = getWhereClause(values, colDefs, col, oldValue);
    String whereClause = whereClausePartUtil.createWhereClause(whereClauseParts);
    if (s_log.isDebugEnabled()) {
      s_log.debug("updateTableComponent: whereClause = " + whereClause);
    }

    final ISession session = _session;
    final ISQLConnection conn = session.getSQLConnection();

    int count = -1;

    final String sql =
        constructUpdateSql(ti.getQualifiedName(), colDefs[col].getColumnName(), whereClause);

    if (s_log.isDebugEnabled()) {
      s_log.debug("updateTableComponent: executing SQL - " + sql);
    }
    PreparedStatement pstmt = null;
    try {
      pstmt = conn.prepareStatement(sql);

      /*
       * have the DataType object fill in the appropriate kind of value of the changed data
       * into the first variable position in the prepared stmt
       */
      CellComponentFactory.setPreparedStatementValue(colDefs[col], pstmt, newValue, 1);

      // Fill the parameters of the where clause - start at position 2 because the data which is
      // updated is at position 1
      whereClausePartUtil.setParameters(pstmt, whereClauseParts, 2);
      count = pstmt.executeUpdate();
    } catch (SQLException ex) {
      // i18n[DataSetUpdateableTableModelImpl.error.updateproblem=There
      // was a problem reported during the update.
      // The DB message was:\n{0}\nThis may or may not be serious depending
      // on the above message.\nThe data was probably not changed in the
      // database.\nYou may need to refresh the table to get an accurate
      // view of the current data.]
      String errMsg =
          s_stringMgr.getString(
              "DataSetUpdateableTableModelImpl.error.updateproblem", ex.getMessage());
      s_log.error(
          "updateTableComponent: unexpected exception - "
              + ex.getMessage()
              + " while executing SQL: "
              + sql);

      return errMsg;
    } finally {
      SQLUtilities.closeStatement(pstmt);
    }

    if (count == -1) {
      // i18n[DataSetUpdateableTableModelImpl.error.unknownupdateerror=Unknown problem during
      // update.\nNo count of updated rows was returned.\nDatabase may be corrupted!]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.error.unknownupdateerror");
    }
    if (count == 0) {
      // i18n[DataSetUpdateableTableModelImpl.info.norowsupdated=No rows updated.]
      return s_stringMgr.getString("DataSetUpdateableTableModelImpl.info.norowsupdated");
    }
    // everything seems to have worked ok
    return null;
  }