[Schmitzm-commits] r2124 - in trunk/schmitzm-core/src/main/java/de/schmitzm: lang versionnumber

scm-commit at wald.intevation.org scm-commit at wald.intevation.org
Fri Nov 9 15:01:56 CET 2012


Author: mojays
Date: 2012-11-09 15:01:56 +0100 (Fri, 09 Nov 2012)
New Revision: 2124

Added:
   trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseControl.java
   trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseException.java
Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
Log:
LangUtil: new method replaceParameters(.) analogous to ResourceProvider.getString(..)
new ReleaseControl

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2012-11-09 14:00:46 UTC (rev 2123)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2012-11-09 14:01:56 UTC (rev 2124)
@@ -2593,4 +2593,28 @@
 		int gBytes = (int) Math.round(bytes * 1.0 / LangUtil.GB_BYTES);
 		return kBytes + " GB";
 	}
+    
+    
+    /**
+     * Replaces all {@code ${0}}, {@code ${1}}, ... occurencies (wildcards)
+     * in a string with the given parameters.
+     * @param string
+     *            String which contains the wildcards 
+     * @param replParams
+     *            Strings/Numbers, which are used as replacements for the
+     *            wildcards <code>${0}</code>, <code>${1}</code>, <code>${2}</code>, etc.
+     */
+    public static String replaceParameters(String string, Object... replParams) {
+      String replString = null;
+      for (int i = 0; i < replParams.length; i++) {
+        replString = replParams[i] != null ? replParams[i].toString() : "null";
+        // Problem with replacement of '$' sign in
+        // replace string, so first quote these characters
+        // in the replacement
+        replString = Matcher.quoteReplacement(replString);
+        // Perform the "real" replacement for the ${..}
+        string = string.replaceAll("\\$\\{" + i + "\\}", replString);
+      }
+      return string;
+    }
 }

