Index: src/edu/ucsb/nceas/metacat/ContentTypeProvider.java
===================================================================
--- src/edu/ucsb/nceas/metacat/ContentTypeProvider.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/ContentTypeProvider.java	(revision 2641)
@@ -173,8 +173,12 @@
     // create xml document
     try
     {
-      xmlDoc = new DocumentImpl(eml2DocId);
+      String accNumber = eml2DocId + MetaCatUtil.getOption("accNumSeparator") +
+                    DBUtil.getLatestRevisionInDocumentTable(eml2DocId);
+      //System.out.println("the acc number is !!!!!!!!!!!!!!!!!"+accNumber);
+      xmlDoc = new DocumentImpl(accNumber);
       xmlString = xmlDoc.toString();
+      //System.out.println("the xml doc is "+xmlDoc);
       // create dom tree
       read = new StringReader(xmlString);
       in = new InputSource(read);
@@ -528,8 +532,12 @@
     String xmlDoc = null;
     try
     {
-      DocumentImpl doc = new DocumentImpl(physicalDocid);
+      String accNumber = physicalDocid + MetaCatUtil.getOption("accNumSeparator") +
+        DBUtil.getLatestRevisionInDocumentTable(physicalDocid);
+      //System.out.println("the accenumber is !!!!!!!!!!!!!!!!!!" + accNumber);
+      DocumentImpl doc = new DocumentImpl(accNumber);
       xmlDoc = doc.toString();
+      //System.out.println("The physical xml is "+xmlDoc);
     }
     catch (Exception e)
     {
Index: src/edu/ucsb/nceas/metacat/DocumentImpl.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DocumentImpl.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/DocumentImpl.java	(revision 2641)
@@ -106,8 +106,7 @@
     static final int READ = 4;
     protected static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
     protected DBConnection connection = null;
-    protected String docid = null;
-    protected String updatedVersion = null;
+    //protected String updatedVersion = null;
     protected String docname = null;
     protected String doctype = null;
     private String validateType = null; //base on dtd or schema
@@ -116,6 +115,7 @@
     private String system_id = null;
     private String userowner = null;
     private String userupdated = null;
+    protected String docid = null; // without revision
     private int rev;
     private int serverlocation;
     private String docHomeServer;
@@ -142,18 +142,20 @@
      * @param conn
      *            the database connection from which to read the document
      * @param docid
-     *            the identifier of the document to be created
+     *            the identifier of the document to be created, it should
+     *            be with revision
      * @param readNodes
      *            flag indicating whether the xmlnodes should be read
      */
-    public DocumentImpl(String docid, boolean readNodes) throws McdbException
+    public DocumentImpl(String accNum, boolean readNodes) throws McdbException
     {
         try {
             //this.conn = conn;
-            this.docid = docid;
+            this.docid = MetaCatUtil.getDocIdFromAccessionNumber(accNum);
+            this.rev   = MetaCatUtil.getRevisionFromAccessionNumber(accNum);
 
             // Look up the document information
-            getDocumentInfo(docid);
+            getDocumentInfo(docid, rev);
 
             if (readNodes) {
                 // Download all of the document nodes using a single SQL query
@@ -235,7 +237,8 @@
         this.docname = docName;
         this.doctype = docType;
         this.docid = docId;
-        this.updatedVersion = newRevision;
+        this.rev = (new Integer(newRevision)).intValue();
+        //this.updatedVersion = newRevision;
         writeDocumentToDB(action, user, pub, catalogId, serverCode, createDate, updateDate);
     }
 
@@ -384,6 +387,7 @@
       DBConnection dbconn = null;
       PreparedStatement pstmt = null;
       int serialNumber = -1;
+      int revision = (new Integer(rev)).intValue();
       String sqlDateString = dbAdapter.getDateTimeFunction();
       if (createDate == null)
       {
@@ -421,8 +425,8 @@
             sql.append(doctype).append("','");
             sql.append(user).append("','");
             sql.append(user).append("','");
-            sql.append(serverCode).append("','");
-            sql.append(rev).append("',");
+            sql.append(serverCode).append("',");
+            sql.append(revision).append(",");
             sql.append(createDate).append(",");
             sql.append(updateDate).append(",");
             sql.append("'0')");
@@ -433,8 +437,8 @@
             sql.append(user).append("', ");
             sql.append("server_location='");
             sql.append(serverCode).append("',");
-            sql.append("rev='");
-            sql.append(rev).append("',");
+            sql.append("rev=");
+            sql.append(revision).append(",");
             sql.append("date_updated=");
             sql.append(updateDate);
             sql.append(" where docid='");
@@ -541,7 +545,7 @@
         String action = null;
         MetaCatUtil.debugMessage("The user specifyRev: " + userSpecifyRev, 30);
         // Revision for this docid in current database
-        int revInDataBase = getLatestRevisionNumber(docid);
+        int revInDataBase =DBUtil.getLatestRevisionInDocumentTable(docid);
         MetaCatUtil.debugMessage("The rev in data base: " + revInDataBase, 30);
         // String to store the revision
         String rev = null;
@@ -1201,8 +1205,11 @@
             nodeRecordMap.put(nodeId, currentNode);
         }
 
-        DocumentIdentifier doc = null;
-        try {
+        //DocumentIdentifier doc = null;
+        //String doc = MetaCatUtil.getDocIdFromAccessionNumber(docid);
+        String doc = docid;
+        //System.out.println("The doc is-----!!!!!!!!!!!!!!!!!! "+doc);
+        /*try {
             doc = new DocumentIdentifier(docid);
         } catch (AccessionNumberException e){
             MetaCatUtil.debugMessage("AccessionNumber Exception while "
@@ -1210,7 +1217,7 @@
                                      + "in DocumentImpl.buildIndex for "
                                      + "document " + docid, 10);
             MetaCatUtil.debugMessage(e.getMessage(), 10);
-        }
+        }*/
 
         // Opening separate db connection for deleting and writing
         // XML Index -- be sure that it is all in one db transaction
@@ -1229,7 +1236,7 @@
             // Delete all the entries in xml_queryresult
             PreparedStatement pstmt = dbConn.prepareStatement(
                     "DELETE FROM xml_queryresult WHERE docid = ?");
-            pstmt.setString(1, doc.getIdentifier());
+            pstmt.setString(1, doc);
             pstmt.execute();
             pstmt.close();
             dbConn.increaseUsageCount(1);
@@ -1237,15 +1244,17 @@
             // Delete all the entries in xml_queryresult
             pstmt = dbConn.prepareStatement(
                     "DELETE FROM xml_path_index WHERE docid = ?");
-            pstmt.setString(1, doc.getIdentifier());
+            pstmt.setString(1, doc);
             pstmt.execute();
             pstmt.close();
             dbConn.increaseUsageCount(1);
-
+            //System.out.println("after dleteing !!!!!!!!!!!1");
             // Step through all of the node records we were given
             // and build the new index and update the database
             it = nodeRecordLists.iterator();
+            //System.out.println("before iterator!!!!!!!!!!!1");
             while (it.hasNext()) {
+                //System.out.println("here!!!!!!!!!!!!!!!");
                 NodeRecord currentNode = (NodeRecord) it.next();
                 HashMap pathList = new HashMap();
                 if (currentNode.nodetype.equals("ELEMENT") ||
@@ -1304,7 +1313,7 @@
                                             + " ) AND n.parentnodeid=i.nodeid AND"
                                             + " n.nodetype LIKE 'TEXT' and n.docid = ?");
 
-            pstmt.setString(1, doc.getIdentifier());
+            pstmt.setString(1, doc);
 
             pstmt.execute();
             rs = pstmt.getResultSet();
@@ -1312,6 +1321,7 @@
             int count = 0;
 
             while (rs.next()) {
+                //System.out.println("update xml_path_index!!!!!!!1");
                 String docid = rs.getString(1);
                 String nodedata = rs.getString(2);
                 float nodedatanumerical = rs.getFloat(3);
@@ -1424,7 +1434,8 @@
      */
     private void deleteNodeIndex(DBConnection conn) throws SQLException
     {
-        String familyId = MetaCatUtil.getDocIdFromString(docid);
+        //String familyId = MetaCatUtil.getDocIdFromString(docid);
+        String familyId = docid;
         String sql = "DELETE FROM xml_index WHERE docid LIKE ?";
         MetaCatUtil.debugMessage(sql, 55);
         MetaCatUtil.debugMessage("SQL is: " + sql, 60);
@@ -1460,7 +1471,7 @@
                 "parentnodeid) " + "VALUES (?, ?, ?, ?, ?)");
         // Increase usage count for the connection
         conn.increaseUsageCount(1);
-        String familyId = MetaCatUtil.getDocIdFromString(docid);
+        String familyId = docid;
         pstmt.setString(3, familyId);
         pstmt.setString(4, doctype);
 
@@ -1479,14 +1490,13 @@
         pstmt.close();
     }
 
-    private boolean isRevisionOnly(DocumentIdentifier docid) throws Exception
+    private boolean isRevisionOnly(String docid, int revision) throws Exception
     {
-        //System.out.println("inRevisionOnly");
+        //System.out.println("inRevisionOnly given "+ docid + "."+ revision);
         DBConnection dbconn = null;
         int serialNumber = -1;
         PreparedStatement pstmt = null;
-        String rev = docid.getRev();
-        String newid = docid.getIdentifier();
+        String newid = docid;
 
         try {
             dbconn = DBConnectionPool
@@ -1497,21 +1507,22 @@
             pstmt.execute();
             ResultSet rs = pstmt.getResultSet();
             boolean tablehasrows = rs.next();
-            if (rev.equals("newest") || rev.equals("all")) { return false; }
-
+            //if (rev.equals("newest") || rev.equals("all")) { return false; }
+            
             if (tablehasrows) {
                 int r = rs.getInt(1);
+                //System.out.println("the rev in xml_documents table is "+r);
                 pstmt.close();
-                if (new Integer(rev).intValue() == r) { //the current revision
+                if (revision == r) { //the current revision
                                                         // in in xml_documents
                     //System.out.println("returning false");
                     return false;
-                } else if (new Integer(rev).intValue() < r) { //the current
+                } else if (revision < r) { //the current
                                                               // revision is in
                                                               // xml_revisions.
                     //System.out.println("returning true");
                     return true;
-                } else if (new Integer(rev).intValue() > r) { //error, rev
+                } else if (revision > r) { //error, rev
                                                               // cannot be
                                                               // greater than r
                 throw new Exception(
@@ -1518,10 +1529,26 @@
                         "requested revision cannot be greater than "
                                 + "the latest revision number."); }
             }
+            else
+            {
+                //System.out.println("in revision table branch -------");
+                // if we couldn't find it in xml_documents we 
+                // need to find it in xml_revision table
+                Vector revList = DBUtil.getRevListFromRevisionTable(docid);
+                for (int i=0; i<revList.size(); i++)
+                {
+                    Integer k = (Integer) revList.elementAt(i);
+                    //System.out.println("The rev in xml_revision talbe "+ k.toString());
+                }
+                
+                if (revList.contains(new Integer(revision)))
+                {
+                   return true;     
+                }
+            }
             // Get miss docid and rev, throw to McdDocNotFoundException
-            String missDocId = MetaCatUtil.getDocIdFromString(docid.toString());
-            String missRevision = MetaCatUtil.getRevisionStringFromString(docid
-                    .toString());
+            String missDocId = docid;
+            String missRevision = (new Integer(revision)).toString();
             throw new McdbDocNotFoundException("the requested docid '"
                     + docid.toString() + "' does not exist", missDocId,
                     missRevision);
@@ -1532,11 +1559,11 @@
         }//finally
     }
 
-    private void getDocumentInfo(String docid) throws McdbException,
+    /*private void getDocumentInfo(String docid) throws McdbException,
             AccessionNumberException, Exception
     {
         getDocumentInfo(new DocumentIdentifier(docid));
-    }
+    }*/
 
     /**
      * Look up the document type information from the database
@@ -1544,7 +1571,7 @@
      * @param docid
      *            the id of the document to look up
      */
-    private void getDocumentInfo(DocumentIdentifier docid)
+    private void getDocumentInfo(String docid, int revision)
             throws McdbException, Exception
     {
         DBConnection dbconn = null;
@@ -1553,7 +1580,7 @@
         String table = "xml_documents";
 
         try {
-            if (isRevisionOnly(docid)) { //pull the document from xml_revisions
+            if (isRevisionOnly(docid, revision)) { //pull the document from xml_revisions
                                          // instead of from xml_documents;
                 table = "xml_revisions";
             }
@@ -1577,8 +1604,8 @@
             sql.append("date_created, date_updated, user_owner, user_updated,");
             sql.append(" server_location, public_access, rev");
             sql.append(" FROM ").append(table);
-            sql.append(" WHERE docid LIKE '").append(docid.getIdentifier());
-            sql.append("' and rev like '").append(docid.getRev()).append("'");
+            sql.append(" WHERE docid LIKE '").append(docid);
+            sql.append("' and rev like '").append(revision).append("'");
 
             pstmt = dbconn.prepareStatement(sql.toString());
 
@@ -1641,8 +1668,8 @@
                 pstmt.close();
             }
         } catch (SQLException e) {
-            System.out.println("error in DocumentImpl.getDocumentInfo: "
-                    + e.getMessage());
+            MetaCatUtil.debugMessage("error in DocumentImpl.getDocumentInfo: "
+                    + e.getMessage(), 30);
             e.printStackTrace(System.out);
             throw new McdbException("Error accessing database connection in "
                     + "DocumentImpl.getDocumentInfo: ", e);
@@ -1660,8 +1687,7 @@
 
         if (this.docname == null) {
             throw new McdbDocNotFoundException(
-                "Document not found: " + docid, docid.getIdentifier(), docid
-                        .getRev());
+                "Document not found: " + docid, docid, (new Integer(revision)).toString());
         }
     }
 
@@ -1782,11 +1808,12 @@
         String nodedata = null;
         String quotechar = dbAdapter.getStringDelimiter();
         String table = "xml_nodes";
-
+        //System.out.println("in getNodeREcorelist !!!!!!!!!!!for root node id "+rootnodeid);
         try {
-            if (isRevisionOnly(new DocumentIdentifier(docid))) { //pull the document from xml_revisions
+            if (isRevisionOnly(docid, rev)) { //pull the document from xml_revisions
                 // instead of from xml_documents;
                 table = "xml_nodes_revisions";
+                //System.out.println("in getNodeREcorelist !!!!!!!!!!!2");
             }
         }  catch (McdbDocNotFoundException notFound) {
             throw notFound;
@@ -1795,7 +1822,7 @@
             MetaCatUtil.debugMessage("error in DocumentImpl.getDocumentInfo: "
                     + e.getMessage(), 30);
         }
-
+        //System.out.println("in getNodeREcorelist !!!!!!!!!!!3");
         try {
             dbconn = DBConnectionPool
                     .getDBConnection("DocumentImpl.getNodeRecordList");
@@ -1807,11 +1834,13 @@
 
             // Bind the values to the query
             pstmt.setLong(1, rootnodeid);
-
+            //System.out.println("in getNodeREcorelist !!!!!!!!!!!4");
             pstmt.execute();
             ResultSet rs = pstmt.getResultSet();
+            //System.out.println("in getNodeREcorelist !!!!!!!!!!!5");
             boolean tableHasRows = rs.next();
             while (tableHasRows) {
+                //System.out.println("in getNodeREcorelist !!!!!!!!!!!6");
                 nodeid = rs.getLong(1);
                 parentnodeid = rs.getLong(2);
                 nodeindex = rs.getLong(3);
@@ -1829,6 +1858,7 @@
                 tableHasRows = rs.next();
             }
             pstmt.close();
+            //System.out.println("in getNodeREcorelist !!!!!!!!!!!7");
 
         } catch (SQLException e) {
             throw new McdbException("Error in DocumentImpl.getNodeRecordList "
@@ -1844,7 +1874,7 @@
                 DBConnectionPool.returnDBConnection(dbconn, serialNumber);
             }
         }
-
+        //System.out.println("in getNodeREcorelist !!!!!!!!!!!8");
         return nodeRecordList;
 
     }
@@ -1853,6 +1883,7 @@
     private void writeDocumentToDB(String action, String user, String pub,
             String catalogid, int serverCode, String createDate, String updateDate) throws SQLException, Exception
     {
+        //System.out.println("!!!!!!!!1write document to db  " +docid +"."+rev);
         String sysdate = dbAdapter.getDateTimeFunction();
         if (createDate == null)
         {
@@ -1911,25 +1942,24 @@
                  */
                 pstmt.setInt(8, (new Integer(catalogid)).intValue());
                 pstmt.setInt(9, serverCode);
-                pstmt.setInt(10, Integer.parseInt(updatedVersion));
+                pstmt.setInt(10, rev);
                 
             } else if (action.equals("UPDATE")) {
-               
+                int thisrev = DBUtil.getLatestRevisionInDocumentTable(docid);
+                MetaCatUtil.debugMessage("this revsion is: " + thisrev, 40);
                 // Save the old document publicaccessentry in a backup table
-                thisdoc = new DocumentImpl(docid, false);
+                String accNumber = docid+MetaCatUtil.getOption("accNumSeparator")+thisrev;
+                thisdoc = new DocumentImpl(accNumber, false);
                 DocumentImpl.archiveDocRevision(connection, docid, user, thisdoc);
                 MetaCatUtil.debugMessage("after archiveDoc", 30);
-
-                int thisrev = thisdoc.getRev();
-                MetaCatUtil.debugMessage("this revsion is: " + thisrev, 40);
                 //if the updated vesion is not greater than current one,
                 //throw it into a exception
-                if (Integer.parseInt(updatedVersion) <= thisrev) {
+                if (rev <= thisrev) {
                     throw new Exception("Next revision number couldn't be less"
                             + " than or equal " + thisrev);
                 } else {
                     //set the user specified revision
-                    thisrev = Integer.parseInt(updatedVersion);
+                    thisrev = rev;
                 }
                 MetaCatUtil.debugMessage("final revsion is: " + thisrev, 40);
                 boolean useXMLIndex = (new Boolean(MetaCatUtil
@@ -2115,8 +2145,9 @@
                     + accnum);
             }
 
-            DocumentIdentifier id = new DocumentIdentifier(accnum);
-            String updaterev = id.getRev();
+            //DocumentIdentifier id = new DocumentIdentifier(accnum);
+            int revision = MetaCatUtil.getRevisionFromAccessionNumber(accnum);
+            String updaterev = (new Integer(revision)).toString();
             String server = MetacatReplication
                     .getServerNameForServerCode(serverCode);
             MetacatReplication.replLog("attempting to lock " + accnum);
@@ -2218,6 +2249,7 @@
 
             conn.setAutoCommit(false);
             parser.parse(new InputSource(xml));
+            //System.out.println("commit!!!!!!!!!!!!!!!!!111");
             conn.commit();
             conn.setAutoCommit(true);
             
@@ -2242,6 +2274,7 @@
         }
 
         // run access db base on relation table and access object
+        //System.out.println("the accnum will be write into access table "+accnum);
         runRelationAndAccessHandler(accnum, user, groups, serverCode);
 
         // Delete enteries from xml_queryresult for given docid if
@@ -2322,7 +2355,7 @@
         int userSpecifyRev = MetaCatUtil.getRevisionFromAccessionNumber(accnum);
         MetaCatUtil.debugMessage("The user specifyRev: " + userSpecifyRev, 30);
         // Revision for this docid in current database
-        int revInDataBase = getLatestRevisionNumber(docid);
+        int revInDataBase = DBUtil.getLatestRevisionInDocumentTable(docid);
         MetaCatUtil.debugMessage("The rev in data base: " + revInDataBase, 30);
         // String to store the revision
         String rev = (new Integer(userSpecifyRev)).toString();
@@ -2371,6 +2404,7 @@
             conn.commit();
             conn.setAutoCommit(true);
             
+            
             // write to xml_node complete. start the indexing thread.
             // this only for xml_documents
             DBSAXHandler dbx = (DBSAXHandler) parser.getContentHandler();
@@ -2416,6 +2450,12 @@
         } catch (Exception ee) {
         	conn.rollback();
             conn.setAutoCommit(true);
+            if (tableName.equals(REVISIONTABLE))
+            {
+                // because we couldn't register the table into xml_revsion
+                // we need to delete the nodes in xml_ndoes.
+                deleteXMLNodes(rootId);
+            }
             MetacatReplication.replErrorLog("Failed to " + "create access "
                     + "rule for package: " + accnum + " because "
                     + ee.getMessage());
@@ -2445,6 +2485,7 @@
             Vector packagedoctypes = new Vector();
             packagedoctypes = MetaCatUtil.getOptionList(packagedoctype);
             String docIdWithoutRev = MetaCatUtil.getDocIdFromString(accnumber);
+            int revision = MetaCatUtil.getRevisionFromAccessionNumber(accnumber);
             if (documenttype != null &&
                     packagedoctypes.contains(documenttype)) {
                 dbconn = DBConnectionPool.getDBConnection(
@@ -2455,7 +2496,7 @@
                 String aclid = RelationHandler.getAccessFileID(docIdWithoutRev);
                 // if there are access file, write ACL for that package
                 if (aclid != null) {
-                    runAccessControlList(dbconn, aclid, userName, group,
+                    runAccessControlList(dbconn, aclid, revision, userName, group,
                             servercode);
                 }
                 dbconn.commit();
@@ -2471,7 +2512,7 @@
                 serialNumber = dbconn.getCheckOutSerialNumber();
                 dbconn.setAutoCommit(false);
                 // write ACL for the package
-                runAccessControlList(dbconn, docIdWithoutRev, userName, group,
+                runAccessControlList(dbconn, docIdWithoutRev, revision, userName, group,
                         servercode);
                 dbconn.commit();
                 dbconn.setAutoCommit(true);
@@ -2496,11 +2537,11 @@
 
     // It runs in xmlIndex thread. It writes ACL for a package.
     private static void runAccessControlList(DBConnection conn, String aclid,
-            String users, String[] group, int servercode) throws Exception
+            int rev, String users, String[] group, int servercode) throws Exception
     {
         // read the access file from xml_nodes
         // parse the access file and store the access info into xml_access
-        AccessControlList aclobj = new AccessControlList(conn, aclid, users,
+        AccessControlList aclobj = new AccessControlList(conn, aclid, rev, users,
                 group, servercode);
 
     }
@@ -2931,7 +2972,9 @@
 
         try {
             if (doc == null) {
-                    doc = new DocumentImpl(docid);
+                String accNumber = docid + MetaCatUtil.getOption("accNumSeparator") +
+                DBUtil.getLatestRevisionInDocumentTable(docid);
+                    doc = new DocumentImpl(accNumber);
             }
             
             long rootNodeId = doc.getRootNodeID();
@@ -3114,57 +3157,8 @@
         }
     }
 
-    /**
-     * Get last revision number from database for a docid If couldn't find an
-     * entry, -1 will return The return value is integer because we want compare
-     * it to there new one
-     *
-     * @param docid
-     *            <sitecode>. <uniqueid>part of Accession Number
-     */
-    public static int getLatestRevisionNumber(String docId) throws SQLException
-    {
-        int rev = 1;
-        PreparedStatement pStmt = null;
-        DBConnection dbConn = null;
-        int serialNumber = -1;
-        // get rid of rev
-        docId = MetaCatUtil.getDocIdFromString(docId);
-        try {
-            //check out DBConnection
-            dbConn = DBConnectionPool
-                    .getDBConnection("DocumentImpl.getLatestRevisionNumber");
-            serialNumber = dbConn.getCheckOutSerialNumber();
+   
 
-            pStmt = dbConn
-                    .prepareStatement("SELECT rev FROM xml_documents WHERE docid='"
-                            + docId + "'");
-            pStmt.execute();
-
-            ResultSet rs = pStmt.getResultSet();
-            boolean hasRow = rs.next();
-            if (hasRow) {
-                rev = rs.getInt(1);
-                pStmt.close();
-            } else {
-                rev = -1;
-                pStmt.close();
-            }
-        }//try
-        finally {
-            try {
-                pStmt.close();
-            } catch (Exception ee) {
-                MetaCatUtil.debugMessage("Error in DocumentImpl."
-                        + "getLatestRevisionNumber: " + ee.getMessage(), 50);
-            } finally {
-                DBConnectionPool.returnDBConnection(dbConn, serialNumber);
-            }
-        }//finally
-
-        return rev;
-    }//getLatestRevisionNumber
-
     /**
      * Get server location form database for a accNum
      *
@@ -3471,13 +3465,13 @@
             if (action.equals("READ")) {
                 DocumentImpl xmldoc = new DocumentImpl(docid);
                 if (useOldReadAlgorithm) {
-                    System.out.println(xmldoc.readUsingSlowAlgorithm());
+                    MetaCatUtil.debugMessage(xmldoc.readUsingSlowAlgorithm(), 10);
                 } else {
                     xmldoc.toXml(new PrintWriter(System.out), null, null, true);
                 }
             } else if (action.equals("DELETE")) {
                 DocumentImpl.delete(docid, null, null,null);
-                System.out.println("Document deleted: " + docid);
+                //System.out.println("Document deleted: " + docid);
             } else {
                 /*
                  * String newdocid = DocumentImpl.write(dbconn, filename, null,
@@ -3498,18 +3492,18 @@
             double insertTime = (stopTime - connTime) / 1000;
             double executionTime = (stopTime - startTime) / 1000;
             if (showRuntime) {
-                System.out.println("\n\nTotal Execution time was: "
-                        + executionTime + " seconds.");
-                System.out.println("Time to open DB connection was: "
-                        + dbOpenTime + " seconds.");
-                System.out.println("Time to insert document was: " + insertTime
-                        + " seconds.");
+                MetaCatUtil.debugMessage("\n\nTotal Execution time was: "
+                        + executionTime + " seconds.", 10);
+                MetaCatUtil.debugMessage("Time to open DB connection was: "
+                        + dbOpenTime + " seconds.", 10);
+                MetaCatUtil.debugMessage("Time to insert document was: " + insertTime
+                        + " seconds.", 10);
             }
             dbconn.close();
         } catch (McdbException me) {
             me.toXml(new PrintWriter(System.err));
         } catch (AccessionNumberException ane) {
-            System.out.println(ane.getMessage());
+            System.err.println(ane.getMessage());
         } catch (Exception e) {
             System.err.println("EXCEPTION HANDLING REQUIRED");
             System.err.println(e.getMessage());
@@ -3640,4 +3634,39 @@
             DBConnectionPool.returnDBConnection(dbconn, serialNumber);
         }
     }
+    
+    /*
+     * This method will delete the xml_nodes table for a given root id
+     * This method will be called in the time_replication for revision table
+     * In revision replication, xml first will insert into xml_nodes, then
+     * move to xml_nodes_revision and register into xml_revsion table.
+     * if in the second step some error happend, we need to delete the
+     * node in xml_nodes table as roll back
+     */
+    static private void deleteXMLNodes(long rootId) throws Exception
+    {
+        DBConnection dbconn = null;
+        int serialNumber = -1;
+        //MetaCatUtil util = new MetaCatUtil();
+        AccessionNumber ac;
+        PreparedStatement pstmt = null;
+        String sql = "DELETE FROM xml_documents WHERE docid = "+ rootId;
+        try 
+        {
+            //dbconn = util.openDBConnection();
+            dbconn = DBConnectionPool.getDBConnection(
+                    "DeletedDocumentImpl.deletXMLNode");
+            serialNumber = dbconn.getCheckOutSerialNumber();
+            pstmt = dbconn.prepareStatement(sql);
+            // Increase dbconnection usage count
+            dbconn.increaseUsageCount(1);
+            pstmt.close();
+            dbconn.close();
+        } 
+        finally 
+        {
+            
+            DBConnectionPool.returnDBConnection(dbconn, serialNumber);
+        }
+    }
 }
Index: src/edu/ucsb/nceas/metacat/ReplicationHandler.java
===================================================================
--- src/edu/ucsb/nceas/metacat/ReplicationHandler.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/ReplicationHandler.java	(revision 2641)
@@ -269,7 +269,7 @@
 
   /* Handle replicate single xml document*/
   private void handleSingleXMLDocument(String remoteserver, String actions,
-                                       String docId, String tableName)
+                                       String accNumber, String tableName)
                throws Exception
   {
     DBConnection dbConn = null;
@@ -282,7 +282,7 @@
       serialNumber=dbConn.getCheckOutSerialNumber();
       //if the document needs to be updated or inserted, this is executed
       String readDocURLString = "https://" + remoteserver + "?server="+
-              util.getLocalReplicationServerName()+"&action=read&docid="+docId;
+              util.getLocalReplicationServerName()+"&action=read&docid="+accNumber;
       readDocURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDocURLString);
       URL u = new URL(readDocURLString);
 
@@ -301,7 +301,7 @@
       XMLReader docinfoParser = initParser(dih);
       String docInfoURLStr = "https://" + remoteserver +
                        "?server="+util.getLocalReplicationServerName()+
-                       "&action=getdocumentinfo&docid="+docId;
+                       "&action=getdocumentinfo&docid="+accNumber;
       docInfoURLStr = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLStr);
       URL docinfoUrl = new URL(docInfoURLStr);
       MetaCatUtil.debugMessage("Sending message: " +
@@ -315,9 +315,9 @@
       String createdDate = (String)docinfoHash.get("date_created");
       String updatedDate = (String)docinfoHash.get("date_updated");
       //docid should include rev number too
-      String accnum=docId+util.getOption("accNumSeparator")+
-                                              (String)docinfoHash.get("rev");
-      MetaCatUtil.debugMessage("docid in repl: "+accnum, 45);
+      /*String accnum=docId+util.getOption("accNumSeparator")+
+                                              (String)docinfoHash.get("rev");*/
+      MetaCatUtil.debugMessage("docid in repl: "+accNumber, 45);
       String docType = (String)docinfoHash.get("doctype");
       MetaCatUtil.debugMessage("doctype in repl: "+docType, 45);
 
@@ -342,7 +342,7 @@
                               (String)docinfoHash.get("public_access"),
                               null,  /* the dtd text */
                               actions,
-                              accnum,
+                              accNumber,
                               (String)docinfoHash.get("user_owner"),
                               null, /* null for groups[] */
                               docHomeServer,
@@ -349,16 +349,16 @@
                               remoteserver, tableName, true,// true is for time replication 
                               createdDate,
                               updatedDate);
-      MetaCatUtil.debugMessage("Successfully replicated doc " + accnum, 35);
-      MetacatReplication.replLog("wrote doc " + accnum + " from " +
+      MetaCatUtil.debugMessage("Successfully replicated doc " + accNumber, 35);
+      MetacatReplication.replLog("wrote doc " + accNumber + " from " +
                                          remoteserver);
 
     }//try
     catch(Exception e)
     {
-      MetacatReplication.replErrorLog("Failed to write doc " + docId +
+      MetacatReplication.replErrorLog("Failed to write doc " + accNumber +
                                       " into db because " +e.getMessage());
-      MetaCatUtil.debugMessage("Failed to write doc " + docId +
+      MetaCatUtil.debugMessage("Failed to write doc " + accNumber +
                                       " into db because " +e.getMessage(), 30);
       throw e;
     }
@@ -373,10 +373,10 @@
 
   /* Handle replicate single xml document*/
   private void handleSingleDataFile(String remoteserver, String actions,
-                                    String docId, String tableName)
+                                    String accNumber, String tableName)
                throws Exception
   {
-    MetaCatUtil.debugMessage("Try to replicate data file: "+docId, 40);
+    MetaCatUtil.debugMessage("Try to replicate data file: "+accNumber, 40);
     DBConnection dbConn = null;
     int serialNumber = -1;
     try
@@ -390,7 +390,7 @@
       XMLReader docinfoParser = initParser(dih);
       String docInfoURLString = "https://" + remoteserver +
                   "?server="+util.getLocalReplicationServerName()+
-                  "&action=getdocumentinfo&docid="+docId;
+                  "&action=getdocumentinfo&docid="+accNumber;
       docInfoURLString = MetaCatUtil.replaceWhiteSpaceForURL(docInfoURLString);
       URL docinfoUrl = new URL(docInfoURLString);
 
@@ -409,8 +409,8 @@
       String createdDate = (String)docinfoHash.get("date_created");
       String updatedDate = (String)docinfoHash.get("date_updated");
       //docid should include rev number too
-      String accnum=docId+util.getOption("accNumSeparator")+
-                                              (String)docinfoHash.get("rev");
+      /*String accnum=docId+util.getOption("accNumSeparator")+
+                                              (String)docinfoHash.get("rev");*/
 
 
       String datafilePath = util.getOption("datafilepath");
@@ -417,7 +417,7 @@
       // Get data file content
       String readDataURLString = "https://" + remoteserver + "?server="+
                                         util.getLocalReplicationServerName()+
-                                            "&action=readdata&docid="+accnum;
+                                            "&action=readdata&docid="+accNumber;
       readDataURLString = MetaCatUtil.replaceWhiteSpaceForURL(readDataURLString);
       URL u = new URL(readDataURLString);
       InputStream input = u.openStream();
@@ -428,7 +428,7 @@
         DocumentImpl.writeDataFileInReplication(input,
                                                 datafilePath,
                                                 docName,docType,
-                                                accnum, user,
+                                                accNumber, user,
                                                 docHomeServer,
                                                 remoteserver,
                                                 tableName,
@@ -436,22 +436,22 @@
                                                 createdDate,
                                                 updatedDate);
                                          
-        MetaCatUtil.debugMessage("Successfully to write datafile " + docId, 30);
-        MetacatReplication.replLog("wrote datafile " + accnum + " from " +
+        MetaCatUtil.debugMessage("Successfully to write datafile " + accNumber, 30);
+        MetacatReplication.replLog("wrote datafile " + accNumber + " from " +
                                     remoteserver);
       }//if
       else
       {
-         MetaCatUtil.debugMessage("Couldn't open the data file: " + accnum, 30);
-         throw new Exception("Couldn't open the data file: " + accnum);
+         MetaCatUtil.debugMessage("Couldn't open the data file: " + accNumber, 30);
+         throw new Exception("Couldn't open the data file: " + accNumber);
       }//else
 
     }//try
     catch(Exception e)
     {
-      MetacatReplication.replErrorLog("Failed to try wrote datafile " + docId +
+      MetacatReplication.replErrorLog("Failed to try wrote datafile " + accNumber +
                                       " because " +e.getMessage());
-      MetaCatUtil.debugMessage("Failed to try wrote datafile " + docId +
+      MetaCatUtil.debugMessage("Failed to try wrote datafile " + accNumber +
                                       " because " +e.getMessage(), 30);
       throw e;
     }
@@ -991,7 +991,7 @@
        boolean flag = false;
        try
        {
-         localrev = DocumentImpl.getLatestRevisionNumber(docid);
+         localrev = DBUtil.getLatestRevisionInDocumentTable(docid);
        }
        catch (SQLException e)
        {
@@ -1027,13 +1027,14 @@
            flag = true;
          }
        }
-
+       
+       String accNumber = docid + MetaCatUtil.getOption("accNumSeparator") + rev;
        // this is non-data file
        if(flag && !dataFile)
        {
          try
          {
-           handleSingleXMLDocument(remoteServer, action, docid, DocumentImpl.DOCUMENTTABLE);
+           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
          }
          catch(Exception e)
          {
@@ -1047,7 +1048,7 @@
        {
          try
          {
-           handleSingleDataFile(remoteServer, action, docid, DocumentImpl.DOCUMENTTABLE);
+           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.DOCUMENTTABLE);
          }
          catch(Exception e)
          {
@@ -1065,6 +1066,9 @@
                                         throws Exception
    {
        // compare the update rev and local rev to see what need happen
+       System.out.println("In handle repliation revsion table");
+       System.out.println("the docid is "+ docid);
+       System.out.println("The rev is "+rev);
        Vector localrev = null;
        String action = "INSERT";
        boolean flag = false;
@@ -1088,13 +1092,15 @@
        {
            flag = true;    
        }
-
+     
+       String accNumber = docid + MetaCatUtil.getOption("accNumSeparator") + rev;
        // this is non-data file
        if(flag && !dataFile)
        {
          try
          {
-           handleSingleXMLDocument(remoteServer, action, docid, DocumentImpl.REVISIONTABLE);
+           
+           handleSingleXMLDocument(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
          }
          catch(Exception e)
          {
@@ -1108,7 +1114,7 @@
        {
          try
          {
-           handleSingleDataFile(remoteServer, action, docid, DocumentImpl.REVISIONTABLE);
+           handleSingleDataFile(remoteServer, action, accNumber, DocumentImpl.REVISIONTABLE);
          }
          catch(Exception e)
          {
Index: src/edu/ucsb/nceas/metacat/DBUtil.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBUtil.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/DBUtil.java	(revision 2641)
@@ -622,5 +622,54 @@
 
       return list;
   }//getLatestRevisionNumber
+  
+  /**
+   * Get last revision number from database for a docid If couldn't find an
+   * entry, -1 will return The return value is integer because we want compare
+   * it to there new one
+   *
+   * @param docid
+   *            <sitecode>. <uniqueid>part of Accession Number
+   */
+  public static int getLatestRevisionInDocumentTable(String docIdWithoutRev) throws SQLException
+  {
+      int rev = 1;
+      PreparedStatement pStmt = null;
+      DBConnection dbConn = null;
+      int serialNumber = -1;
+      try {
+          //check out DBConnection
+          dbConn = DBConnectionPool
+                  .getDBConnection("DBUtil.getLatestRevisionInDocumentTable");
+          serialNumber = dbConn.getCheckOutSerialNumber();
+
+          pStmt = dbConn
+                  .prepareStatement("SELECT rev FROM xml_documents WHERE docid='"
+                          + docIdWithoutRev + "'");
+          pStmt.execute();
+
+          ResultSet rs = pStmt.getResultSet();
+          boolean hasRow = rs.next();
+          if (hasRow) {
+              rev = rs.getInt(1);
+              pStmt.close();
+          } else {
+              rev = -1;
+              pStmt.close();
+          }
+      }//try
+      finally {
+          try {
+              pStmt.close();
+          } catch (Exception ee) {
+              MetaCatUtil.debugMessage("Error in DBUtil."
+                      + "getLatestRevisionInDocumentTable: " + ee.getMessage(), 50);
+          } finally {
+              DBConnectionPool.returnDBConnection(dbConn, serialNumber);
+          }
+      }//finally
+
+      return rev;
+  }//getLatestRevisionNumber
    
 }
Index: src/edu/ucsb/nceas/metacat/DBQuery.java
===================================================================
--- src/edu/ucsb/nceas/metacat/DBQuery.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/DBQuery.java	(revision 2641)
@@ -481,7 +481,9 @@
                     // xmldoc = new DocumentImpl(dbconn, packageDocid);
                     //  thus use the following to get the doc info only
                     //  xmldoc = new DocumentImpl(dbconn);
-                    xmldoc = new DocumentImpl(packageDocid, false);
+                    String accNumber = packageDocid + MetaCatUtil.getOption("accNumSeparator") +
+                    DBUtil.getLatestRevisionInDocumentTable(packageDocid);
+                    xmldoc = new DocumentImpl(accNumber, false);
                     if (xmldoc == null)
                     {
                        MetaCatUtil.debugMessage("Document was null for: "
@@ -1621,7 +1623,7 @@
      *
      * @param dataPackageDocid, the string in docId field of xml_relation table
      */
-    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocid)
+    private Vector getOldVersionDocidListForDataPackage(String dataPackageDocidWithRev)
     {
 
         Vector docIdList = new Vector();//return value
@@ -1629,11 +1631,11 @@
         String xml = null;
 
         // Check the parameter
-        if (dataPackageDocid == null || dataPackageDocid.equals("")) { return docIdList; }//if
+        if (dataPackageDocidWithRev == null || dataPackageDocidWithRev.equals("")) { return docIdList; }//if
 
         try {
             //initial a documentImpl object
-            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocid);
+            DocumentImpl packageDocument = new DocumentImpl(dataPackageDocidWithRev);
             //transfer to documentImpl object to string
             xml = packageDocument.toString();
 
@@ -2045,7 +2047,7 @@
     /**
      * put a data packadge into a zip output stream
      *
-     * @param docId, which the user want to put into zip output stream
+     * @param docId, which the user want to put into zip output stream,it has version
      * @param out, a servletoutput stream which the zip output stream will be
      *            put
      * @param user, the username of the user
@@ -2092,7 +2094,7 @@
                 throw e;
             }
 
-            docImpls = new DocumentImpl(docId);
+            docImpls = new DocumentImpl(docIdString);
             //checking if the user has the permission to read the documents
             if (DocumentImpl.hasReadPermission(user, groups, docImpls
                     .getDocID())) {
Index: src/edu/ucsb/nceas/metacat/RemoteDocument.java
===================================================================
--- src/edu/ucsb/nceas/metacat/RemoteDocument.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/RemoteDocument.java	(revision 2641)
@@ -203,7 +203,9 @@
       throw new Exception ("Couldn't find a dataset docid for the required id");
     }
     // Create a documentImpl object
-    document = new DocumentImpl(givenDocId, false);
+    String accNumber = givenDocId + MetaCatUtil.getOption("accNumSeparator") +
+    DBUtil.getLatestRevisionInDocumentTable(givenDocId);
+    document = new DocumentImpl(accNumber, false);
     // get the replication home server (it come from xml_replication table)
     replicationDocHomeServer = document.getDocHomeServer();
     
Index: src/edu/ucsb/nceas/metacat/AccessControlList.java
===================================================================
--- src/edu/ucsb/nceas/metacat/AccessControlList.java	(revision 2640)
+++ src/edu/ucsb/nceas/metacat/AccessControlList.java	(revision 2641)
@@ -118,7 +118,7 @@
    * @param serverCode the serverid from xml_replication on which this document
    *        resides.
    */
-  public AccessControlList(DBConnection conn, String aclid, //Reader acl,
+  public AccessControlList(DBConnection conn, String aclid, int rev,//Reader acl,
                            String user, String[] groups, int serverCode)
                   throws SAXException, IOException, McdbException
   {
@@ -143,7 +143,7 @@
     this.serverCode = serverCode;
     
     // read the access file from db connection
-    DocumentImpl acldoc = new DocumentImpl(aclid);
+    DocumentImpl acldoc = new DocumentImpl(aclid+sep+rev);
     String acl = acldoc.toString();
     this.rev = acldoc.getRev();
 
@@ -326,8 +326,12 @@
           for (int i=0; i < aclObjects.size(); i++) {
             // docid of the current object
             String docid = (String)aclObjects.elementAt(i); 
-            DocumentIdentifier docID = new DocumentIdentifier(docid);
-            docid = docID.getIdentifier();
+            //DocumentIdentifier docID = new DocumentIdentifier(docid);
+            //docid = docID.getIdentifier();
+            // the docid get here has revision number, so we need to 
+            // remove it.
+            //docid = MetaCatUtil.getDocIdFromAccessionNumber(docid);
+            //System.out.println("The docid insert is!!!!!!!!!! "+ docid);
             insertPermissions(docid,leavingTagName);
           }
           
@@ -429,7 +433,9 @@
       ResultSet rs = pstmt.getResultSet();
       boolean hasRows = rs.next();
       while (hasRows) {
-        aclObjects.addElement(rs.getString(1));
+        String object = rs.getString(1);
+        //System.out.println("add acl object into vector !!!!!!!!!!!!!!!!!"+object);
+        aclObjects.addElement(object);
         hasRows = rs.next();
       }//whil
     }
