You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@stanbol.apache.org by su...@apache.org on 2012/09/17 10:01:45 UTC

svn commit: r1386499 - in /incubator/stanbol/branches/contenthub-two-layered-structure: commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/ contenthub/revisionmanager/src/main/java/org/apache/...

Author: suat
Date: Mon Sep 17 08:01:45 2012
New Revision: 1386499

URL: http://svn.apache.org/viewvc?rev=1386499&view=rev
Log:
STANBOL-498: Moved the database access logic into the DerbyDBManager class. So, DerbyRevisionManager has become just a client of the DerbyDBManager.

Added:
    incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionBean.java
Modified:
    incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManager.java
    incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManagerException.java
    incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyDBManager.java
    incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyRevisionManager.java

Added: incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionBean.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionBean.java?rev=1386499&view=auto
==============================================================================
--- incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionBean.java (added)
+++ incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionBean.java Mon Sep 17 08:01:45 2012
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.stanbol.commons.semanticindex.store.revisionmanager;
+
+/**
+ * A tiny bean holding the changes obtained from a {@link RevisionManager}. This it keeps the uri of the
+ * changed item and corresponding new revision.
+ * 
+ * @author suat
+ * 
+ */
+public class RevisionBean {
+    private String id;
+
+    private long revision;
+
+    public RevisionBean(String id, long revision) {
+        this.id = id;
+        this.revision = revision;
+    }
+
+    public String getID() {
+        return this.id;
+    }
+
+    public long getRevision() {
+        return this.revision;
+    }
+}

Modified: incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManager.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManager.java?rev=1386499&r1=1386498&r2=1386499&view=diff
==============================================================================
--- incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManager.java (original)
+++ incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManager.java Mon Sep 17 08:01:45 2012
@@ -1,5 +1,23 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.stanbol.commons.semanticindex.store.revisionmanager;
 
+import java.util.List;
+
 import org.apache.stanbol.commons.semanticindex.store.ChangeSet;
 import org.apache.stanbol.commons.semanticindex.store.Store;
 