Added: trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseControl.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseControl.java	                        (rev 0)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseControl.java	2012-11-09 14:01:56 UTC (rev 2124)
@@ -0,0 +1,245 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ * 
+ * This file is part of the SCHMITZM library - a collection of utility 
+ * classes based on Java 1.6, focusing (not only) on Java Swing 
+ * and the Geotools library.
+ * 
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ * 
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ * 
+ * Contributors:
+ *     Martin O. J. Schmitz - initial API and implementation
+ *     Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.versionnumber;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+
+import de.schmitzm.lang.LangUtil;
+
+/**
+ * This class helps to check consistency between (Hibernate) database and
+ * program application.<br>
+ * The {@link ReleaseControl} expects a parameters table in the database
+ * which holds a required build number for the front-end application.
+ * {@link #checkApplicationRelease()} checks this number is checked against
+ * the build number provided by {@link ReleaseUtil#getVersionBuild(Class)}.
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class ReleaseControl {
+  protected Logger LOGGER = LangUtil.createLogger(this); 
+  
+  /** Application class used as reference for {@link ReleaseUtil#getVersionBuild(Class)}. */
+  protected Class<?> applClass;
+  /** Name of parameters table in database where the required application
+   *  release number can be found. */
+  protected String paramTableName;
+  /** Name of column (in parameters table) where the required application
+   *  release number can be found (String column required!). */
+  protected String reqReleaseColName;
+  /** Exception message in case of release conflict. */
+  protected String confictMess = "Application release conflict! The database requires application release '${0}' while you are currently using release ${1}.";
+  
+  
+  /**
+   * Creates a new release control.
+   * @param applClass application class used as reference for {@link ReleaseUtil#getVersionBuild(Class)}
+   * @param tableName Name of parameters table in database where the required application
+   *                  release number can be found
+   * @param colName   Name of column (in parameters table) where the required application
+   *                  release number can be found (String column required!)
+   */
+  public ReleaseControl(Class<?> applClass, String tableName, String colName) {
+    this.applClass = applClass;
+    this.paramTableName = tableName;
+    this.reqReleaseColName = colName;
+  }
+  
+  
+  /**
+   * Returns the application class used as reference for
+   * {@link ReleaseUtil#getVersionBuild(Class)} to determine build
+   * number of running application.
+   */
+  public Class<?> getApplicationClass() {
+    return applClass;
+  }
+  
+  /**
+   * Returns the release number of the running application.
+   * @see ReleaseUtil#getVersionBuild(Class)
+   */
+  public String getApplicationReleaseNumber() {
+    return ReleaseUtil.getVersionBuild(getApplicationClass());
+  }
+
+
+  /**
+   * Returns the name of the parameters table in database where the
+   * required application release number can be found.
+   */
+  public String getParametersTableName() {
+    return paramTableName;
+  }
+
+
+  /**
+   * Returns the column name (in parameters table) where the required application
+   * release number can be found (String column required!).
+   */
+  public String getRequiredReleaseColName() {
+    return reqReleaseColName;
+  }
+
+  /**
+   * Returns the exception message thrown in case of release conflict.
+   * Message contains wildcard {@code ${0}} for expected release number and
+   * {@code ${1}} for current application release number.
+   */
+  public String getConfictMess() {
+    return confictMess;
+  }
+
+
+  /**
+   * Sets the exception message thrown in case of release conflict.
+   * Message can contain wildcard {@code ${0}} for expected release number and
+   * {@code ${1}} for current application release number.
+   */
+  public void setConfictMess(String confictMess) {
+    this.confictMess = confictMess;
+  }
+
+
+  /**
+   * Checks whether the current application version fits the given expected
+   * version.<br>
+   * <b>Note:</b> If the release number of the running application is not
+   * present, the method expects that the running application is an up-to-date
+   * build, e.g. run from Eclipse. In this case this method returns {@code true}!
+   * @param expectedBuild expected build number (e.g. from database) the running
+   *                      application build number is checked against
+   */
+  public boolean checkApplicationRelease(String expectedBuild) {
+    String currProgrVersion = getApplicationReleaseNumber(); // Format: YYYYMMDDHHMM
+    long   currProgrVersionNum = StringUtils.isBlank(currProgrVersion) ? 0 : Long.parseLong(currProgrVersion);
+    // if current version number is not set, we are running an
+    // up-to-date build (e.g. from Eclipse)
+    if ( currProgrVersionNum == 0 )
+      return true;
+    long expProgrVersionNum = StringUtils.isBlank(expectedBuild) ? 0 : Long.parseLong(expectedBuild);
+    return currProgrVersionNum >= expProgrVersionNum;
+  }
+
+  
+  /**
+   * Checks whether the current application version fits the required version
+   * set in the database
+   * @param connURL  database connection URL
+   * @param user     database user used for database connection
+   * @param password password used for database connection
+   */
+  public void checkApplicationRelease(String connURL, String user, String password) throws SQLException {
+    Connection conn = DriverManager.getConnection(connURL, user, password);
+    try {
+      checkApplicationRelease(conn);
+    } finally {
+      conn.close();
+    }
+  }
+  
+  /**
+   * Checks whether the current application version fits the required version
+   * set in the database
+   * @param conn  database connection
+   */
+  public void checkApplicationRelease(Connection conn) throws SQLException {
+      String    expProgrVersion = "";
+      Statement stmt = conn.createStatement();
+      try {
+        ResultSet rs = stmt.executeQuery("SELECT "+getRequiredReleaseColName()+" FROM "+getParametersTableName());
+        if ( rs.next() )
+          expProgrVersion = rs.getString(getRequiredReleaseColName());
+        rs.close();
+      } catch (SQLException err) {
+        LOGGER.warn("Parameters table '"+getParametersTableName()+"' does not exist. Try to create table...");
+        // Error executing the query -> table does not exist
+        // -> create table
+        createParametersTable(conn);
+      }
+      if ( !checkApplicationRelease(expProgrVersion) ) {
+        String mess = LangUtil.replaceParameters(getConfictMess(), expProgrVersion, getApplicationReleaseNumber());
+        throw new ReleaseException(mess);
+      }
+  }
+
+  /**
+   * Creates a parameters table in database schema.
+   * @param conn connection used to create the table
+   */
+  protected void createParametersTable(Connection conn) throws SQLException {
+    conn.setAutoCommit(false);
+    Statement stmt = conn.createStatement();
+    // Create table
+    String    stmtStr = "CREATE TABLE "+getParametersTableName()+" ("
+                      + "id INT PRIMARY KEY DEFAULT 1, "
+                      + getRequiredReleaseColName() + " VARCHAR(20)"
+                      + ")";
+    stmt.execute(stmtStr);
+    // Insert default record
+    stmtStr = "INSERT INTO "+getParametersTableName()+" DEFAULT VALUES";
+    stmt.execute(stmtStr);
+    
+    conn.commit();
+    LOGGER.warn("Parameters table '"+getParametersTableName()+"' created.");
+  }
+  
+  /**
+   * Updates the required application release number in database to the
+   * build number of the running application.
+   * @param conn connection used to update the table
+   */
+  protected void updateRequiredVersionInDatabase(Connection conn) throws SQLException {
+    String reqVersion = getApplicationReleaseNumber();
+    updateRequiredVersionInDatabase(conn, reqVersion );
+  }
+
+  /**
+   * Updates the required application release number in database.
+   * @param conn connection used to update the table
+   * @param reqVersion build number to set
+   */
+  protected void updateRequiredVersionInDatabase(Connection conn, String reqVersion) throws SQLException {
+    PreparedStatement stmt = conn.prepareStatement("UPDATE "+getParametersTableName()+
+                                                   " SET "+getRequiredReleaseColName()+" = ?");
+    stmt.setString(1, reqVersion);
+    stmt.execute();
+  }
+  
+
+}

Added: trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseException.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseException.java	                        (rev 0)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/versionnumber/ReleaseException.java	2012-11-09 14:01:56 UTC (rev 2124)
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2009 Martin O. J. Schmitz.
+ * 
+ * This file is part of the SCHMITZM library - a collection of utility 
+ * classes based on Java 1.6, focusing (not only) on Java Swing 
+ * and the Geotools library.
+ * 
+ * The SCHMITZM project is hosted at:
+ * http://wald.intevation.org/projects/schmitzm/
+ * 
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 3
+ * of the License, or (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public License (license.txt)
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ * or try this link: http://www.gnu.org/licenses/lgpl.html
+ * 
+ * Contributors:
+ *     Martin O. J. Schmitz - initial API and implementation
+ *     Stefan A. Tzeggai - additional utility classes
+ */
+package de.schmitzm.versionnumber;
+
+import java.sql.SQLException;
+
+/**
+ * Special {@link SQLException} indicating release conflict between database and
+ * running application.
+ * @author Martin O.J. Schmitz
+ *
+ */
+public class ReleaseException extends SQLException {
+
+  /**
+   * Creates a new exception.
+   */
+  public ReleaseException() {
+    super();
+  }
+
+  /**
+   * Creates a new exception.
+   */
+  public ReleaseException(String message) {
+    super(message);
+  }
+  
+
+}



More information about the Schmitzm-commits mailing list