[jboss-cvs] JBossCache/src/org/jboss/cache/loader ...

Mircea Markus mircea.markus at gmail.com
Mon Mar 5 16:10:43 EST 2007


  User: mmarkus 
  Date: 07/03/05 16:10:43

  Modified:    src/org/jboss/cache/loader         
                        C3p0ConnectionFactory.java ConnectionFactory.java
                        JDBCCacheLoader.java JDBCCacheLoaderConfig.java
                        JDBCCacheLoaderOld.java
                        ManagedConnectionFactory.java
                        NonManagedConnectionFactory.java
  Added:       src/org/jboss/cache/loader         
                        AdjListJDBCCacheLoader.java
                        AdjListJDBCCacheLoaderConfig.java
  Log:
  some classes were incorreclly named *JDBCClassLoader* instead of *JDBCCacheLoader*. The typo was fixed.
  
  Revision  Changes    Path
  1.3       +1 -1      JBossCache/src/org/jboss/cache/loader/C3p0ConnectionFactory.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: C3p0ConnectionFactory.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/C3p0ConnectionFactory.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -b -r1.2 -r1.3
  --- C3p0ConnectionFactory.java	10 Feb 2007 17:47:02 -0000	1.2
  +++ C3p0ConnectionFactory.java	5 Mar 2007 21:10:43 -0000	1.3
  @@ -27,7 +27,7 @@
   
      private DataSource ds;
   
  -   public void setConfig(AdjListJDBCClassLoaderConfig config)
  +   public void setConfig(AdjListJDBCCacheLoaderConfig config)
      {
         super.setConfig(config);
   
  
  
  
  1.3       +1 -1      JBossCache/src/org/jboss/cache/loader/ConnectionFactory.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: ConnectionFactory.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/ConnectionFactory.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -b -r1.2 -r1.3
  --- ConnectionFactory.java	10 Feb 2007 17:47:02 -0000	1.2
  +++ ConnectionFactory.java	5 Mar 2007 21:10:43 -0000	1.3
  @@ -17,7 +17,7 @@
    */
   public interface ConnectionFactory
   {
  -    void setConfig(AdjListJDBCClassLoaderConfig config);
  +    void setConfig(AdjListJDBCCacheLoaderConfig config);
   
       void start() throws Exception;
   
  
  
  
  1.33      +4 -4      JBossCache/src/org/jboss/cache/loader/JDBCCacheLoader.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: JDBCCacheLoader.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/JDBCCacheLoader.java,v
  retrieving revision 1.32
  retrieving revision 1.33
  diff -u -b -r1.32 -r1.33
  --- JDBCCacheLoader.java	10 Feb 2007 17:47:02 -0000	1.32
  +++ JDBCCacheLoader.java	5 Mar 2007 21:10:43 -0000	1.33
  @@ -18,7 +18,7 @@
   import java.util.Map;
   
   /**
  - * JDBC implementation of <tt>AdjListJDBCClassLoader</tt>.
  + * JDBC implementation of <tt>AdjListJDBCCacheLoader</tt>.
    * Represents a faster alternative than JDBCCacheLoaderOld and relies on the same database structrure.
    * It is backward compatible with data created by existing <tt>JDBCCacheLoaderOld</tt> implemetation.
    * All configuration elements described there {@link org.jboss.cache.loader.JDBCCacheLoaderOld} also apply for this
  @@ -32,7 +32,7 @@
    * @author Mircea.Markus at iquestint.com
    * @version 1.0
    */
  -public class JDBCCacheLoader extends AdjListJDBCClassLoader
  +public class JDBCCacheLoader extends AdjListJDBCCacheLoader
   {
   
       private static final Log log = LogFactory.getLog(JDBCCacheLoader.class);
  @@ -40,9 +40,9 @@
       private JDBCCacheLoaderConfig config;
   
       /**
  -     * Builds a AdjListJDBCClassLoaderConfig based on the supplied base config.
  +     * Builds a AdjListJDBCCacheLoaderConfig based on the supplied base config.
        */
  -    protected AdjListJDBCClassLoaderConfig processConfig(CacheLoaderConfig.IndividualCacheLoaderConfig base)
  +    protected AdjListJDBCCacheLoaderConfig processConfig(CacheLoaderConfig.IndividualCacheLoaderConfig base)
       {
           if (base instanceof JDBCCacheLoaderConfig)
           {
  
  
  
  1.6       +1 -1      JBossCache/src/org/jboss/cache/loader/JDBCCacheLoaderConfig.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: JDBCCacheLoaderConfig.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/JDBCCacheLoaderConfig.java,v
  retrieving revision 1.5
  retrieving revision 1.6
  diff -u -b -r1.5 -r1.6
  --- JDBCCacheLoaderConfig.java	21 Feb 2007 15:31:31 -0000	1.5
  +++ JDBCCacheLoaderConfig.java	5 Mar 2007 21:10:43 -0000	1.6
  @@ -12,7 +12,7 @@
    * @author Mircea.Markus at iquestint.com
    * @version 1.0
    */
  -public class JDBCCacheLoaderConfig extends AdjListJDBCClassLoaderConfig
  +public class JDBCCacheLoaderConfig extends AdjListJDBCCacheLoaderConfig
   {
   
       private static final long serialVersionUID = -8371846151643130271L;
  
  
  
  1.2       +7 -7      JBossCache/src/org/jboss/cache/loader/JDBCCacheLoaderOld.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: JDBCCacheLoaderOld.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/JDBCCacheLoaderOld.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -b -r1.1 -r1.2
  --- JDBCCacheLoaderOld.java	10 Feb 2007 17:47:02 -0000	1.1
  +++ JDBCCacheLoaderOld.java	5 Mar 2007 21:10:43 -0000	1.2
  @@ -61,24 +61,24 @@
    * @author <a href="mailto:alex at jboss.org">Alexey Loubyansky</a>
    * @author <a href="mailto:hmesha at novell.com">Hany Mesha </a>
    * @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
  - * @version <tt>$Revision: 1.1 $</tt>
  + * @version <tt>$Revision: 1.2 $</tt>
    * @deprecated please use the 
    */
  -public class JDBCCacheLoaderOld extends AdjListJDBCClassLoader
  +public class JDBCCacheLoaderOld extends AdjListJDBCCacheLoader
   {
       private static final Log log = LogFactory.getLog(JDBCCacheLoaderOld.class);
   
  -    private AdjListJDBCClassLoaderConfig config;
  +    private AdjListJDBCCacheLoaderConfig config;
   
   
  -    public AdjListJDBCClassLoaderConfig processConfig(IndividualCacheLoaderConfig base)
  +    public AdjListJDBCCacheLoaderConfig processConfig(IndividualCacheLoaderConfig base)
       {
  -        if (config instanceof AdjListJDBCClassLoaderConfig)
  +        if (config instanceof AdjListJDBCCacheLoaderConfig)
           {
  -            config = (AdjListJDBCClassLoaderConfig) base;
  +            config = (AdjListJDBCCacheLoaderConfig) base;
           } else
           {
  -            config = new AdjListJDBCClassLoaderConfig(base);
  +            config = new AdjListJDBCCacheLoaderConfig(base);
           }
           return config;
       }
  
  
  
  1.3       +1 -1      JBossCache/src/org/jboss/cache/loader/ManagedConnectionFactory.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: ManagedConnectionFactory.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/ManagedConnectionFactory.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -b -r1.2 -r1.3
  --- ManagedConnectionFactory.java	10 Feb 2007 17:47:02 -0000	1.2
  +++ ManagedConnectionFactory.java	5 Mar 2007 21:10:43 -0000	1.3
  @@ -28,7 +28,7 @@
      private DataSource dataSource;
      private String datasourceName;
   
  -   public void setConfig(AdjListJDBCClassLoaderConfig config)
  +   public void setConfig(AdjListJDBCCacheLoaderConfig config)
      {
         datasourceName = config.getDatasourceName();
      }
  
  
  
  1.3       +1 -1      JBossCache/src/org/jboss/cache/loader/NonManagedConnectionFactory.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: NonManagedConnectionFactory.java
  ===================================================================
  RCS file: /cvsroot/jboss/JBossCache/src/org/jboss/cache/loader/NonManagedConnectionFactory.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -b -r1.2 -r1.3
  --- NonManagedConnectionFactory.java	10 Feb 2007 17:47:02 -0000	1.2
  +++ NonManagedConnectionFactory.java	5 Mar 2007 21:10:43 -0000	1.3
  @@ -30,7 +30,7 @@
      private String pwd;
      private String driverClass;
   
  -   public void setConfig(AdjListJDBCClassLoaderConfig config)
  +   public void setConfig(AdjListJDBCCacheLoaderConfig config)
      {
         url = config.getJdbcURL();
         usr = config.getJdbcUser();
  
  
  
  1.1      date: 2007/03/05 21:10:43;  author: mmarkus;  state: Exp;JBossCache/src/org/jboss/cache/loader/AdjListJDBCCacheLoader.java
  
  Index: AdjListJDBCCacheLoader.java
  ===================================================================
  package org.jboss.cache.loader;
  
  import org.jboss.cache.Fqn;
  import org.jboss.cache.Modification;
  import org.jboss.cache.util.Util;
  import org.jboss.cache.config.CacheLoaderConfig;
  import org.apache.commons.logging.Log;
  
  import java.util.*;
  import java.sql.*;
  import java.io.InputStream;
  import java.io.IOException;
  import java.io.ByteArrayInputStream;
  
  /**
   * Adjacency List Model is the model of persisting trees in which each children holds a reference to its parent.
   * An alternative model is the Nested Set Model (a.k.a. Modified Preorder Model) - this approach adds some additional
   * indexing information to each persisted node. This indexing info is further used for optimizing operations like
   * subtree loading, deleting etc. The indexes are update for each insertion.
   * <p/>
   * Adjacency List Model proved more performance-effective for the following reason: the entire path is persisted rather
   * than only a reference to parent. Looking up nodes heavily relies on that, and the performance is similar as in the
   * case of Modified Preorder Model. Even more there is no costly update indexes operation.
   *
   * @author Mircea.Markus at iquestint.com
   * @version 1.0
   */
  public abstract class AdjListJDBCCacheLoader extends AbstractCacheLoader
  {
      protected ConnectionFactory cf;
      protected String driverName;
      private AdjListJDBCCacheLoaderConfig config;
  
      public void setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig base)
      {
          config = processConfig(base);
  
          if (config.getDatasourceName() == null)
          {
              try
              {
                  /* Instantiate an standalone connection factory as per configuration, either explicitly
                  defined or the default one */
                  cf = (ConnectionFactory) Util.loadClass(config.getConnectionFactoryClass()).newInstance();
              }
              catch (Exception e)
              {
                  getLogger().error("Connectionn factory class could not be loaded", e);
                  throw new IllegalStateException("Connectionn factory class could not be loaded", e);
              }
          } else
          {
              /* We create the ManagedConnectionFactory instance but the JNDI lookup is no done until
              the start method is called, since that's when its registered in its lifecycle */
              cf = new ManagedConnectionFactory();
          }
          /* Regardless of the type of connection factory, we set the configuration */
          cf.setConfig(config);
      }
  
  
      /**
       * Returns a map representing a node.
       *
       * @param name node's fqn
       * @return node
       * @throws Exception
       */
      public Map get(Fqn name) throws Exception
      {
          final Map node = loadNode(name);
          return node == NULL_NODE_IN_ROW ? new HashMap(0) : node;
      }
  
      /**
       * Fetches child node names (not pathes).
       *
       * @param fqn parent fqn
       * @return a set of child node names or null if there are not children found for the fqn
       * @throws Exception
       */
      public Set<String> getChildrenNames(Fqn fqn) throws Exception
      {
          Set children = null;
          Connection con = null;
          PreparedStatement ps = null;
          ResultSet rs = null;
          try
          {
              if (getLogger().isDebugEnabled())
              {
                  getLogger().debug("executing sql: " + config.getSelectChildNamesSql() + " (" + fqn + ")");
              }
  
              con = cf.getConnection();
              ps = con.prepareStatement(config.getSelectChildNamesSql());
              ps.setString(1, fqn.toString());
              rs = ps.executeQuery();
              if (rs.next())
              {
                  children = new HashSet();
                  do
                  {
                      String child = rs.getString(1);
                      int slashInd = child.lastIndexOf('/');
                      String name = child.substring(slashInd + 1);
                      //Fqn childFqn = Fqn.fromString(child);
                      //String name = (String) childFqn.get(childFqn.size() - 1);
                      children.add(name);
                  }
                  while (rs.next());
              }
          }
          catch (SQLException e)
          {
              reportAndRethrowError("Failed to get children names for fqn " + fqn, e);
          }
          finally
          {
              safeClose(rs);
              safeClose(ps);
              cf.close(con);
          }
  
          return children == null ? null : Collections.unmodifiableSet(children);
      }
  
  
      /**
       * Nullifies the node.
       *
       * @param name node's fqn
       * @throws Exception
       */
      public void removeData(Fqn name) throws Exception
      {
          updateNode(name, null);
      }
  
      /**
       * First phase in transaction commit process. The changes are committed if only one phase if requested.
       * All the modifications are committed using the same connection.
       *
       * @param tx            something representing transaction
       * @param modifications a list of modifications
       * @param one_phase     indicates whether it's one or two phase commit transaction
       * @throws Exception
       */
      public void prepare(Object tx, List<Modification> modifications, boolean one_phase) throws Exception
      {
          // start a tx
          cf.prepare(tx);
  
          try
          {
              put(modifications);
  
              // commit if it's one phase only
              if (one_phase)
              {
                  commit(tx);
              }
          }
          catch (Exception e)
          {
              // todo should I rollback it here or rollback is supposed to be invoke by someone from outside?
              rollback(tx);
              // is this ok?
              throw e;
          }
      }
  
  
      /**
       * Commits a transaction.
       *
       * @param tx the tx to commit
       * @throws Exception
       */
      public void commit(Object tx) throws Exception
      {
          cf.commit(tx);
      }
  
      /**
       * Rolls back a transaction.
       *
       * @param tx the tx to rollback
       */
      public void rollback(Object tx)
      {
          cf.rollback(tx);
      }
  
      // Service implementation
  
      public void create() throws Exception
      {
      }
  
      public void start() throws Exception
      {
          cf.start();
  
          Connection con = null;
          Statement st = null;
  
          try
          {
              con = cf.getConnection();
              driverName = getDriverName(con);
              if (config.getCreateTable())
              {
                  if (!tableExists(config.getTable(), con))
                  {
                      if (getLogger().isDebugEnabled())
                      {
                          getLogger().debug("executing ddl: " + config.getCreateTableDDL());
                      }
                      st = con.createStatement();
                      st.executeUpdate(config.getCreateTableDDL());
                  }
              }
          }
          finally
          {
              safeClose(st);
              cf.close(con);
          }
      }
  
      public void stop()
      {
          if (config.getDropTable())
          {
              Connection con = null;
              Statement st = null;
              try
              {
                  if (getLogger().isDebugEnabled())
                  {
                      getLogger().debug("executing ddl: " + config.getDropTableDDL());
                  }
  
                  con = cf.getConnection();
                  st = con.createStatement();
                  st.executeUpdate(config.getDropTableDDL());
                  safeClose(st);
              }
              catch (SQLException e)
              {
                  getLogger().error("Failed to drop table: " + e.getMessage(), e);
              }
              finally
              {
                  safeClose(st);
                  cf.close(con);
                  cf.stop();
              }
          }
      }
  
      public void destroy()
      {
      }
  
  
      /**
       * Checks that there is a row for the fqn in the database.
       *
       * @param name node's fqn
       * @return true if there is a row in the database for the given fqn even if the node column is null.
       * @throws Exception
       */
      public boolean exists(Fqn name) throws Exception
      {
          final Map node = loadNode(name);
          return node != null;// && node != NULL_NODE_IN_ROW;
      }
  
      /**
       * Removes attribute's value for a key. If after removal the node contains no attributes, the node is nullified.
       *
       * @param name node's name
       * @param key  attribute's key
       * @return removed value or null if there was no value for the passed in key
       * @throws Exception
       */
      public Object remove(Fqn name, Object key) throws Exception
      {
          Object removedValue = null;
          Map node = loadNode(name);
          if (node != null && node != NULL_NODE_IN_ROW)
          {
              removedValue = node.remove(key);
              if (node.isEmpty())
              {
                  updateNode(name, null);
              } else
              {
                  updateNode(name, node);
              }
          }
          return removedValue;
      }
  
  
      /**
       * Loads a node from the database.
       *
       * @param name the fqn
       * @return non-null Map representing the node,
       *         null if there is no row with the fqn in the table,
       *         NULL_NODE_IN_ROW if there is a row in the table with the fqn but the node column contains null.
       */
      protected Map loadNode(Fqn name)
      {
          boolean rowExists = false;
          Map oldNode = null;
          Connection con = null;
          PreparedStatement ps = null;
          ResultSet rs = null;
          try
          {
              if (getLogger().isDebugEnabled())
              {
                  getLogger().debug("executing sql: " + config.getSelectNodeSql() + " (" + name + ")");
              }
  
              con = cf.getConnection();
              ps = con.prepareStatement(config.getSelectNodeSql());
              ps.setString(1, name.toString());
  
              rs = ps.executeQuery();
  
              if (rs.next())
              {
                  rowExists = true;
                  InputStream is = rs.getBinaryStream(1);
                  if (is != null && !rs.wasNull())
                  {
                      try
                      {
                          //                 ObjectInputStream ois = null;
                          //                 ois = new ObjectInputStream(is);
                          //                 Object marshalledNode = ois.readObject();
  
                          // deserialize result
                          Object marshalledNode = getMarshaller().objectFromStream(is);
                          oldNode = (Map) marshalledNode;
                      }
                      catch (Exception e)
                      {
                          throw new Exception("Unable to load to deserialize result: ", e);
                      }
                      finally
                      {
                          safeClose(is);
                      }
                  }
              }
          }
          catch (Exception e)
          {
              reportAndRethrowError("Failed to load node for fqn " + name, e);
          }
          finally
          {
              safeClose(rs);
              safeClose(ps);
              cf.close(con);
          }
  
          return oldNode == null ? (rowExists ? NULL_NODE_IN_ROW : null) : oldNode;
      }
  
  
      /**
       * Inserts a node into the database
       *
       * @param name the fqn
       * @param node the node
       */
      protected void insertNode(Fqn name, Map node)
      {
          Connection con = null;
          PreparedStatement ps = null;
          try
          {
              if (getLogger().isDebugEnabled())
              {
                  getLogger().debug("executing sql: " + config.getInsertNodeSql() + " (" + name + ")");
              }
  
              con = cf.getConnection();
              ps = con.prepareStatement(config.getInsertNodeSql());
  
              ps.setString(1, name.toString());
  
              if (node != null)
              {
                  //            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  //            ObjectOutputStream oos = new ObjectOutputStream(baos);
                  //            oos.writeObject(node);
  
                  byte[] byteStream = getMarshaller().objectToByteBuffer(node);
                  ByteArrayInputStream bais = new ByteArrayInputStream(byteStream);
                  ps.setBinaryStream(2, bais, byteStream.length);
              } else
              {
                  // a hack to handles the incomp. of SQL server jdbc driver prior to SQL SERVER 2005
                  if (driverName != null && (driverName.contains("SQLSERVER")
                          || driverName.contains("POSTGRESQL")))
                  {
                      ps.setNull(2, Types.LONGVARBINARY);
                  } else
                  {
                      ps.setNull(2, Types.BLOB);
                  }
                  //ps.setNull(2, Types.LONGVARBINARY);
              }
  
              if (name.size() == 0)
              {
                  ps.setNull(3, Types.VARCHAR);
              } else
              {
                  ps.setString(3, name.getFqnChild(name.size() - 1).toString());
              }
  
              int rows = ps.executeUpdate();
              if (rows != 1)
              {
                  throw new IllegalStateException("Expected one insert row but got " + rows);
              }
          }
          catch (RuntimeException e)
          {
              throw e;
          }
          catch (Exception e)
          {
              getLogger().error("Failed to insert node :" + e.getMessage());
              throw new IllegalStateException("Failed to insert node: " + e.getMessage(), e);
          }
          finally
          {
              safeClose(ps);
              cf.close(con);
          }
      }
  
  
      /**
       * Updates a node in the database.
       *
       * @param name the fqn
       * @param node new node value
       */
      protected void updateNode(Fqn name, Map node)
      {
          Connection con = null;
          PreparedStatement ps = null;
          try
          {
              if (getLogger().isDebugEnabled())
              {
                  getLogger().debug("executing sql: " + config.getUpdateNodeSql());
              }
  
              con = cf.getConnection();
              ps = con.prepareStatement(config.getUpdateNodeSql());
  
              if (node == null)
              {
                  //ps.setNull(1, Types.BLOB);
                  //            ps.setNull(1, Types.LONGVARBINARY);
                  // don't set it to null - simply use an empty hash map.
                  node = new HashMap(0);
              }
  
              //         ByteArrayOutputStream baos = new ByteArrayOutputStream();
              //         ObjectOutputStream oos = new ObjectOutputStream(baos);
              //         oos.writeObject(node);
  
              byte[] byteStream = getMarshaller().objectToByteBuffer(node);
              ByteArrayInputStream bais = new ByteArrayInputStream(byteStream);
              ps.setBinaryStream(1, bais, byteStream.length);
  
              ps.setString(2, name.toString());
  
              int rows = ps.executeUpdate();
              //         if (rows != 1)
              //         {
              //            throw new IllegalStateException("Expected one updated row but got " + rows);
              //         }
          }
          catch (Exception e)
          {
              reportAndRethrowError("Failed to update node for fqn " + name, e);
          }
          finally
          {
              safeClose(ps);
              cf.close(con);
          }
      }
  
      protected String getDriverName(Connection con)
      {
          if (con == null) return null;
          try
          {
              DatabaseMetaData dmd = con.getMetaData();
              return toUpperCase(dmd.getDriverName());
          }
          catch (SQLException e)
          {
              // This should not happen. A J2EE compatiable JDBC driver is
              // required to fully support metadata.
              throw new IllegalStateException("Error while getting the driver name", e);
          }
      }
  
      static String getRequiredProperty(Properties props, String name)
      {
          String value = props.getProperty(name);
          if (value == null)
          {
              throw new IllegalStateException("Missing required property: " + name);
          }
          return value;
      }
  
      protected boolean tableExists(String tableName, Connection con)
      {
          ResultSet rs = null;
          try
          {
              // (a j2ee spec compatible jdbc driver has to fully
              // implement the DatabaseMetaData)
              DatabaseMetaData dmd = con.getMetaData();
              String catalog = con.getCatalog();
              String schema = null;
              String quote = dmd.getIdentifierQuoteString();
              if (tableName.startsWith(quote))
              {
                  if (!tableName.endsWith(quote))
                  {
                      throw new IllegalStateException("Mismatched quote in table name: " + tableName);
                  }
                  int quoteLength = quote.length();
                  tableName = tableName.substring(quoteLength, tableName.length() - quoteLength);
                  if (dmd.storesLowerCaseQuotedIdentifiers())
                  {
                      tableName = toLowerCase(tableName);
                  } else if (dmd.storesUpperCaseQuotedIdentifiers())
                  {
                      tableName = toUpperCase(tableName);
                  }
              } else
              {
                  if (dmd.storesLowerCaseIdentifiers())
                  {
                      tableName = toLowerCase(tableName);
                  } else if (dmd.storesUpperCaseIdentifiers())
                  {
                      tableName = toUpperCase(tableName);
                  }
              }
  
              int dotIndex;
              if ((dotIndex = tableName.indexOf('.')) != -1)
              {
                  // Yank out schema name ...
                  schema = tableName.substring(0, dotIndex);
                  tableName = tableName.substring(dotIndex + 1);
              }
  
              rs = dmd.getTables(catalog, schema, tableName, null);
              return rs.next();
          }
          catch (SQLException e)
          {
              // This should not happen. A J2EE compatiable JDBC driver is
              // required fully support metadata.
              throw new IllegalStateException("Error while checking if table aleady exists " + tableName, e);
          }
          finally
          {
              safeClose(rs);
          }
      }
  
  
      protected abstract Log getLogger();
  
      protected abstract AdjListJDBCCacheLoaderConfig processConfig(CacheLoaderConfig.IndividualCacheLoaderConfig base);
  
      protected void reportAndRethrowError(String message, Exception cause) throws IllegalStateException
      {
          getLogger().error(message, cause);
          throw new IllegalStateException(message, cause);
      }
  
      protected void safeClose(InputStream is)
      {
          if (is != null)
          {
              try
              {
                  is.close();
              }
              catch (IOException e)
              {
                  getLogger().warn("Failed to close input stream: " + e.getMessage());
              }
          }
      }
  
      protected void safeClose(Statement st)
      {
          if (st != null)
          {
              try
              {
                  st.close();
              }
              catch (SQLException e)
              {
                  getLogger().warn("Failed to close statement: " + e.getMessage());
              }
          }
      }
  
      protected void safeClose(ResultSet rs)
      {
          if (rs != null)
          {
              try
              {
                  rs.close();
              }
              catch (SQLException e)
              {
                  getLogger().warn("Failed to close result set: " + e.getMessage());
              }
          }
      }
  
      private static String toUpperCase(String s)
      {
          return s.toUpperCase(Locale.ENGLISH);
      }
  
      private static String toLowerCase(String s)
      {
          return s.toLowerCase((Locale.ENGLISH));
      }
  
      // Inner
  
      protected static final Map NULL_NODE_IN_ROW = new Map()
      {
          public int size()
          {
              throw new UnsupportedOperationException();
          }
  
          public void clear()
          {
              throw new UnsupportedOperationException();
          }
  
          public boolean isEmpty()
          {
              throw new UnsupportedOperationException();
          }
  
          public boolean containsKey(Object key)
          {
              throw new UnsupportedOperationException();
          }
  
          public boolean containsValue(Object value)
          {
              throw new UnsupportedOperationException();
          }
  
          public Collection values()
          {
              throw new UnsupportedOperationException();
          }
  
          public void putAll(Map t)
          {
              throw new UnsupportedOperationException();
          }
  
          public Set entrySet()
          {
              throw new UnsupportedOperationException();
          }
  
          public Set keySet()
          {
              throw new UnsupportedOperationException();
          }
  
          public Object get(Object key)
          {
              throw new UnsupportedOperationException();
          }
  
          public Object remove(Object key)
          {
              throw new UnsupportedOperationException();
          }
  
          public Object put(Object key, Object value)
          {
              throw new UnsupportedOperationException();
          }
      };
  
  }
  
  
  
  1.1      date: 2007/03/05 21:10:43;  author: mmarkus;  state: Exp;JBossCache/src/org/jboss/cache/loader/AdjListJDBCCacheLoaderConfig.java
  
  Index: AdjListJDBCCacheLoaderConfig.java
  ===================================================================
  package org.jboss.cache.loader;
  
  import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
  
  import java.util.Properties;
  
  /**
   * AdjListJDBCCacheLoaderConfig
   *
   * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
   * @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
   */
  public class AdjListJDBCCacheLoaderConfig extends IndividualCacheLoaderConfig
  {
      /**
       * The serialVersionUID
       */
      private static final long serialVersionUID = -8371846151643130281L;
  
      private boolean createTable;
      private String createTableDDL;
      private String datasourceName;
      private String deleteAllSql;
      private String deleteNodeSql;
      private boolean dropTable;
      private String dropTableDDL;
      private String driverClass;
      private String insertNodeSql;
      private String jdbcURL;
      private String jdbcUser;
      private String jdbcPassword;
      private String selectChildFqnsSql;
      private String selectChildNamesSql;
      private String selectNodeSql;
      private String updateNodeSql;
      private String updateTableSql;
      private String connectionFactoryClass;
      protected String table;
      protected String nodeColumn;
      protected String fqnColumn;
  
      public AdjListJDBCCacheLoaderConfig()
      {
          setClassName(JDBCCacheLoaderOld.class.getName());
      }
  
      /**
       * For use by {@link JDBCCacheLoaderOld}.
       *
       * @param base generic config object created by XML parsing.
       */
      AdjListJDBCCacheLoaderConfig(IndividualCacheLoaderConfig base)
      {
          setClassName(JDBCCacheLoaderOld.class.getName());
          populateFromBaseConfig(base);
      }
  
      public boolean getCreateTable()
      {
          return createTable;
      }
  
      public void setCreateTable(boolean createTable)
      {
          testImmutability("createTable");
          this.createTable = createTable;
      }
  
      public String getCreateTableDDL()
      {
          return createTableDDL;
      }
  
      public void setCreateTableDDL(String createTableDDL)
      {
          testImmutability("createTableDDL");
          this.createTableDDL = createTableDDL;
      }
  
      public String getDatasourceName()
      {
          return datasourceName;
      }
  
      public void setDatasourceName(String datasourceName)
      {
          testImmutability("datasourceName");
          this.datasourceName = datasourceName;
      }
  
      public String getDeleteAllSql()
      {
          return deleteAllSql;
      }
  
      public void setDeleteAllSql(String deleteAllSql)
      {
          testImmutability("deleteAllSql");
          this.deleteAllSql = deleteAllSql;
      }
  
      public String getDeleteNodeSql()
      {
          return deleteNodeSql;
      }
  
      public void setDeleteNodeSql(String deleteNodeSql)
      {
          testImmutability("deleteNodeSql");
          this.deleteNodeSql = deleteNodeSql;
      }
  
      public String getDriverClass()
      {
          return driverClass;
      }
  
      public void setDriverClass(String driverClass)
      {
          testImmutability("driverClass");
          this.driverClass = driverClass;
      }
  
      public boolean getDropTable()
      {
          return dropTable;
      }
  
      public void setDropTable(boolean dropTable)
      {
          testImmutability("dropTable");
          this.dropTable = dropTable;
      }
  
      public String getInsertNodeSql()
      {
          return insertNodeSql;
      }
  
      public void setInsertNodeSql(String insertNodeSql)
      {
          testImmutability("insertNodeSql");
          this.insertNodeSql = insertNodeSql;
      }
  
      public String getSelectChildFqnsSql()
      {
          return selectChildFqnsSql;
      }
  
      public void setSelectChildFqnsSql(String selectChildFqnsSql)
      {
          testImmutability("selectChildFqnsSql");
          this.selectChildFqnsSql = selectChildFqnsSql;
      }
  
      public String getSelectNodeSql()
      {
          return selectNodeSql;
      }
  
      public void setSelectNodeSql(String selectNodeSql)
      {
          testImmutability("selectNodeSql");
          this.selectNodeSql = selectNodeSql;
      }
  
      public String getTable()
      {
          return table;
      }
  
      public void setTable(String table)
      {
          testImmutability("table");
          this.table = table;
      }
  
      public String getUpdateTableSql()
      {
          return updateTableSql;
      }
  
      public void setUpdateTableSql(String updateTableSql)
      {
          testImmutability("updateTableSql");
          this.updateTableSql = updateTableSql;
      }
  
      public String getDropTableDDL()
      {
          return dropTableDDL;
      }
  
      public void setDropTableDDL(String dropTableDDL)
      {
          testImmutability("dropTableDDL");
          this.dropTableDDL = dropTableDDL;
      }
  
      public String getSelectChildNamesSql()
      {
          return selectChildNamesSql;
      }
  
      public void setSelectChildNamesSql(String selectChildNamesSql)
      {
          testImmutability("selectChildNamesSql");
          this.selectChildNamesSql = selectChildNamesSql;
      }
  
      public String getUpdateNodeSql()
      {
          return updateNodeSql;
      }
  
      public void setUpdateNodeSql(String updateNodeSql)
      {
          testImmutability("updateNodeSql");
          this.updateNodeSql = updateNodeSql;
      }
  
      public String getJdbcPassword()
      {
          return jdbcPassword;
      }
  
      public void setJdbcPassword(String jdbcPassword)
      {
          testImmutability("jdbcPassword");
          this.jdbcPassword = jdbcPassword;
      }
  
      public String getJdbcURL()
      {
          return jdbcURL;
      }
  
      public void setJdbcURL(String jdbcURL)
      {
          testImmutability("jdbcURL");
          this.jdbcURL = jdbcURL;
      }
  
      public String getJdbcUser()
      {
          return jdbcUser;
      }
  
      public void setJdbcUser(String jdbcUser)
      {
          testImmutability("jdbcUser");
          this.jdbcUser = jdbcUser;
      }
  
      public String getConnectionFactoryClass()
      {
          return connectionFactoryClass;
      }
  
      public void setConnectionFactoryClass(String connectionFactoryClass)
      {
          testImmutability("connectionFactoryClass");
          this.connectionFactoryClass = connectionFactoryClass;
      }
  
      public void setProperties(Properties props)
      {
          super.setProperties(props);
          datasourceName = props.getProperty("cache.jdbc.datasource");
          if (datasourceName == null)
          {
              this.driverClass = AdjListJDBCCacheLoader.getRequiredProperty(props, "cache.jdbc.driver");
              this.jdbcURL = AdjListJDBCCacheLoader.getRequiredProperty(props, "cache.jdbc.url");
              this.jdbcUser = AdjListJDBCCacheLoader.getRequiredProperty(props, "cache.jdbc.user");
              this.jdbcPassword = AdjListJDBCCacheLoader.getRequiredProperty(props, "cache.jdbc.password");
  
              if (log.isDebugEnabled())
              {
                  log.debug("Properties: " +
                          "cache.jdbc.url=" +
                          jdbcURL +
                          ", cache.jdbc.driver=" +
                          driverClass +
                          ", cache.jdbc.user=" +
                          jdbcUser +
                          ", cache.jdbc.password=" +
                          jdbcPassword +
                          ", cache.jdbc.table=" + table);
              }
          }
  
          String prop = props.getProperty("cache.jdbc.table.create");
          this.createTable = (prop == null || Boolean.valueOf(prop));
          prop = props.getProperty("cache.jdbc.table.drop");
          this.dropTable = (prop == null || Boolean.valueOf(prop));
  
          this.table = props.getProperty("cache.jdbc.table.name", "jbosscache");
          String primaryKey = props.getProperty("cache.jdbc.table.primarykey", "jbosscache_pk");
          fqnColumn = props.getProperty("cache.jdbc.fqn.column", "fqn");
          String fqnType = props.getProperty("cache.jdbc.fqn.type", "varchar(255)");
          nodeColumn = props.getProperty("cache.jdbc.node.column", "node");
          String nodeType = props.getProperty("cache.jdbc.node.type", "blob");
          String parentColumn = props.getProperty("cache.jdbc.parent.column", "parent");
  
          selectChildNamesSql = "select " + fqnColumn + " from " + table + " where " + parentColumn + "=?";
          deleteNodeSql = "delete from " + table + " where " + fqnColumn + "=?";
          deleteAllSql = "delete from " + table;
          selectChildFqnsSql = "select " + fqnColumn + " from " + table + " where " + parentColumn + "=?";
          insertNodeSql = "insert into " +
                  table +
                  " (" +
                  fqnColumn +
                  ", " +
                  nodeColumn +
                  ", " +
                  parentColumn +
                  ") values (?, ?, ?)";
          updateNodeSql = "update " + table + " set " + nodeColumn + "=? where " + fqnColumn + "=?";
          selectNodeSql = "select " + nodeColumn + " from " + table + " where " + fqnColumn + "=?";
  
          createTableDDL = "create table " +
                  table +
                  "(" +
                  fqnColumn +
                  " " +
                  fqnType +
                  " not null, " +
                  nodeColumn +
                  " " +
                  nodeType +
                  ", " +
                  parentColumn +
                  " " +
                  fqnType +
                  ", constraint " + primaryKey + " primary key (" + fqnColumn + "))";
  
          dropTableDDL = "drop table " + table;
          connectionFactoryClass = props.getProperty("cache.jdbc.connection.factory", "org.jboss.cache.loader.NonManagedConnectionFactory");
      }
  
      public boolean equals(Object obj)
      {
          if (obj instanceof AdjListJDBCCacheLoaderConfig && equalsExcludingProperties(obj))
          {
              AdjListJDBCCacheLoaderConfig other = (AdjListJDBCCacheLoaderConfig) obj;
  
              return (this.createTable == other.createTable)
                      && safeEquals(createTableDDL, other.createTableDDL)
                      && safeEquals(datasourceName, other.datasourceName)
                      && safeEquals(deleteAllSql, other.deleteAllSql)
                      && safeEquals(deleteNodeSql, other.deleteNodeSql)
                      && safeEquals(driverClass, other.driverClass)
                      && (dropTable == other.dropTable)
                      && safeEquals(dropTableDDL, other.dropTableDDL)
                      && safeEquals(insertNodeSql, other.insertNodeSql)
                      && safeEquals(jdbcPassword, other.jdbcPassword)
                      && safeEquals(jdbcURL, other.jdbcURL)
                      && safeEquals(jdbcUser, other.jdbcUser)
                      && safeEquals(selectChildFqnsSql, other.selectChildFqnsSql)
                      && safeEquals(selectChildNamesSql, other.selectChildNamesSql)
                      && safeEquals(selectNodeSql, other.selectNodeSql)
                      && safeEquals(table, other.table)
                      && safeEquals(updateNodeSql, other.updateNodeSql)
                      && safeEquals(updateTableSql, other.updateTableSql)
                      && safeEquals(connectionFactoryClass, other.connectionFactoryClass);
          }
  
          return false;
      }
  
      public int hashCode()
      {
          int result = hashCodeExcludingProperties();
          result = 31 * result + (createTable ? 0 : 1);
          result = 31 * result + (createTableDDL == null ? 0 : createTableDDL.hashCode());
          result = 31 * result + (datasourceName == null ? 0 : datasourceName.hashCode());
          result = 31 * result + (deleteAllSql == null ? 0 : deleteAllSql.hashCode());
          result = 31 * result + (deleteNodeSql == null ? 0 : deleteNodeSql.hashCode());
          result = 31 * result + (driverClass == null ? 0 : driverClass.hashCode());
          result = 31 * result + (dropTable ? 0 : 1);
          result = 31 * result + (dropTableDDL == null ? 0 : dropTableDDL.hashCode());
          result = 31 * result + (insertNodeSql == null ? 0 : insertNodeSql.hashCode());
          result = 31 * result + (jdbcPassword == null ? 0 : jdbcPassword.hashCode());
          result = 31 * result + (jdbcUser == null ? 0 : jdbcUser.hashCode());
          result = 31 * result + (jdbcURL == null ? 0 : jdbcURL.hashCode());
          result = 31 * result + (selectChildFqnsSql == null ? 0 : selectChildFqnsSql.hashCode());
          result = 31 * result + (selectChildNamesSql == null ? 0 : selectChildNamesSql.hashCode());
          result = 31 * result + (selectNodeSql == null ? 0 : selectNodeSql.hashCode());
          result = 31 * result + (table == null ? 0 : table.hashCode());
          result = 31 * result + (updateNodeSql == null ? 0 : updateNodeSql.hashCode());
          result = 31 * result + (updateTableSql == null ? 0 : updateTableSql.hashCode());
          result = 31 * result + (connectionFactoryClass == null ? 0 : connectionFactoryClass.hashCode());
  
          return result;
      }
  
  }
  
  



More information about the jboss-cvs-commits mailing list