@@ -36,9 +54,22 @@ public interface RevisionManager {
      * @throws RevisionManagerException
      */
     void unregisterStore(String storeID) throws RevisionManagerException;
+    
+    /**
+     * Creates revisions for the items, represented by the identifiers given in the {@code itemIDs} parameter,
+     * which are managed by the give {@link Store}. This method is should be called when iniatializing the
+     * revisions of all of the items in the Store e.g after the an epoch change.
+     * 
+     * @param storeID
+     *            the identifier of the keeper {@link Store} instance for the given items
+     * @param itemIDs
+     *            identifiers of the items of which revisions will be created.
+     * @throws RevisionManagerException
+     */
+    void registerRevisions(String storeID, List<String> itemIDs) throws RevisionManagerException;
 
     /**
-     * Updates the revision of the item represented by {@code itemID} which is managed by the given
+     * Updates the revision of the item, represented by {@code itemID}, which is managed by the given
      * {@link Store}. If there does not exist a revision for the given item a new is created.
      * 
      * @param storeID

Modified: incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManagerException.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManagerException.java?rev=1386499&r1=1386498&r2=1386499&view=diff
==============================================================================
--- incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManagerException.java (original)
+++ incubator/stanbol/branches/contenthub-two-layered-structure/commons/semanticindex/servicesapi/src/main/java/org/apache/stanbol/commons/semanticindex/store/revisionmanager/RevisionManagerException.java Mon Sep 17 08:01:45 2012
@@ -1,7 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.stanbol.commons.semanticindex.store.revisionmanager;
 
 import org.apache.stanbol.commons.semanticindex.store.StoreException;
 
+/**
+ * Exception to be thrown when an unexpected situation occurs during revision management
+ * 
+ */
 public class RevisionManagerException extends StoreException {
 
     private static final long serialVersionUID = -3536940194241661109L;

Modified: incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyDBManager.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyDBManager.java?rev=1386499&r1=1386498&r2=1386499&view=diff
==============================================================================
--- incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyDBManager.java (original)
+++ incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyDBManager.java Mon Sep 17 08:01:45 2012
@@ -20,15 +20,19 @@ import java.net.ConnectException;
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.DriverManager;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
 
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Service;
 import org.apache.stanbol.commons.semanticindex.store.Store;
-import org.apache.stanbol.commons.semanticindex.store.StoreException;
+import org.apache.stanbol.commons.semanticindex.store.revisionmanager.RevisionBean;
+import org.apache.stanbol.commons.semanticindex.store.revisionmanager.RevisionManagerException;
 import org.osgi.service.component.ComponentContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -50,16 +54,36 @@ import org.slf4j.LoggerFactory;
 @Service(value = DerbyDBManager.class)
 public class DerbyDBManager {
 
-    public static final String EPOCH_TABLE_NAME = "epochTable";
+    private static final int INSERT_BATCH_SIZE = 1000;
 
-    private static Logger log = LoggerFactory.getLogger(DerbyDBManager.class);
+    public static final String EPOCH_TABLE_NAME = "epochTable";
 
     private static int MAX_ID_LENGTH = 1024;
 
+    // private String SELECT_CHANGES =
+    // "SELECT id, revision FROM \"%s\" WHERE revision > ? ORDER BY revision ASC";
+    private String SELECT_CHANGES = "SELECT id, revision FROM \"%s\" WHERE revision > ? AND revision <= ? ORDER BY revision ASC OFFSET ? ROWS";
+
+    private String SELECT_REVISION = "SELECT id,revision FROM \"%s\" content_item_revision WHERE id = ?";
+
+    private String INSERT_REVISION = "INSERT INTO \"%s\" (id, revision) VALUES (?,?)";
+
+    private String UPDATE_REVISION = "UPDATE \"%s\" SET revision=? WHERE id=?";
+
+    private String SELECT_EPOCH = "SELECT epoch FROM " + EPOCH_TABLE_NAME + " WHERE tableName = ?";
+
+    private String INSERT_EPOCH = "INSERT INTO " + DerbyDBManager.EPOCH_TABLE_NAME
+                                  + " (epoch, tableName) values (?, ?)";
+
+    private String UPDATE_EPOCH = "UPDATE " + DerbyDBManager.EPOCH_TABLE_NAME
+                                  + " SET epoch = ? WHERE tableName = ?";
+
+    private static Logger log = LoggerFactory.getLogger(DerbyDBManager.class);
+
     private static String DB_URL;
 
     @Activate
-    protected void activate(ComponentContext componentContext) throws StoreException {
+    protected void activate(ComponentContext componentContext) throws RevisionManagerException {
         System.setProperty("derby.language.statementCacheSize", "0");
         String stanbolHome = componentContext.getBundleContext().getProperty("sling.home");
         DB_URL = "jdbc:derby:" + stanbolHome + "/contenthub/store/revisions;create=true";
@@ -67,41 +91,47 @@ public class DerbyDBManager {
         createEpochTable();
     }
 
+    /*
+     * Table scoped methods
+     */
+
     /**
      * Creates an empty revision table with the given name. Different {@link Store} implementations are
      * expected to call this method in their initializations with the value to be obtained by
-     * {@link DerbyRevisionManager#getStoreID(Store)} method.
+     * {@link DerbyRevisionManager#getStoreID(Store)} method. If there is already a revision table for this
+     * name, nothing is done.
      * 
      * @param tableName
      *            name of the table to be created
-     * @throws StoreException
+     * @throws RevisionManagerException
      */
-    public void createRevisionTable(String tableName) throws StoreException {
-        Connection con = getConnection();
+    public void createRevisionTable(String tableName) throws RevisionManagerException {
+        Connection con = null;
         Statement stmt = null;
         try {
             // try to create revision table
             if (!existsTable(tableName)) {
+                con = getConnection();
                 String createRevisionTable = "CREATE TABLE \"" + tableName + "\" (id VARCHAR("
                                              + MAX_ID_LENGTH + ") NOT NULL PRIMARY KEY,"
                                              + "revision BIGINT NOT NULL)";
                 stmt = con.createStatement();
                 stmt.executeUpdate(createRevisionTable);
-                log.info("Revision table created for {}.", tableName);
+                log.info("Revision table: {} has beem created.", tableName);
             } else {
                 log.info("Revision table already exists for {}", tableName);
             }
 
         } catch (SQLException e) {
             log.error(String.format("Failed to create table %s", tableName), e);
-            throw new StoreException(String.format("Failed to create table %s", tableName), e);
+            throw new RevisionManagerException(String.format("Failed to create table %s", tableName), e);
         } finally {
             closeStatement(stmt);
             closeConnection(con);
         }
     }
 
-    private void createEpochTable() throws StoreException {
+    private void createEpochTable() throws RevisionManagerException {
         Connection con = getConnection();
         Statement stmt = null;
         try {
@@ -119,7 +149,8 @@ public class DerbyDBManager {
 
         } catch (SQLException e) {
             log.error(String.format("Failed to create table %s", EPOCH_TABLE_NAME), e);
-            throw new StoreException(String.format("Failed to create table %s", EPOCH_TABLE_NAME), e);
+            throw new RevisionManagerException(String.format("Failed to create table %s", EPOCH_TABLE_NAME),
+                    e);
         } finally {
             closeStatement(stmt);
             closeConnection(con);
@@ -132,9 +163,9 @@ public class DerbyDBManager {
      * @param tableName
      *            name of the table to be checked
      * @return <code>true</code> if the table already exists, otherwise <code>false</code>.
-     * @throws StoreException
+     * @throws RevisionManagerException
      */
-    public boolean existsTable(String tableName) throws StoreException {
+    public boolean existsTable(String tableName) throws RevisionManagerException {
         boolean exists = false;
         ResultSet rs = null;
         Connection con = null;
@@ -150,8 +181,8 @@ public class DerbyDBManager {
             }
         } catch (SQLException e) {
             log.error("Failed to check existence of the table: {}", tableName);
-            throw new StoreException(String.format("Failed to check existence of the table: %s", tableName),
-                    e);
+            throw new RevisionManagerException(String.format("Failed to check existence of the table: %s",
+                tableName), e);
         } finally {
             closeResultSet(rs);
             closeConnection(con);
@@ -160,13 +191,36 @@ public class DerbyDBManager {
     }
 
     /**
+     * Drops the table specified with the {@code tableName}
+     * 
+     * @param tableName
+     *            name of the table to be dropped
+     * @throws RevisionManagerException
+     */
+    public void removeTable(String tableName) throws RevisionManagerException {
+        Connection con = getConnection();
+        Statement stmt = null;
+        try {
+            stmt = con.createStatement();
+            stmt.executeUpdate("DROP TABLE \"" + tableName + "\"");
+            log.info("The revision table having name: {} has been dropped", tableName);
+        } catch (SQLException e) {
+            log.error("Failed to drop the table: {}", tableName);
+            throw new RevisionManagerException(String.format("Failed to drop the table: %s", tableName), e);
+        } finally {
+            closeStatement(stmt);
+            closeConnection(con);
+        }
+    }
+
+    /**
      * Truncates the content of the table specified with the {@code tableName}
      * 
      * @param tableName
      *            name of the table to be truncated
-     * @throws StoreException
+     * @throws RevisionManagerException
      */
-    public void truncateTable(String tableName) throws StoreException {
+    public void truncateTable(String tableName) throws RevisionManagerException {
         boolean exists = existsTable(tableName);
         if (!exists) {
             throw new IllegalArgumentException(String.format("There is no table having name: %s", tableName));
@@ -177,10 +231,44 @@ public class DerbyDBManager {
         try {
             stmt = con.createStatement();
             stmt.execute(truncateTable);
-            log.debug("Table having name: {} has been truncated", tableName);
+            log.info("Table having name: {} has been truncated", tableName);
         } catch (SQLException e) {
             log.error("Failed to truncate table: {}", tableName, e);
-            throw new StoreException(String.format("Failed to truncate table: %s", tableName), e);
+            throw new RevisionManagerException(String.format("Failed to truncate table: %s", tableName), e);
+        } finally {
+            closeStatement(stmt);
+            closeConnection(con);
+        }
+    }
+
+    /*
+     * Index scoped methods
+     */
+
+    /**
+     * Creates an index over the <b>revision</b> fields of the revision tables created via the
+     * {@link #createRevisionTable(String)} method.
+     * 
+     * @param indexName
+     *            name of the index to be created
+     * @param tableName
+     *            name of the table on which the index will be created
+     * @throws RevisionManagerException
+     */
+    public void createRevisionIndex(String indexName, String tableName) throws RevisionManagerException {
+        Connection con = getConnection();
+        Statement stmt = null;
+
+        String createIndex = "CREATE INDEX \"" + indexName + "\" ON \"" + tableName + "\" (revision)";
+        try {
+            stmt = con.createStatement();
+            stmt.executeUpdate(createIndex);
+            log.info("Revision index has been created for the revision table: {}.", tableName);
+        } catch (SQLException e) {
+            log.error(
+                String.format("Failed to create the index: %s for the table: %s", indexName, tableName), e);
+            throw new RevisionManagerException(String.format(
+                "Failed to create the index: %s for the table: %s", indexName, tableName), e);
         } finally {
             closeStatement(stmt);
             closeConnection(con);
@@ -188,6 +276,382 @@ public class DerbyDBManager {
     }
 
     /**
+     * Drops the index specified with the {@code indexName}
+     * 
+     * @param indexName
+     *            name of the index to be dropped
+     * @throws RevisionManagerException
+     */
+    public void removeIndex(String indexName) throws RevisionManagerException {
+        Connection con = getConnection();
+        Statement stmt = null;
+        try {
+            stmt = con.createStatement();
+            stmt.executeUpdate("DROP INDEX \"" + indexName + "\"");
+            log.info("The index: {} has been dropped", indexName);
+        } catch (SQLException e) {
+            log.error("Failed to drop the index: {}", indexName);
+            throw new RevisionManagerException(String.format("Failed to drop the index: %s", indexName), e);
+        } finally {
+            closeStatement(stmt);
+            closeConnection(con);
+        }
+    }
+
+    /*
+     * Epoch entry modification methods
+     */
+
+    /**
+     * Returns the epoch value for the given {@link Store}
+     * 
+     * @param storeID
+     *            identifier of the Store of which epoch value will be returned
+     * @return the epoch value for the given store if there exists such a value
+     * @throws RevisionManagerException
+     */
+    public long getEpoch(String storeID) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        ResultSet rs = null;
+        long epoch;
+        try {
+            ps = con.prepareStatement(SELECT_EPOCH);
+            ps.setString(1, storeID);
+            rs = ps.executeQuery();
+
+            if (rs.next()) {
+                epoch = rs.getLong(1);
+            } else {
+                log.error(String.format("There is not an epoch record for the Store: %s", storeID));
+                throw new RevisionManagerException(String.format(
+                    "There is not an epoch record for the Store: %s", storeID));
+            }
+            log.info("The epoch for the Store: %s has been fetched as %s", storeID, epoch);
+
+        } catch (SQLException e) {
+            log.error("Failed to get epoch of the Store: {}", storeID, e);
+            throw new RevisionManagerException(
+                    String.format("Failed to get epoch of the Store: %s", storeID), e);
+        } finally {
+            closeResultSet(rs);
+            closeStatement(ps);
+            closeConnection(con);
+        }
+        return epoch;
+    }
+
+    /**
+     * Creates a new epoch entry for the given {@link Store}
+     * 
+     * @param storeID
+     *            identifier of the {@link Store} for which a new epoch entry will be created
+     * @param epoch
+     *            value of the epoch
+     * @throws RevisionManagerException
+     */
+    public void createEpochEntry(String storeID, long epoch) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        try {
+            ps = con.prepareStatement(INSERT_EPOCH);
+            ps.setLong(1, epoch);
+            ps.setString(2, storeID);
+            ps.executeUpdate();
+            log.info("New epoch: {} has been created for the Store: {}", epoch, storeID);
+        } catch (SQLException e) {
+            log.error("Failed to create new epoch entry for the Store: {}", storeID, e);
+            throw new RevisionManagerException(String.format(
+                "Failed to create new epoch entry for the Store: %s", storeID), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Updates the existing epoch entry for the given {@link Store}
+     * 
+     * @param storeID
+     *            identifier of the Store of which epoch will be updated
+     * @param epoch
+     *            new epoch value
+     * @throws RevisionManagerException
+     */
+    public void updateEpochEntry(String storeID, long epoch) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        try {
+            ps = con.prepareStatement(UPDATE_EPOCH);
+            ps.setLong(1, epoch);
+            ps.setString(2, storeID);
+            ps.executeUpdate();
+            log.info("New epoch: {} has been inserted for the Store: {}", epoch, storeID);
+        } catch (SQLException e) {
+            log.error("Failed to create new epoch entry for the Store: {}", storeID, e);
+            throw new RevisionManagerException(String.format(
+                "Failed to create new epoch entry for the Store: %s", storeID), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Removes the epoch entry regarding the given {@link Store}
+     * 
+     * @param storeID
+     *            identifier of the Store of which epoch record will be deleted
+     * @throws RevisionManagerException
+     */
+    public void removeEpochEntry(String storeID) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+
+        try {
+            ps = con.prepareStatement("DELETE FROM " + EPOCH_TABLE_NAME + " WHERE tableName = ?");
+            ps.setString(1, storeID);
+            ps.executeUpdate();
+            log.info("The epoch entry for the the Store: {} has been deleted", storeID);
+        } catch (SQLException e) {
+            log.error("Failed to remove the epoch entry for the store: {}", storeID, e);
+            throw new RevisionManagerException(String.format(
+                "Failed to remove the epoch entry for the store: {}", storeID), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /*
+     * Revision entry modification methods
+     */
+
+    /**
+     * Obtains changes which are larger than the given {@code revision} from the specified table
+     * 
+     * @param tableName
+     *            name of the table from which the revisions will be obtained
+     * @param revision
+     *            results will be larger than the value specified in this parameter
+     * @param upperRevision
+     *            results will be smaller than or equal to the value specified in this parameter
+     * @param limit
+     *            maximum number changes to be returned
+     * @param offset
+     *            starting point of entries to be obtained from the database
+     * @return {@link List} of {@link RevisionBean}s. RevisionBeans contain the id representing the item and
+     *         the changed revision
+     * @throws RevisionManagerException
+     */
+    public List<RevisionBean> getRevisions(String tableName,
+                                           long revision,
+                                           long upperRevision,
+                                           int limit,
+                                           int offset) throws RevisionManagerException {
+        List<RevisionBean> results = new ArrayList<RevisionBean>();
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        ResultSet rs = null;
+        try {
+            ps = con.prepareStatement(String.format(SELECT_CHANGES, tableName),
+                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+            ps.setLong(1, revision);
+            ps.setLong(2, upperRevision);
+            ps.setInt(3, offset);
+            ps.setMaxRows(limit);
+            rs = ps.executeQuery();
+            while (rs.next()) {
+                results.add(new RevisionBean(rs.getString("id"), rs.getLong("revision")));
+            }
+            return results;
+        } catch (SQLException e) {
+            log.error("Failed to get changes from the table: {}", tableName, e);
+            throw new RevisionManagerException(String.format("Failed to get changes from the table: %s",
+                tableName), e);
+        } finally {
+            closeResultSet(rs);
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Checks a revision entry exists for the given item and table
+     * 
+     * @param tableName
+     *            name of the table on which the check will be done
+     * @param itemID
+     *            identifier of the item to be checked
+     * @return {@code true} if a record exists, otherwise {@code false}
+     * @throws RevisionManagerException
+     */
+    public boolean existsRevisionEntry(String tableName, String itemID) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        ResultSet rs = null;
+        boolean recordExist = false;
+        try {
+            ps = con.prepareStatement(String.format(SELECT_REVISION, tableName));
+            ps.setString(1, itemID);
+            rs = ps.executeQuery();
+            if (rs.next()) {
+                recordExist = true;
+            }
+            log.info(String
+                    .format(
+                        "Checked the existence of revision entry for the table: %s and for the item: %s with the result: %b",
+                        new Object[] {tableName, itemID, recordExist}));
+            return recordExist;
+        } catch (SQLException e) {
+            log.error(String.format(
+                "Failed to check existence of revision entry for the table: %s and item: %s", tableName,
+                itemID), e);
+            throw new RevisionManagerException(String.format(
+                "Failed to check existence of revision entry for the table: %s and item: %s", tableName,
+                itemID), e);
+        } finally {
+            closeResultSet(rs);
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Inserts a new revision entry for the item in the specified table
+     * 
+     * @param tableName
+     *            name of the table in which the revision entry for the given item will be created
+     * @param itemID
+     *            identifier of the item for which a revision entry will be created
+     * @param revision
+     *            revision value
+     * @throws RevisionManagerException
+     */
+    public void createRevisionEntry(String tableName, String itemID, long revision) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        try {
+            ps = con.prepareStatement(String.format(INSERT_REVISION, tableName));
+            ps.setString(1, itemID);
+            ps.setLong(2, revision);
+            ps.executeUpdate();
+            log.info("Revision of the item: %s in table: %s has been inserted as %d",
+                new Object[] {itemID, tableName, revision});
+        } catch (SQLException e) {
+            log.error(
+                String.format("Failed to insert revision for the table: %s and item: %s", tableName, itemID),
+                e);
+            throw new RevisionManagerException(String.format(
+                "Failed to insert revision for the table: %s and item: %s", tableName, itemID), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Updates the existing revision of an item with the new revision
+     * 
+     * @param tableName
+     *            name of the table keeping the revision entry for the given item
+     * @param itemID
+     *            identifier of the item of which revision will be updated
+     * @param revision
+     *            new revision value
+     * @throws RevisionManagerException
+     */
+    public void updateRevisionEntry(String tableName, String itemID, long revision) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        try {
+            ps = con.prepareStatement(String.format(UPDATE_REVISION, tableName));
+            ps.setString(1, itemID);
+            ps.setLong(2, revision);
+            ps.executeUpdate();
+            log.info("Revision of the item: %s in table: %s has been updated as %d", new Object[] {itemID,
+                                                                                                   tableName,
+                                                                                                   revision});
+        } catch (SQLException e) {
+            log.error(
+                String.format("Failed to update revision for the table: %s and item: %s", tableName, itemID),
+                e);
+            throw new RevisionManagerException(String.format(
+                "Failed to update revision for the table: %s and item: %s", tableName, itemID), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
+     * Creates new revision entries for the given items in the specified table. Revision numbers start from
+     * the {@link Long#MIN_VALUE} and it is incremented 1 by 1. A new revision number is given to each item.
+     * To create revision entries in an efficient way, {@link PreparedStatement}s are prepared so that
+     * {@value #INSERT_BATCH_SIZE} entries are created in a single query execution.
+     * 
+     * @param tableName
+     *            name of the table in which the revision entries will be created
+     * @param itemIDs
+     *            identifiers of the items for which revision entries will be created
+     * @throws RevisionManagerException
+     */
+    public void createRevisionEntries(String tableName, List<String> itemIDs) throws RevisionManagerException {
+        Connection con = getConnection();
+        PreparedStatement ps = null;
+        long start = System.currentTimeMillis();
+        String query = "INSERT INTO \"" + tableName + "\" (id, revision) VALUES";
+        StringBuilder sb = new StringBuilder(query);
+        try {
+            long revision = Long.MIN_VALUE;
+            int i;
+            for (i = 0; i < itemIDs.size(); i++) {
+                sb.append("(?,?),");
+                if ((i + 1) % INSERT_BATCH_SIZE == 0) {
+                    sb.setCharAt(sb.length() - 1, ' ');
+                    if (ps == null) {
+                        ps = con.prepareStatement(sb.toString());
+                    }
+                    for (int j = i - (INSERT_BATCH_SIZE - 1), l = 1; j <= i; j++, l += 2) {
+                        ps.setString(l, itemIDs.get(j));
+                        ps.setLong(l + 1, revision++);
+                    }
+                    ps.executeUpdate();
+                    ps.clearParameters();
+                    log.info("{} item have been inserted in {}ms", (i + 1),
+                        (System.currentTimeMillis() - start));
+                    sb = null;
+                    sb = new StringBuilder(query);
+                }
+            }
+
+            if (ps != null) {
+                ps.close();
+            }
+
+            sb.setCharAt(sb.length() - 1, ' ');
+            ps = con.prepareStatement(sb.toString());
+            for (int j = i - itemIDs.size() % INSERT_BATCH_SIZE, l = 1; j < i; j++, l += 2) {
+                ps.setString(l, itemIDs.get(j));
+                ps.setLong(l + 1, revision++);
+            }
+            ps.executeUpdate();
+
+            long finish = System.currentTimeMillis();
+            log.info("Revisions have been created in {}ms in {} number of entities", (finish - start),
+                itemIDs.size());
+
+        } catch (SQLException e) {
+            log.error("Failed to create revision entries in the table: {}", tableName);
+            throw new RevisionManagerException(String.format(
+                "Failed to create revision entries in the table: {}", tableName), e);
+        } finally {
+            closeStatement(ps);
+            closeConnection(con);
+        }
+    }
+
+    /**
      * Closes the given {@link Connection}
      * 
      * @param con
@@ -236,16 +700,16 @@ public class DerbyDBManager {
      * Creates a {@link ConnectException}
      * 
      * @return the {@link Connection} if successfully established
-     * @throws StoreException
+     * @throws RevisionManagerException
      */
-    public Connection getConnection() throws StoreException {
+    public Connection getConnection() throws RevisionManagerException {
         Connection con = null;
         try {
             con = DriverManager.getConnection(DB_URL);
             log.debug("New database connection has been prepared");
         } catch (SQLException e) {
             log.error("Failed to obtain Derby connection", e);
-            throw new StoreException("Failed to obtain Derby connection", e);
+            throw new RevisionManagerException("Failed to obtain Derby connection", e);
         }
         return con;
     }

Modified: incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyRevisionManager.java
URL: http://svn.apache.org/viewvc/incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyRevisionManager.java?rev=1386499&r1=1386498&r2=1386499&view=diff
==============================================================================
--- incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyRevisionManager.java (original)
+++ incubator/stanbol/branches/contenthub-two-layered-structure/contenthub/revisionmanager/src/main/java/org/apache/stanbol/contenthub/revisionmanager/DerbyRevisionManager.java Mon Sep 17 08:01:45 2012
@@ -17,12 +17,9 @@
 package org.apache.stanbol.contenthub.revisionmanager;
 
 import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.LinkedHashSet;
+import java.util.List;
 import java.util.Set;
 
 import org.apache.felix.scr.annotations.Component;
@@ -32,6 +29,7 @@ import org.apache.stanbol.commons.semant
 import org.apache.stanbol.commons.semanticindex.store.ChangeSet;
 import org.apache.stanbol.commons.semanticindex.store.Store;
 import org.apache.stanbol.commons.semanticindex.store.StoreException;
+import org.apache.stanbol.commons.semanticindex.store.revisionmanager.RevisionBean;
 import org.apache.stanbol.commons.semanticindex.store.revisionmanager.RevisionManager;
 import org.apache.stanbol.commons.semanticindex.store.revisionmanager.RevisionManagerException;
 import org.slf4j.Logger;
@@ -61,25 +59,6 @@ import org.slf4j.LoggerFactory;
 public class DerbyRevisionManager implements RevisionManager {
     private static Logger log = LoggerFactory.getLogger(DerbyRevisionManager.class);
 
-    private String SELECT_REVISION = "SELECT id,revision FROM \"%s\" content_item_revision WHERE id = ?";
-
-    private String INSERT_REVISION = "INSERT INTO \"%s\" (id, revision) VALUES (?,?)";
-
-    private String UPDATE_REVISION = "UPDATE \"%s\" SET revision=? WHERE id=?";
-
-    private String SELECT_CHANGES = "SELECT id, revision FROM \"%s\" WHERE revision > ? ORDER BY revision ASC";
-
-    private String SELECT_MORECHANGES = "SELECT id, revision FROM \"%s\" WHERE revision > ? AND revision <= ? ORDER BY revision ASC OFFSET ? ROWS";
-
-    private String SELECT_EPOCH = "SELECT epoch FROM " + DerbyDBManager.EPOCH_TABLE_NAME
-                                  + " WHERE tableName = ?";
-
-    private String INSERT_EPOCH = "INSERT INTO " + DerbyDBManager.EPOCH_TABLE_NAME
-                                  + " (epoch, tableName) values (?, ?)";
-
-    private String UPDATE_EPOCH = "UPDATE " + DerbyDBManager.EPOCH_TABLE_NAME
-                                  + " SET epoch = ? WHERE tableName = ?";
-
     @Reference
     DerbyDBManager dbManager;
 
@@ -96,114 +75,53 @@ public class DerbyRevisionManager implem
     @Override
     public void registerStore(String storeID) throws RevisionManagerException {
         // initialize tables if not already
-        try {
-            dbManager.createRevisionTable(storeID);
-            log.debug("Revision table initialized for the Store: {}", storeID);
-        } catch (StoreException e) {
-            log.error("Failed to create revision table for the store: {}", storeID);
-            throw new RevisionManagerException(String.format(
-                "Failed to create revision table for the store: %s", storeID), e);
-        }
+        dbManager.createRevisionTable(storeID);
 
         // add initial epoch for the store
         updateEpoch(storeID, true);
-        log.debug("Epoch is initialized for the Store: {}", storeID);
+
+        log.info("The Store: {} has been registered", storeID);
     }
 
     /**
-     * Removes the revision table and the epoch entry regarding the given {@link Store}
+     * Removes the revision table and associated index on the revision from the Derby database. Also, the
+     * epoch entry is removed from the epoch table.
      * 
      * @param storeID
      *            the identifier of the {@link Store}
      * @throws StoreException
      */
     public void unregisterStore(String storeID) throws RevisionManagerException {
-        // get connection
-        Connection con = getConnection();
-        Statement stmt = null;
-        PreparedStatement ps = null;
-        String tableName = storeID;
-        try {
-            // first remove the the table
-            stmt = con.createStatement();
-            stmt.executeUpdate("DROP TABLE \"" + tableName + "\"");
-            log.debug("The revision table for the Store: {} has been dropped", storeID);
-
-            // delete the entry from epoch table
-            ps = con.prepareStatement("DELETE FROM " + DerbyDBManager.EPOCH_TABLE_NAME
-                                      + " WHERE tableName = ?");
-            ps.setString(1, tableName);
-            ps.executeUpdate();
-            log.debug("The epoch entry for the the Store: {} has been deleted", storeID);
-
-        } catch (SQLException e) {
-            log.error("Failed clear test resources for the table: {}", tableName);
-            throw new RevisionManagerException(String.format("Failed clear test resources for the table: %s",
-                tableName), e);
-        } finally {
-            dbManager.closeStatement(stmt);
-            dbManager.closeStatement(ps);
-            dbManager.closeConnection(con);
-        }
+        // first remove the table
+        dbManager.removeTable(storeID);
+        // remove the index
+        dbManager.removeIndex(getRevisionIndexName(storeID));
+        // delete the entry from epoch table
+        dbManager.removeEpochEntry(storeID);
+
+        log.info("The Store: {} has been unregistered");
     }
 
     @Override
     public long updateRevision(String storeID, String itemID) throws RevisionManagerException {
-        // get connection
-        Connection con = getConnection();
         String revisionTableName = storeID;
 
         // check existence of record for the given content item id
-        PreparedStatement ps = null;
-        ResultSet rs = null;
-        boolean recordExist = false;
-        try {
-            ps = con.prepareStatement(String.format(SELECT_REVISION, revisionTableName));
-            ps.setString(1, itemID);
-            rs = ps.executeQuery();
-            if (rs.next()) {
-                recordExist = true;
-            }
+        boolean recordExist = dbManager.existsRevisionEntry(revisionTableName, itemID);
 
-        } catch (SQLException e) {
-            dbManager.closeConnection(con);
-            log.error("Failed to query revision of content item", e);
-            throw new RevisionManagerException("Failed to query revision of content item", e);
-        } finally {
-            dbManager.closeResultSet(rs);
-            dbManager.closeStatement(ps);
+        long newRevision = System.currentTimeMillis();
+        if (!recordExist) {
+            dbManager.createRevisionEntry(revisionTableName, itemID, newRevision);
+        } else {
+            dbManager.updateRevisionEntry(revisionTableName, itemID, newRevision);
         }
+        log.info("Revision of the item: {} in Store: {} has been updated", itemID, storeID);
+        return newRevision;
+    }
 
-        // update the table
-        try {
-            long newRevision = System.currentTimeMillis();
-            if (!recordExist) {
-                log.debug("New revision: {} for the item: {} of Store: {} will be added",
-                    new Object[] {newRevision, itemID, revisionTableName});
-                ps = con.prepareStatement(String.format(INSERT_REVISION, revisionTableName));
-                ps.setString(1, itemID);
-                ps.setLong(2, newRevision);
-            } else {
-                log.debug("New revision: {} for the item: {} of Store: {} will be updated",
-                    new Object[] {newRevision, itemID, revisionTableName});
-
-                ps = con.prepareStatement(String.format(UPDATE_REVISION, revisionTableName));
-                ps.setLong(1, newRevision);
-                ps.setString(2, itemID);
-            }
-            int updatedRecordNum = ps.executeUpdate();
-            // exactly one record should be affected
-            if (updatedRecordNum != 1) {
-                log.warn("Unexpected number of updated records: {}, should be 1", updatedRecordNum);
-            }
-            return newRevision;
-        } catch (SQLException e) {
-            log.error("Failed to update revision", e);
-            throw new RevisionManagerException("Failed to update revision", e);
-        } finally {
-            dbManager.closeStatement(ps);
-            dbManager.closeConnection(con);
-        }
+    @Override
+    public void registerRevisions(String storeID, List<String> itemIDs) throws RevisionManagerException {
+        dbManager.createRevisionEntries(storeID, itemIDs);
     }
 
     /**
@@ -235,88 +153,52 @@ public class DerbyRevisionManager implem
         batchSize = batchSize == Integer.MAX_VALUE ? batchSize - 1 : batchSize;
 
         // check existence of record for the given content item id
-        PreparedStatement ps = null;
-        ResultSet rs = null;
         try {
             boolean moreChanges = false;
             long lastRowRevision = 0;
-            try {
-                ps = con.prepareStatement(String.format(SELECT_CHANGES, revisionTableName),
-                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-                ps.setLong(1, revision);
-                // set max rows one more than the batchsize to be able to see if there are other changes for
-                // the given revision beyond the batchsize
-                ps.setMaxRows(batchSize + 1);
-                rs = ps.executeQuery();
-
-                if (!rs.first()) {
-                    log.debug("There is no changes in store: {}, after revision: {}", storeID, revision);
-                    return new ChangeSetImpl(Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE,
-                            new ArrayList<String>());
+            // set max rows one more than the batchsize to be able to see if there are other changes for
+            // the given revision beyond the batchsize
+            List<RevisionBean> revisionBeans = dbManager.getRevisions(revisionTableName, revision,
+                Long.MAX_VALUE, batchSize + 1, 0);
+
+            if (revisionBeans.isEmpty()) {
+                log.debug("There is no changes in store: {}, after revision: {}", storeID, revision);
+                return new ChangeSetImpl(Long.MIN_VALUE, Long.MIN_VALUE, Long.MIN_VALUE,
+                        new ArrayList<String>());
+            }
+
+            // if the number of changes >= batchsize + 1
+            if (revisionBeans.size() == (batchSize + 1)) {
+                log.debug("There are changes more than the given batch size: {}", batchSize);
+                lastRowRevision = revisionBeans.get(batchSize).getRevision();
+                long nextToLastRowRevision = revisionBeans.get(batchSize - 1).getRevision();
+                // if we are in the middle of a revision, set the moreChanges flag to add all changes in
+                // that revision to changedUris
+                if (lastRowRevision == nextToLastRowRevision) {
+                    log.debug("The changes for the revision: {} exceeds the batch size", revision);
+                    moreChanges = true;
                 }
-
-                // if the number of changes >= batchsize + 1
-                if (rs.absolute(batchSize + 1)) {
-                    log.debug("There are changes after given revision more than the given batch size");
-                    lastRowRevision = rs.getLong(2);
-                    rs.previous();
-                    long nextToLastRowRevision = rs.getLong(2);
-                    rs.beforeFirst();
-                    // if we are in the middle of a revision, set the moreChanges flag to add all changes in
-                    // that revision to changedUris
-                    if (lastRowRevision == nextToLastRowRevision) {
-                        log.debug("The changes for the revision: {} exceeds the batch size");
-                        moreChanges = true;
-                    }
-                    while (rs.next()) {
-                        if (rs.isLast()) {
-                            break;
-                        }
-                        changedUris.add(rs.getString(1));
-                    }
-                    rs.previous();
-                } else {
-                    log.debug("There are changes after given revision less than or equal to the given batch size");
-                    rs.beforeFirst();
-                    while (rs.next()) {
-                        changedUris.add(rs.getString(1));
-                    }
-                    rs.last();
+                for (int i = 0; i < revisionBeans.size() - 1; i++) {
+                    changedUris.add(revisionBeans.get(i).getID());
+                }
+                log.info("Changes have been fetched for the initial batch size");
+            } else {
+                log.info("There are {} changes in total", revisionBeans.size());
+                for (RevisionBean rb : revisionBeans) {
+                    changedUris.add(rb.getID());
                 }
-
-                to = rs.getLong(2);
-                rs.first();
-                from = rs.getLong(2);
-                log.debug("Changes have been fetched for the initial batch size");
-
-            } catch (SQLException e) {
-                log.error("Failed to get changes for the Store: {}", storeID, e);
-                throw new RevisionManagerException(String.format("Failed to get changes for the Store: %s",
-                    storeID), e);
-            } finally {
-                dbManager.closeResultSet(rs);
-                dbManager.closeStatement(ps);
             }
+
+            to = revisionBeans.get(batchSize).getRevision();
+            from = revisionBeans.get(0).getRevision();
+
             if (moreChanges) {
-                try {
-                    ps = con.prepareStatement(String.format(SELECT_MORECHANGES, revisionTableName),
-                        ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-                    ps.setLong(1, revision);
-                    ps.setLong(2, lastRowRevision);
-                    ps.setLong(3, batchSize);
-                    rs = ps.executeQuery();
-
-                    while (rs.next()) {
-                        changedUris.add(rs.getString(1));
-                    }
-                    log.debug("Changes exceeding the batch size have been fetched");
-                } catch (SQLException e) {
-                    log.error("Failed to get changes", e);
-                    throw new RevisionManagerException("Failed to get changes", e);
-                } finally {
-                    dbManager.closeResultSet(rs);
-                    dbManager.closeStatement(ps);
+                revisionBeans = dbManager.getRevisions(revisionTableName, revision, lastRowRevision,
+                    Integer.MAX_VALUE, batchSize);
+                for (RevisionBean rb : revisionBeans) {
+                    changedUris.add(rb.getID());
                 }
+                log.info("Changes exceeding the batch size have been fetched. Total fetched changes: {}", changedUris.size());
             }
 
             long epoch = getEpoch(storeID);
@@ -328,34 +210,7 @@ public class DerbyRevisionManager implem
 
     @Override
     public long getEpoch(String storeID) throws RevisionManagerException {
-        // get connection
-        Connection con = getConnection();
-        PreparedStatement ps = null;
-        ResultSet rs = null;
-        long epoch;
-        try {
-            ps = con.prepareStatement(SELECT_EPOCH);
-            ps.setString(1, storeID);
-            rs = ps.executeQuery();
-
-            if (rs.next()) {
-                epoch = rs.getLong(1);
-            } else {
-                log.error(String.format("There is not an epoch record for the Store: %s", storeID));
-                throw new RevisionManagerException(String.format(
-                    "There is not an epoch record for the Store: %s", storeID));
-            }
-            log.debug("The epoch: {} for the Store: {} has been fetched", epoch, storeID);
-
-        } catch (SQLException e) {
-            log.error("Failed to execute query", e);
-            throw new RevisionManagerException("Failed to execute query", e);
-        } finally {
-            dbManager.closeResultSet(rs);
-            dbManager.closeStatement(ps);
-            dbManager.closeConnection(con);
-        }
-        return epoch;
+        return dbManager.getEpoch(storeID);
     }
 
     /**
@@ -370,74 +225,26 @@ public class DerbyRevisionManager implem
         return updateEpoch(storeID, false);
     }
 
-    private long updateEpoch(String storeID, boolean insert) throws RevisionManagerException {
-        // get connection
-        Connection con = getConnection();
-        PreparedStatement ps = null;
-
-        // update the table
-        try {
-            long newEpoch = System.currentTimeMillis();
-            if (!insert) {
-                // truncate the revision table
-                try {
-                    dbManager.truncateTable(storeID);
-                } catch (StoreException e) {
-                    log.error("Failed to truncate table while updating the epoch for the Store: {}", storeID);
-                    throw new RevisionManagerException(String.format(
-                        "Failed to truncate table while updating the epoch for the Store: %s", storeID), e);
-                }
-
-                log.debug("New epoch: {} for the Store: {} will be updated", newEpoch, storeID);
-                ps = con.prepareStatement(UPDATE_EPOCH);
-            } else {
-                // check existence of the epoch entry for the given Store
-                ResultSet rs = null;
-                boolean recordExist = false;
-                try {
-                    ps = con.prepareStatement(SELECT_EPOCH);
-                    ps.setString(1, storeID);
-                    rs = ps.executeQuery();
-                    if (rs.next()) {
-                        recordExist = true;
-                        newEpoch = rs.getLong("epoch");
-                    }
-
-                } catch (SQLException e) {
-                    log.error("Failed to query revision of content item", e);
-                    throw new RevisionManagerException("Failed to query revision of content item", e);
-                } finally {
-                    dbManager.closeResultSet(rs);
-                    dbManager.closeStatement(ps);
-                }
-
-                if (!recordExist) {
-                    log.debug("New epoch: {} for the Store: {} will be added", newEpoch, storeID);
-                    ps = con.prepareStatement(INSERT_EPOCH);
+    private long updateEpoch(String storeID, boolean initialize) throws RevisionManagerException {
+        long newEpoch = System.currentTimeMillis();
+        if (!initialize) {
+            // truncate the revision table
+            dbManager.truncateTable(storeID);
+            dbManager.updateEpochEntry(storeID, newEpoch);
+        } else {
+            try {
+                newEpoch = dbManager.getEpoch(storeID);
+            } catch (RevisionManagerException e) {
+                if (e.getCause() == null) {
+                    dbManager.createEpochEntry(storeID, newEpoch);
                 } else {
-                    // if there already exists an entry in the "epochTable"
-                    // for the given store, return from the method
-                    return newEpoch;
+                    throw e;
                 }
             }
-            ps.setLong(1, newEpoch);
-            ps.setString(2, storeID);
-            int updatedRecordNum = ps.executeUpdate();
-            log.debug("Epoch update/insertion has been done");
-
-            // exactly one record should be affected
-            if (updatedRecordNum != 1) {
-                log.warn("Unexpected number of updated records: {}, should be 1", updatedRecordNum);
-            }
-            return newEpoch;
-        } catch (SQLException e) {
-            log.error("Failed to update epoch for Store identified as: {}", storeID, e);
-            throw new RevisionManagerException(String.format("Failed to update epoch for identified as: %s",
-                storeID), e);
-        } finally {
-            dbManager.closeStatement(ps);
-            dbManager.closeConnection(con);
         }
+
+        log.info("Epoch update has been completed for the Store: {}", storeID);
+        return newEpoch;
     }
 
     private Connection getConnection() throws RevisionManagerException {
@@ -452,14 +259,13 @@ public class DerbyRevisionManager implem
     }
 
     /**
-     * Returns a string identifying the given {@link Store} instance in the scope of the revision management.
-     * Currently, the name of the Store is used as the identifiers of the Store. The name is obtained through
-     * the {@link Store#getName()} method.
+     * Returns a name for the index to be created on the <b>revision</b> of the given table
      * 
-     * @param store
+     * @param tableName
+     *            name of the revision table on which the index will be created
      * @return
      */
-    // public <Item> String getStoreID(Store<Item> store) {
-    // return store.getName();
-    // }
+    private String getRevisionIndexName(String tableName) {
+        return tableName + "_revisionindex";
+    }
 }