]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-5943: SQL query now invokes JDBCTools routine rather than replicating SQL...
authorAron Roberts <aron@socrates.berkeley.edu>
Mon, 25 Mar 2013 21:57:32 +0000 (14:57 -0700)
committerAron Roberts <aron@socrates.berkeley.edu>
Mon, 25 Mar 2013 21:57:32 +0000 (14:57 -0700)
services/common/src/main/java/org/collectionspace/services/common/document/DocumentHandler.java
services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RepositoryJavaClientImpl.java

index 075c350978ab1bd69ef01aa4414d4544f6feb3d9..d6da4bea98bad986df7bc5fc37dc1d84104b379f 100644 (file)
@@ -337,13 +337,13 @@ public interface DocumentHandler<T, TL, WT, WTL> {
      */
     public String getCMISQuery(QueryContext queryContext);
     
-    /*
-     * Returns TRUE if a CMIS query should be used (instead of an NXQL) query
+    /**
+     * Returns TRUE if a CMIS query should be used (instead of an NXQL query)
      */
     public boolean isCMISQuery();
 
-    /*
-     * Returns TRUE if an SQL query should be used (instead of an NXQL)
+    /**
+     * Returns TRUE if a JDBC/SQL query should be used (instead of an NXQL query)
      */
-       public boolean isJDBCQuery();
+    public boolean isJDBCQuery();
 }
index 1ed4c4c5ff69f7b85604d71e6db18b3a5be18e21..8f58bd6352112672a310879cfd1861243f21a889 100644 (file)
@@ -35,6 +35,9 @@ import java.sql.ResultSetMetaData;
 import java.sql.SQLException;\r
 import java.sql.Statement;\r
 import java.util.HashMap;\r
+import javax.sql.rowset.CachedRowSet;\r
+import javax.sql.rowset.RowSetFactory;\r
+import javax.sql.rowset.RowSetProvider;\r
 \r
 /**\r
  * User: laramie\r
@@ -164,22 +167,23 @@ public class JDBCTools {
                \r
         return result;\r
     }\r
-    \r
-    // Regarding the method below, we might instead identify whether we can\r
-    // return a CachedRowSet or equivalent.\r
-    // http://docs.oracle.com/javase/1.5.0/docs/api/javax/sql/rowset/CachedRowSet.html\r
-    // -- ADR 2012-12-06\r
 \r
-    /* THIS IS BROKEN - If you close the statement, it closes the ResultSet!!!\r
-    public static ResultSet executeQuery(String repoName, String sql) throws Exception {\r
+    public static CachedRowSet executeQuery(String dataSourceName, String repositoryName, String sql) throws Exception {\r
         Connection conn = null;\r
         Statement stmt = null;\r
         try {\r
-            conn = getConnection(repoName);    // If null, uses default\r
+            conn = getConnection(dataSourceName, repositoryName);\r
             stmt = conn.createStatement();\r
-            ResultSet rs = stmt.executeQuery(sql);\r
-            stmt.close();\r
-            return rs;  //don't call rs.close() here ... Let caller close and catch any exceptions.\r
+             \r
+           RowSetFactory rowSetFactory = RowSetProvider.newFactory();\r
+            CachedRowSet crs = rowSetFactory.createCachedRowSet();\r
+\r
+            stmt = conn.createStatement();\r
+            try (ResultSet resultSet = stmt.executeQuery(sql)) {\r
+                crs.populate(resultSet);\r
+            }\r
+            stmt.close(); // also closes resultSet\r
+            return crs;\r
         } catch (SQLException sqle) {\r
             SQLException tempException = sqle;\r
             while (null != tempException) {       // SQLExceptions can be chained. Loop to log all.\r
@@ -200,7 +204,7 @@ public class JDBCTools {
                 return null;\r
             }\r
         }\r
-    } */\r
+    }\r
 \r
     public static int executeUpdate(String dataSourceName, String repositoryName, String sql) throws Exception {\r
         Connection conn = null;\r
index 4bde46cf553cb77ea466476458bb8d545f32eb28..8a819685311a06251ce77ae58dbe19947d1e2d72 100644 (file)
@@ -1,25 +1,25 @@
 /**
- *  This document is a part of the source code and related artifacts
- *  for CollectionSpace, an open source collections management system
- *  for museums and related institutions:
-
- *  http://www.collectionspace.org
- *  http://wiki.collectionspace.org
-
- *  Copyright 2009 University of California at Berkeley
-
- *  Licensed under the Educational Community License (ECL), Version 2.0.
- *  You may not use this file except in compliance with this License.
-
- *  You may obtain a copy of the ECL 2.0 License at
-
- *  https://source.collectionspace.org/collection-space/LICENSE.txt
+ * This document is a part of the source code and related artifacts for
+ * CollectionSpace, an open source collections management system for museums and
+ * related institutions:
+ *
+ * http://www.collectionspace.org http://wiki.collectionspace.org
+ *
+ * Copyright 2009 University of California at Berkeley
+ *
+ * Licensed under the Educational Community License (ECL), Version 2.0. You may
+ * not use this file except in compliance with this License.
+ *
+ * You may obtain a copy of the ECL 2.0 License at
+ *
+ * https://source.collectionspace.org/collection-space/LICENSE.txt
  */
 package org.collectionspace.services.nuxeo.client.java;
 
 import java.io.Serializable;
 import java.sql.Connection;
 import java.sql.ResultSet;
+import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.Hashtable;
@@ -27,6 +27,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
+import javax.sql.rowset.CachedRowSet;
 
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MultivaluedMap;
@@ -82,60 +83,61 @@ import org.slf4j.LoggerFactory;
 
 /**
  * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
- * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler
- * with the client.
- * 
+ * repository using Remote Java APIs. It uses
+ *
+ * @see DocumentHandler as IOHandler with the client.
+ *
  * $LastChangedRevision: $ $LastChangedDate: $
  */
 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
 
-    /** The logger. */
+    /**
+     * The logger.
+     */
     private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
 //    private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
 //    private String foo = Profiler.createLogger();
-
     public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
     public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
-    
+    private static final String ID_COLUMN_NAME = "id";
+
     /**
      * Instantiates a new repository java client impl.
      */
     public RepositoryJavaClientImpl() {
         //Empty constructor
-       
     }
 
     public void assertWorkflowState(ServiceContext ctx,
-               DocumentModel docModel) throws DocumentNotFoundException, ClientException {
-       MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
-       if (queryParams != null) {
-               //
-               // Look for the workflow "delete" query param and see if we need to assert that the
-               // docModel is in a non-deleted workflow state.
-               //
-               String currentState = docModel.getCurrentLifeCycleState();
-               String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
-               boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
-               if (includeDeleted == false) {
-                       //
-                       // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
-                       //
-                       if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
-                               String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
-                               logger.debug(msg);
-                               throw new DocumentNotFoundException(msg);
-                       }
-               }
-       }
+            DocumentModel docModel) throws DocumentNotFoundException, ClientException {
+        MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
+        if (queryParams != null) {
+            //
+            // Look for the workflow "delete" query param and see if we need to assert that the
+            // docModel is in a non-deleted workflow state.
+            //
+            String currentState = docModel.getCurrentLifeCycleState();
+            String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
+            boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
+            if (includeDeleted == false) {
+                //
+                // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
+                //
+                if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
+                    String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
+                    logger.debug(msg);
+                    throw new DocumentNotFoundException(msg);
+                }
+            }
+        }
     }
-    
+
     /**
      * create document in the Nuxeo repository
      *
      * @param ctx service context under which this method is invoked
-     * @param handler
-     *            should be used by the caller to provide and transform the
-     *            document
+     * @param handler should be used by the caller to provide and transform the
+     * document
      * @return id in repository of the newly created document
      * @throws BadRequestException
      * @throws TransactionException
@@ -146,12 +148,12 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             DocumentHandler handler) throws BadRequestException,
             TransactionException, DocumentException {
 
-       String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
+        String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
         if (docType == null) {
             throw new IllegalArgumentException(
                     "RepositoryJavaClient.create: docType is missing");
         }
-       
+
         if (handler == null) {
             throw new IllegalArgumentException(
                     "RepositoryJavaClient.create: handler is missing");
@@ -162,7 +164,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                     "Unable to find workspace for service " + ctx.getServiceName()
                     + " check if the workspace exists in the Nuxeo repository");
         }
-        
+
         RepositoryInstance repoSession = null;
         try {
             handler.prepare(Action.CREATE);
@@ -176,11 +178,11 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
             /* Check for a versioned document, and check In and Out before we proceed.
              * This does not work as we do not have the uid schema on our docs.
-            if(((DocumentModelHandler) handler).supportsVersioning()) {
-                   doc.setProperty("uid","major_version",1);
-                   doc.setProperty("uid","minor_version",0);
-            }
-            */
+             if(((DocumentModelHandler) handler).supportsVersioning()) {
+             doc.setProperty("uid","major_version",1);
+             doc.setProperty("uid","minor_version",0);
+             }
+             */
             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
             handler.handle(Action.CREATE, wrapDoc);
@@ -194,7 +196,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         } catch (BadRequestException bre) {
             throw bre;
         } catch (Exception e) {
-                logger.error("Caught exception ", e);
+            logger.error("Caught exception ", e);
             throw new DocumentException(e);
         } finally {
             if (repoSession != null) {
@@ -206,13 +208,13 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
     /**
      * get document from the Nuxeo repository
+     *
      * @param ctx service context under which this method is invoked
-     * @param id
-     *            of the document to retrieve
-     * @param handler
-     *            should be used by the caller to provide and transform the
-     *            document
-     * @throws DocumentNotFoundException if the document cannot be found in the repository
+     * @param id of the document to retrieve
+     * @param handler should be used by the caller to provide and transform the
+     * document
+     * @throws DocumentNotFoundException if the document cannot be found in the
+     * repository
      * @throws TransactionException
      * @throws DocumentException
      */
@@ -224,7 +226,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             throw new IllegalArgumentException(
                     "RepositoryJavaClient.get: handler is missing");
         }
-        
+
         RepositoryInstance repoSession = null;
         try {
             handler.prepare(Action.GET);
@@ -232,7 +234,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
             DocumentModel docModel = null;
             try {
-               docModel = repoSession.getDocument(docRef);
+                docModel = repoSession.getDocument(docRef);
                 assertWorkflowState(ctx, docModel);
             } catch (ClientException ce) {
                 String msg = logException(ce, "Could not find document with CSID=" + id);
@@ -263,11 +265,12 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
     /**
      * get a document from the Nuxeo repository, using the docFilter params.
+     *
      * @param ctx service context under which this method is invoked
-     * @param handler
-     *            should be used by the caller to provide and transform the
-     *            document. Handler must have a docFilter set to return a single item.
-     * @throws DocumentNotFoundException if the document cannot be found in the repository
+     * @param handler should be used by the caller to provide and transform the
+     * document. Handler must have a docFilter set to return a single item.
+     * @throws DocumentNotFoundException if the document cannot be found in the
+     * repository
      * @throws TransactionException
      * @throws DocumentException
      */
@@ -314,9 +317,9 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
         }
     }
-    
+
     public DocumentWrapper<DocumentModel> getDoc(
-               RepositoryInstance repoSession,
+            RepositoryInstance repoSession,
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
             String csid) throws DocumentNotFoundException, DocumentException {
         DocumentWrapper<DocumentModel> wrapDoc = null;
@@ -327,8 +330,8 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             try {
                 doc = repoSession.getDocument(docRef);
             } catch (ClientException ce) {
-               String msg = logException(ce, "Could not find document with CSID=" + csid);
-               throw new DocumentNotFoundException(msg, ce);
+                String msg = logException(ce, "Could not find document with CSID=" + csid);
+                throw new DocumentNotFoundException(msg, ce);
             }
             wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
         } catch (IllegalArgumentException iae) {
@@ -339,14 +342,13 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
         return wrapDoc;
     }
-    
+
     /**
-     * Get wrapped documentModel from the Nuxeo repository.  The search is restricted to the workspace
-     * of the current context.
-     * 
+     * Get wrapped documentModel from the Nuxeo repository. The search is
+     * restricted to the workspace of the current context.
+     *
      * @param ctx service context under which this method is invoked
-     * @param csid
-     *            of the document to retrieve
+     * @param csid of the document to retrieve
      * @throws DocumentNotFoundException
      * @throws TransactionException
      * @throws DocumentException
@@ -360,7 +362,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         DocumentWrapper<DocumentModel> wrapDoc = null;
 
         try {
-               // Open a new repository session
+            // Open a new repository session
             repoSession = getRepositorySession(ctx);
             wrapDoc = getDoc(repoSession, ctx, csid);
         } catch (IllegalArgumentException iae) {
@@ -377,9 +379,9 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                 releaseRepositorySession(ctx, repoSession);
             }
         }
-        
+
         if (logger.isWarnEnabled() == true) {
-               logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
+            logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
         }
         return wrapDoc;
     }
@@ -420,12 +422,13 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
             throw new DocumentException(e);
         }
-        
+
         return wrapDoc;
     }
-    
+
     /**
      * find wrapped documentModel from the Nuxeo repository
+     *
      * @param ctx service context under which this method is invoked
      * @param whereClause where NXQL where clause to get the document
      * @throws DocumentNotFoundException
@@ -437,7 +440,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
     public DocumentWrapper<DocumentModel> findDoc(
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
             String whereClause)
-                       throws DocumentNotFoundException, TransactionException, DocumentException {
+            throws DocumentNotFoundException, TransactionException, DocumentException {
         RepositoryInstance repoSession = null;
         DocumentWrapper<DocumentModel> wrapDoc = null;
 
@@ -445,22 +448,23 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             repoSession = getRepositorySession(ctx);
             wrapDoc = findDoc(repoSession, ctx, whereClause);
         } catch (Exception e) {
-                       throw new DocumentException("Unable to create a Nuxeo repository session.", e);
-               } finally {
+            throw new DocumentException("Unable to create a Nuxeo repository session.", e);
+        } finally {
             if (repoSession != null) {
                 releaseRepositorySession(ctx, repoSession);
             }
         }
-        
+
         if (logger.isWarnEnabled() == true) {
-               logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
+            logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
         }
-        
+
         return wrapDoc;
     }
 
     /**
      * find doc and return CSID from the Nuxeo repository
+     *
      * @param repoSession
      * @param ctx service context under which this method is invoked
      * @param whereClause where NXQL where clause to get the document
@@ -470,16 +474,16 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
      * @return the CollectionSpace ID (CSID) of the requested document
      */
     @Override
-    public String findDocCSID(RepositoryInstance repoSession, 
+    public String findDocCSID(RepositoryInstance repoSession,
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
             throws DocumentNotFoundException, TransactionException, DocumentException {
         String csid = null;
         boolean releaseSession = false;
         try {
-               if (repoSession == null) {
-                       repoSession = this.getRepositorySession(ctx);
-                       releaseSession = true;
-               }
+            if (repoSession == null) {
+                repoSession = this.getRepositorySession(ctx);
+                releaseSession = true;
+            }
             DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
             DocumentModel docModel = wrapDoc.getWrappedObject();
             csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
@@ -495,9 +499,9 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
             throw new DocumentException(e);
         } finally {
-               if(releaseSession && (repoSession != null)) {
-                       this.releaseRepositorySession(ctx, repoSession);
-               }
+            if (releaseSession && (repoSession != null)) {
+                this.releaseRepositorySession(ctx, repoSession);
+            }
         }
         return csid;
     }
@@ -511,7 +515,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             int pageSize,
             int pageNum,
             boolean computeTotal)
-                       throws DocumentNotFoundException, DocumentException {
+            throws DocumentNotFoundException, DocumentException {
         DocumentWrapper<DocumentModelList> wrapDoc = null;
 
         try {
@@ -523,9 +527,9 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
             String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
             if (logger.isDebugEnabled()) {
-                logger.debug("findDocs() NXQL: "+query);
+                logger.debug("findDocs() NXQL: " + query);
             }
-            docList = repoSession.query(query, null, pageSize, pageSize*pageNum, computeTotal);
+            docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
             wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
         } catch (IllegalArgumentException iae) {
             throw iae;
@@ -535,39 +539,39 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
             throw new DocumentException(e);
         }
-                
+
         return wrapDoc;
     }
-    
+
     protected static String buildInListForDocTypes(List<String> docTypes) {
-       StringBuilder sb = new StringBuilder();
-       sb.append("(");
-       boolean first = true;
-       for(String docType:docTypes) {
-               if(first) {
-                       first = false;
-               } else {
-                       sb.append(",");
-               }
-                       sb.append("'");
-               sb.append(docType);
-                       sb.append("'");
-       }
-       sb.append(")");
-       return sb.toString();
+        StringBuilder sb = new StringBuilder();
+        sb.append("(");
+        boolean first = true;
+        for (String docType : docTypes) {
+            if (first) {
+                first = false;
+            } else {
+                sb.append(",");
+            }
+            sb.append("'");
+            sb.append(docType);
+            sb.append("'");
+        }
+        sb.append(")");
+        return sb.toString();
     }
-    
+
     public DocumentWrapper<DocumentModelList> findDocs(
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
             DocumentHandler handler,
             RepositoryInstance repoSession,
             List<String> docTypes)
-                       throws DocumentNotFoundException, DocumentException {
+            throws DocumentNotFoundException, DocumentException {
         DocumentWrapper<DocumentModelList> wrapDoc = null;
 
         DocumentFilter filter = handler.getDocumentFilter();
         String oldOrderBy = filter.getOrderByClause();
-        if (isClauseEmpty(oldOrderBy) == true){
+        if (isClauseEmpty(oldOrderBy) == true) {
             filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
         }
         QueryContext queryContext = new QueryContext(ctx, handler);
@@ -578,14 +582,14 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                         "The findDocs() method must specify at least one DocumentType.");
             }
             DocumentModelList docList = null;
-               if (handler.isCMISQuery() == true) {
-                       String inList = buildInListForDocTypes(docTypes);
-                       ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
-                       docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
+            if (handler.isCMISQuery() == true) {
+                String inList = buildInListForDocTypes(docTypes);
+                ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
+                docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
             } else {
                 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
                 if (logger.isDebugEnabled()) {
-                    logger.debug("findDocs() NXQL: "+query);
+                    logger.debug("findDocs() NXQL: " + query);
                 }
                 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
             }
@@ -598,16 +602,15 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
             throw new DocumentException(e);
         }
-                
+
         return wrapDoc;
     }
-    
 
-    
     /**
      * Find a list of documentModels from the Nuxeo repository
+     *
      * @param docTypes a list of DocType names to match
-     * @param  whereClause where the clause to qualify on
+     * @param whereClause where the clause to qualify on
      * @throws DocumentNotFoundException
      * @throws TransactionException
      * @throws DocumentException
@@ -626,7 +629,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         try {
             repoSession = getRepositorySession(ctx);
             wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
-                       pageSize, pageNum, computeTotal);
+                    pageSize, pageNum, computeTotal);
         } catch (IllegalArgumentException iae) {
             throw iae;
         } catch (Exception e) {
@@ -639,11 +642,11 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                 releaseRepositorySession(ctx, repoSession);
             }
         }
-        
+
         if (logger.isWarnEnabled() == true) {
-               logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
+            logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
         }
-        
+
         return wrapDoc;
     }
 
@@ -694,9 +697,8 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
      * repository
      *
      * @param ctx service context under which this method is invoked
-     * @param handler
-     *            should be used by the caller to provide and transform the
-     *            document
+     * @param handler should be used by the caller to provide and transform the
+     * document
      * @throws DocumentNotFoundException
      * @throws TransactionException
      * @throws DocumentException
@@ -715,7 +717,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                     + ctx.getServiceName()
                     + " check if the workspace exists in the Nuxeo repository.");
         }
-        
+
         RepositoryInstance repoSession = null;
         try {
             handler.prepare(Action.GET_ALL);
@@ -740,26 +742,26 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
         }
     }
-    
+
     private boolean isClauseEmpty(String theString) {
-       boolean result = true;
-       if (theString != null && !theString.isEmpty()) {
-               result = false;
-       }
-       return result;
+        boolean result = true;
+        if (theString != null && !theString.isEmpty()) {
+            result = false;
+        }
+        return result;
     }
-    
+
     public DocumentWrapper<DocumentModel> getDocFromCsid(
-               ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
-               RepositoryInstance repoSession,
-               String csid)
+            ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
+            RepositoryInstance repoSession,
+            String csid)
             throws Exception {
         DocumentWrapper<DocumentModel> result = null;
 
         result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
-        
+
         return result;
-    }    
+    }
 
     /*
      * A method to find a CollectionSpace document (of any type) given just a service context and
@@ -770,76 +772,79 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
      */
     @Override
     public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
-               String csid)
+            String csid)
             throws Exception {
         DocumentWrapper<DocumentModel> result = null;
         RepositoryInstance repoSession = null;
         try {
-               repoSession = getRepositorySession(ctx);
-               result = getDocFromCsid(ctx, repoSession, csid);
+            repoSession = getRepositorySession(ctx);
+            result = getDocFromCsid(ctx, repoSession, csid);
         } finally {
             if (repoSession != null) {
                 releaseRepositorySession(ctx, repoSession);
             }
         }
-        
+
         if (logger.isWarnEnabled() == true) {
-               logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
+            logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
         }
-        
+
         return result;
     }
 
     /**
      * Returns a URI value for a document in the Nuxeo repository
+     *
      * @param wrappedDoc a wrapped documentModel
      * @throws ClientException
      * @return a document URI
      */
     @Override
     public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
-       DocumentModel docModel = wrappedDoc.getWrappedObject();
-        String uri = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
-                       CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
+        DocumentModel docModel = wrappedDoc.getWrappedObject();
+        String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
+                CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
         return uri;
     }
 
     /*
      * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
      */
-       private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
-               IterableQueryResult result = null;
-               
-               // the NuxeoRepository should be constructed only once, then cached
-               // (its construction is expensive)
-               try {
-                       NuxeoRepository repo = new NuxeoRepository(
-                                       repoSession.getRepositoryName(), repoSession
-                                                       .getRootDocument().getId());
-                       logger.debug("Repository ID:" + repo.getId() + " Root folder:"
-                                       + repo.getRootFolderId());
-
-                       CallContextImpl callContext = new CallContextImpl(
-                                       CallContext.BINDING_LOCAL, repo.getId(), false);
-                       callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
-                                       .getName());
-                       NuxeoCmisService cmisService = new NuxeoCmisService(repo,
-                                       callContext, repoSession);
-
-                       result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
-               } catch (ClientException e) {
-                       // TODO Auto-generated catch block
-                       logger.error("Encounter trouble making the following CMIS query: " + query, e);
-               }
-               
-               return result;
-       }
-     
+    private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
+        IterableQueryResult result = null;
+
+        // the NuxeoRepository should be constructed only once, then cached
+        // (its construction is expensive)
+        try {
+            NuxeoRepository repo = new NuxeoRepository(
+                    repoSession.getRepositoryName(), repoSession
+                    .getRootDocument().getId());
+            logger.debug("Repository ID:" + repo.getId() + " Root folder:"
+                    + repo.getRootFolderId());
+
+            CallContextImpl callContext = new CallContextImpl(
+                    CallContext.BINDING_LOCAL, repo.getId(), false);
+            callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
+                    .getName());
+            NuxeoCmisService cmisService = new NuxeoCmisService(repo,
+                    callContext, repoSession);
+
+            result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
+        } catch (ClientException e) {
+            // TODO Auto-generated catch block
+            logger.error("Encounter trouble making the following CMIS query: " + query, e);
+        }
+
+        return result;
+    }
+
     /**
-     * getFiltered get all documents for an entity service from the Document repository,
-     * given filter parameters specified by the handler. 
+     * getFiltered get all documents for an entity service from the Document
+     * repository, given filter parameters specified by the handler.
+     *
      * @param ctx service context under which this method is invoked
-     * @param handler should be used by the caller to provide and transform the document
+     * @param handler should be used by the caller to provide and transform the
+     * document
      * @throws DocumentNotFoundException if workspace not found
      * @throws TransactionException
      * @throws DocumentException
@@ -850,7 +855,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
         DocumentFilter filter = handler.getDocumentFilter();
         String oldOrderBy = filter.getOrderByClause();
-        if (isClauseEmpty(oldOrderBy) == true){
+        if (isClauseEmpty(oldOrderBy) == true) {
             filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
         }
         QueryContext queryContext = new QueryContext(ctx, handler);
@@ -859,7 +864,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         try {
             handler.prepare(Action.GET_ALL);
             repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
-            
+
             DocumentModelList docList = null;
             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
 
@@ -869,14 +874,14 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
             // If we have limit and/or offset, then pass true to get totalSize
             // in returned DocumentModelList.
-               Profiler profiler = new Profiler(this, 2);
-               profiler.log("Executing NXQL query: " + query.toString());
-               profiler.start();
-               if (handler.isJDBCQuery() == true) {
-                       docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
-               } else if (handler.isCMISQuery() == true) {
-                       docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
-               } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
+            Profiler profiler = new Profiler(this, 2);
+            profiler.log("Executing NXQL query: " + query.toString());
+            profiler.start();
+            if (handler.isJDBCQuery() == true) {
+                docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
+            } else if (handler.isCMISQuery() == true) {
+                docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
+            } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
                 docList = repoSession.query(query, null,
                         queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
             } else {
@@ -902,112 +907,158 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
         }
     }
-    
+
     private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
             throws Exception {
-       DocumentModelList result = new DocumentModelListImpl();
-       
-       String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
-       String repositoryName = ctx.getRepositoryName();
-       Connection connection = JDBCTools.getConnection(dataSourceName, repositoryName);
-       
-       MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
+        DocumentModelList result = new DocumentModelListImpl();
+
+        String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
+        String repositoryName = ctx.getRepositoryName();
+
+        // Connection connection = JDBCTools.getConnection(dataSourceName, repositoryName);
+
+        MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
-        
+
         // FIXME: Replace this placeholder with an appropriate per-authority value
         // obtained from the relevant document handler
-        String termInfoGroupTable = "loctermgroup";
-        
+        String termInfoGroupTableName = "loctermgroup";
+
         // FIXME: Replace this placeholder query with an actual query from CSPACE-5945
         // FIXME: Consider using a prepared statement here
-       String theQuery =
-                "SELECT termdisplayname FROM "
-                + termInfoGroupTable
+        String sql =
+                "SELECT id, termdisplayname FROM "
+                + termInfoGroupTableName
                 + " WHERE termdisplayname LIKE '" + partialTerm + "%'";
 
         // Make sure autocommit is off. See:
-       // http://jdbc.postgresql.org/documentation/80/query.html#query-with-cursor
-       // http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
-       connection.setAutoCommit(false);
-       
+        // http://jdbc.postgresql.org/documentation/80/query.html#query-with-cursor
+        // http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
+        // connection.setAutoCommit(false);
+
         // FIXME: Add exception handling and 'finally' blocks to ensure we close resources
         // FIXME: Identify whether we can piggyback on existing JDBC method(s) in common.storage,
         // and if so, add whatever additional functionality may be required to those method(s)
         // FIXME: Add pagination handling
-        
-        Statement st = connection.createStatement();
-       // Enable use of the cursor for pagination
-       st.setFetchSize(50);
+
+        /*
+         Statement st = connection.createStatement();
+         // Enable use of the cursor for pagination
+         st.setFetchSize(50);
+         List<String> docIds = new ArrayList<String>();
+         ResultSet rs = st.executeQuery(sql);
+         String id;
+         while (rs.next()) {
+         id = rs.getString("id");
+         if (Tools.notBlank(id)) {
+         docIds.add(id);
+         }
+         }
+         rs.close();
+
+         // Close the statement.
+         st.close();
+         */
+
         List<String> docIds = new ArrayList<String>();
-       ResultSet rs = st.executeQuery(theQuery);
-        String id;
-       while (rs.next()) {
-            id = rs.getString("id");
-            if (Tools.notBlank(id)) {
-                docIds.add(id);
+        CachedRowSet crs = null;
+        try {
+            crs = JDBCTools.executeQuery(dataSourceName, repositoryName, sql);
+
+            // If the response to the query is null or contains zero rows,
+            // return an empty list of document models
+            if (crs == null) {
+                return result;
+            }
+            crs.last();
+            if (crs.getRow() == 0) {
+                return result; // empty list of document models
             }
-       }
-       rs.close();
 
-       // Close the statement.
-       st.close();
+            // Otherwise, get the document IDs from the results of the query
+            String id;
+            /*
+            int idColumnIndex;
+            try {
+                idColumnIndex = crs.findColumn(ID_COLUMN_NAME);
+            } catch (SQLException sqle) {
+                logger.warn("Could not find expected column '" + ID_COLUMN_NAME + "' in query results.");
+                return result; // return an empty list of document models
+            } finally {
+                crs.close();
+            }
+            */
+            crs.beforeFirst();
+            while (crs.next()) {
+                // id = crs.getString(idColumnIndex);
+                id = crs.getString(1);
+                if (Tools.notBlank(id)) {
+                    docIds.add(id);
+                }
+            }
+        } catch (SQLException sqle) {
+            logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
+            return result; // return an empty list of document models
+        } finally {
+            crs.close();
+        } 
 
         // Get a list of document models, using the IDs obtained from the query
         for (String docId : docIds) {
             result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
         }
-       
-       return result;
+
+        return result;
     }
 
     private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
             throws DocumentNotFoundException, DocumentException {
 
-       DocumentModelList result = new DocumentModelListImpl();
+        DocumentModelList result = new DocumentModelListImpl();
         try {
             String query = handler.getCMISQuery(queryContext);
 
-               DocumentFilter docFilter = handler.getDocumentFilter();
+            DocumentFilter docFilter = handler.getDocumentFilter();
             int pageSize = docFilter.getPageSize();
             int offset = docFilter.getOffset();
             if (logger.isDebugEnabled()) {
                 logger.debug("Executing CMIS query: " + query.toString()
-                               + "with pageSize: "+pageSize+" at offset: "+offset);
+                        + "with pageSize: " + pageSize + " at offset: " + offset);
             }
 
             // If we have limit and/or offset, then pass true to get totalSize
             // in returned DocumentModelList.
-               Profiler profiler = new Profiler(this, 2);
-               profiler.log("Executing CMIS query: " + query.toString());
-               profiler.start();
-               //
-               IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
-               try {
-               int totalSize = (int)queryResult.size();
-               ((DocumentModelListImpl)result).setTotalSize(totalSize);
-                               // Skip the rows before our offset
-                               if (offset > 0) {
-                                       queryResult.skipTo(offset);
-                               }
-                       int nRows = 0;
-                       for (Map<String, Serializable> row : queryResult) {
-                               if (logger.isTraceEnabled()) {
-                                       logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
-                                                       + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
-                               }
-                               String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
-                               DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
-                               result.add(docModel);
-                               nRows++;
-                                       if (nRows >= pageSize && pageSize != 0 ) { // A page size of zero means that they want all of them
-                                               logger.debug("Got page full of items - quitting");
-                                               break;
-                                       }
-                       }
-               } finally {
-                       queryResult.close();
-               }
-               //
+            Profiler profiler = new Profiler(this, 2);
+            profiler.log("Executing CMIS query: " + query.toString());
+            profiler.start();
+            //
+            IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
+            try {
+                int totalSize = (int) queryResult.size();
+                ((DocumentModelListImpl) result).setTotalSize(totalSize);
+                // Skip the rows before our offset
+                if (offset > 0) {
+                    queryResult.skipTo(offset);
+                }
+                int nRows = 0;
+                for (Map<String, Serializable> row : queryResult) {
+                    if (logger.isTraceEnabled()) {
+                        logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
+                                + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
+                    }
+                    String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
+                    DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
+                    result.add(docModel);
+                    nRows++;
+                    if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
+                        logger.debug("Got page full of items - quitting");
+                        break;
+                    }
+                }
+            } finally {
+                queryResult.close();
+            }
+            //
             profiler.stop();
 
         } catch (Exception e) {
@@ -1016,52 +1067,51 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
             throw new DocumentException(e);
         }
-        
+
         //
         // Since we're not supporting paging yet for CMIS queries, we need to perform
         // a workaround for the paging information we return in our list of results
         //
         /*
-        if (result != null) {
-               docFilter.setStartPage(0);
-               if (totalSize > docFilter.getPageSize()) {
-                       docFilter.setPageSize(totalSize);
-               ((DocumentModelListImpl)result).setTotalSize(totalSize);
-               }
-        }
-        */
-        
+         if (result != null) {
+         docFilter.setStartPage(0);
+         if (totalSize > docFilter.getPageSize()) {
+         docFilter.setPageSize(totalSize);
+         ((DocumentModelListImpl)result).setTotalSize(totalSize);
+         }
+         }
+         */
+
         return result;
     }
-    
+
     private String logException(Exception e, String msg) {
-       String result = null;
-       
-       String exceptionMessage = e.getMessage();
-       exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
+        String result = null;
+
+        String exceptionMessage = e.getMessage();
+        exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
         result = msg = msg + ". Caught exception:" + exceptionMessage;
-        
+
         if (logger.isTraceEnabled() == true) {
-               logger.error(msg, e);
+            logger.error(msg, e);
         } else {
-               logger.error(msg);
+            logger.error(msg);
         }
-       
-       return result;
+
+        return result;
     }
-    
+
     /**
      * update given document in the Nuxeo repository
      *
      * @param ctx service context under which this method is invoked
-     * @param csid
-     *            of the document
-     * @param handler
-     *            should be used by the caller to provide and transform the
-     *            document
+     * @param csid of the document
+     * @param handler should be used by the caller to provide and transform the
+     * document
      * @throws BadRequestException
      * @throws DocumentNotFoundException
-     * @throws TransactionException if the transaction times out or otherwise cannot be successfully completed
+     * @throws TransactionException if the transaction times out or otherwise
+     * cannot be successfully completed
      * @throws DocumentException
      */
     @Override
@@ -1072,7 +1122,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             throw new IllegalArgumentException(
                     "RepositoryJavaClient.update: document handler is missing.");
         }
-        
+
         RepositoryInstance repoSession = null;
         try {
             handler.prepare(Action.UPDATE);
@@ -1082,30 +1132,30 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             try {
                 doc = repoSession.getDocument(docRef);
             } catch (ClientException ce) {
-               String msg = logException(ce, "Could not find document to update with CSID=" + csid);
+                String msg = logException(ce, "Could not find document to update with CSID=" + csid);
                 throw new DocumentNotFoundException(msg, ce);
             }
             // Check for a versioned document, and check In and Out before we proceed.
-            if(((DocumentModelHandler) handler).supportsVersioning()) {
-               /* Once we advance to 5.5 or later, we can add this. 
-                * See also https://jira.nuxeo.com/browse/NXP-8506
-               if(!doc.isVersionable()) {
-                       throw new DocumentException("Configuration for: "
-                                       +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
-               }
-                */
-               /* Force a version number - Not working. Apparently we need to configure the uid schema??
-                   if(doc.getProperty("uid","major_version") == null) {
-                           doc.setProperty("uid","major_version",1);
-                   }
-                   if(doc.getProperty("uid","minor_version") == null) {
-                           doc.setProperty("uid","minor_version",0);
-                   }
-                   */
-               doc.checkIn(VersioningOption.MINOR, null); 
-               doc.checkOut();
-            }
-            
+            if (((DocumentModelHandler) handler).supportsVersioning()) {
+                /* Once we advance to 5.5 or later, we can add this. 
+                 * See also https://jira.nuxeo.com/browse/NXP-8506
+                 if(!doc.isVersionable()) {
+                 throw new DocumentException("Configuration for: "
+                 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
+                 }
+                 */
+                /* Force a version number - Not working. Apparently we need to configure the uid schema??
+                 if(doc.getProperty("uid","major_version") == null) {
+                 doc.setProperty("uid","major_version",1);
+                 }
+                 if(doc.getProperty("uid","minor_version") == null) {
+                 doc.setProperty("uid","minor_version",0);
+                 }
+                 */
+                doc.checkIn(VersioningOption.MINOR, null);
+                doc.checkOut();
+            }
+
             //
             // Set reposession to handle the document
             //
@@ -1119,7 +1169,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             throw bre;
         } catch (DocumentException de) {
             throw de;
-        } catch (WebApplicationException wae){
+        } catch (WebApplicationException wae) {
             throw wae;
         } catch (Exception e) {
             if (logger.isDebugEnabled()) {
@@ -1132,13 +1182,15 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             }
         }
     }
-    
+
     /**
      * Save a documentModel to the Nuxeo repository.
+     *
      * @param ctx service context under which this method is invoked
      * @param repoSession
      * @param docModel the document to save
-     * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
+     * @param fSaveSession if TRUE, will call CoreSession.save() to save
+     * accumulated changes.
      * @throws ClientException
      * @throws DocumentException
      */
@@ -1152,7 +1204,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         try {
             repoSession.saveDocument(docModel);
             if (fSaveSession) {
-               repoSession.save();
+                repoSession.save();
             }
         } catch (ClientException ce) {
             throw ce;
@@ -1164,28 +1216,28 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         }
     }
 
-
     /**
      * Save a list of documentModels to the Nuxeo repository.
-     * 
+     *
      * @param ctx service context under which this method is invoked
      * @param repoSession a repository session
      * @param docModelList a list of document models
-     * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
+     * @param fSaveSession if TRUE, will call CoreSession.save() to save
+     * accumulated changes.
      * @throws ClientException
      * @throws DocumentException
      */
     public void saveDocListWithoutHandlerProcessing(
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
             RepositoryInstance repoSession,
-            DocumentModelList docList, 
+            DocumentModelList docList,
             boolean fSaveSession)
             throws ClientException, DocumentException {
         try {
             DocumentModel[] docModelArray = new DocumentModel[docList.size()];
             repoSession.saveDocuments(docList.toArray(docModelArray));
             if (fSaveSession) {
-               repoSession.save();
+                repoSession.save();
             }
         } catch (ClientException ce) {
             throw ce;
@@ -1197,9 +1249,9 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
 
     /**
      * delete a document from the Nuxeo repository
+     *
      * @param ctx service context under which this method is invoked
-     * @param id
-     *            of the document
+     * @param id of the document
      * @throws DocumentException
      */
     @Override
@@ -1218,17 +1270,17 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         }
         RepositoryInstance repoSession = null;
         try {
-               handler.prepare(Action.DELETE);
+            handler.prepare(Action.DELETE);
             repoSession = getRepositorySession(ctx);
             DocumentWrapper<DocumentModel> wrapDoc = null;
             try {
-               DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
-                   wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
-                   ((DocumentModelHandler) handler).setRepositorySession(repoSession);
-                   handler.handle(Action.DELETE, wrapDoc);
+                DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
+                wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
+                ((DocumentModelHandler) handler).setRepositorySession(repoSession);
+                handler.handle(Action.DELETE, wrapDoc);
                 repoSession.removeDocument(docRef);
             } catch (ClientException ce) {
-               String msg = logException(ce, "Could not find document to delete with CSID=" + id);
+                String msg = logException(ce, "Could not find document to delete with CSID=" + id);
                 throw new DocumentNotFoundException(msg, ce);
             }
             repoSession.save();
@@ -1268,15 +1320,15 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         RepositoryInstance repoSession = null;
         String domainId = null;
         try {
-               //
-               // Open a connection to the domain's repo/db
-               //
-               String repoName = repositoryDomain.getRepositoryName();
+            //
+            // Open a connection to the domain's repo/db
+            //
+            String repoName = repositoryDomain.getRepositoryName();
             repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
-               //
-               // First create the top-level domain directory
-               //
-               String domainName = repositoryDomain.getStorageName();
+            //
+            // First create the top-level domain directory
+            //
+            String domainName = repositoryDomain.getStorageName();
             DocumentRef parentDocRef = new PathRef("/");
             DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
             DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
@@ -1291,20 +1343,20 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
             //
             DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
-                       NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
+                    NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
             workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
             workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
                     + domainDoc.getPathAsString());
             workspacesRoot = repoSession.createDocument(workspacesRoot);
             String workspacesRootId = workspacesRoot.getId();
             repoSession.save();
-            
+
             if (logger.isDebugEnabled()) {
                 logger.debug("Created tenant domain name=" + domainName
-                        + " id=" + domainId + " " +
-                        NuxeoUtils.Workspaces + " id=" + workspacesRootId);
-                logger.debug("Path to Domain: "+domainDoc.getPathAsString());
-                logger.debug("Path to Workspaces root: "+workspacesRoot.getPathAsString());
+                        + " id=" + domainId + " "
+                        NuxeoUtils.Workspaces + " id=" + workspacesRootId);
+                logger.debug("Path to Domain: " + domainDoc.getPathAsString());
+                logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
             }
         } catch (Exception e) {
             if (logger.isDebugEnabled()) {
@@ -1316,7 +1368,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                 releaseRepositorySession(null, repoSession);
             }
         }
-        
+
         return domainId;
     }
 
@@ -1324,61 +1376,61 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
     public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
         String domainId = null;
         RepositoryInstance repoSession = null;
-        
+
         String repoName = repositoryDomain.getRepositoryName();
         String domainStorageName = repositoryDomain.getStorageName();
         if (domainStorageName != null && !domainStorageName.isEmpty()) {
-               try {
-                   repoSession = getRepositorySession(repoName);
-                   DocumentRef docRef = new PathRef("/" + domainStorageName);
-                   DocumentModel domain = repoSession.getDocument(docRef);
-                   domainId = domain.getId();
-               } catch (Exception e) {
-                   if (logger.isTraceEnabled()) {
-                       logger.trace("Caught exception ", e);  // The document doesn't exist, this let's us know we need to create it
-                   }
-                   //there is no way to identify if document does not exist due to
-                   //lack of typed exception for getDocument method
-                   return null;
-               } finally {
-                   if (repoSession != null) {
-                       releaseRepositorySession(null, repoSession);
-                   }
-               }
+            try {
+                repoSession = getRepositorySession(repoName);
+                DocumentRef docRef = new PathRef("/" + domainStorageName);
+                DocumentModel domain = repoSession.getDocument(docRef);
+                domainId = domain.getId();
+            } catch (Exception e) {
+                if (logger.isTraceEnabled()) {
+                    logger.trace("Caught exception ", e);  // The document doesn't exist, this let's us know we need to create it
+                }
+                //there is no way to identify if document does not exist due to
+                //lack of typed exception for getDocument method
+                return null;
+            } finally {
+                if (repoSession != null) {
+                    releaseRepositorySession(null, repoSession);
+                }
+            }
         }
-        
+
         return domainId;
     }
 
     /*
-        * Returns the workspaces root directory for a given domain.
-        */
-       private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
-                       String domainName) throws Exception {
-               DocumentModel result = null;
-               
-               String domainPath = "/" + domainName;
-               DocumentRef parentDocRef = new PathRef(domainPath);
-               DocumentModelList domainChildrenList = repoSession.getChildren(
-                               parentDocRef);
-               Iterator<DocumentModel> witer = domainChildrenList.iterator();
-               while (witer.hasNext()) {
-                       DocumentModel childNode = witer.next();
-                       if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
-                               result = childNode;
-                               logger.trace("Found workspaces directory at: " + result.getPathAsString());
-                               break;
-                       }
-               }
-               
-               if (result == null) {
-                       throw new ClientException("Could not find workspace root directory in: "
-                                       + domainPath);
-               }
-
-               return result;
-       }
-    
+     * Returns the workspaces root directory for a given domain.
+     */
+    private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
+            String domainName) throws Exception {
+        DocumentModel result = null;
+
+        String domainPath = "/" + domainName;
+        DocumentRef parentDocRef = new PathRef(domainPath);
+        DocumentModelList domainChildrenList = repoSession.getChildren(
+                parentDocRef);
+        Iterator<DocumentModel> witer = domainChildrenList.iterator();
+        while (witer.hasNext()) {
+            DocumentModel childNode = witer.next();
+            if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
+                result = childNode;
+                logger.trace("Found workspaces directory at: " + result.getPathAsString());
+                break;
+            }
+        }
+
+        if (result == null) {
+            throw new ClientException("Could not find workspace root directory in: "
+                    + domainPath);
+        }
+
+        return result;
+    }
+
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
      */
@@ -1387,17 +1439,17 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         RepositoryInstance repoSession = null;
         String workspaceId = null;
         try {
-               String repoName = repositoryDomain.getRepositoryName();
+            String repoName = repositoryDomain.getRepositoryName();
             repoSession = getRepositorySession(repoName);
-            
+
             String domainStorageName = repositoryDomain.getStorageName();
             DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
             if (logger.isTraceEnabled()) {
-                   for (String facet : parentDoc.getFacets()) {
-                       logger.trace("Facet: " + facet);
-                   }
+                for (String facet : parentDoc.getFacets()) {
+                    logger.trace("Facet: " + facet);
+                }
             }
-            
+
             DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
                     workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
             doc.setPropertyValue("dc:title", workspaceName);
@@ -1430,10 +1482,10 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
     @Deprecated
     public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
         String workspaceId = null;
-        
+
         RepositoryInstance repoSession = null;
         try {
-            repoSession = getRepositorySession((ServiceContext)null);
+            repoSession = getRepositorySession((ServiceContext) null);
             DocumentRef docRef = new PathRef(
                     "/" + tenantDomain
                     + "/" + NuxeoUtils.Workspaces
@@ -1452,63 +1504,64 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
                 releaseRepositorySession(null, repoSession);
             }
         }
-        
+
         return workspaceId;
     }
 
     public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
-       return getRepositorySession(ctx, ctx.getRepositoryName());
+        return getRepositorySession(ctx, ctx.getRepositoryName());
     }
-    
+
     public RepositoryInstance getRepositorySession(String repoName) throws Exception {
-       return getRepositorySession(null, repoName);
+        return getRepositorySession(null, repoName);
     }
-    
+
     /**
-     * Gets the repository session. - Package access only.  If the 'ctx' param is null then the repo name must be non-mull and vice-versa
+     * Gets the repository session. - Package access only. If the 'ctx' param is
+     * null then the repo name must be non-mull and vice-versa
      *
      * @return the repository session
      * @throws Exception the exception
      */
     public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
-       RepositoryInstance repoSession = null;
-       
-       Profiler profiler = new Profiler("getRepositorySession():", 2);
-       profiler.start();
-       //
-       // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
-       //
+        RepositoryInstance repoSession = null;
+
+        Profiler profiler = new Profiler("getRepositorySession():", 2);
+        profiler.start();
+        //
+        // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
+        //
         if (ctx != null) {
-               repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
-               repoSession = (RepositoryInstance)ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
+            repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
+            repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
         } else if (repoName == null || repoName.trim().isEmpty()) {
-               String errMsg = String.format("We can't get a connection to the Nuxeo repo because the service context passed in was null and no repository name was passed in either.");
-               logger.error(errMsg);
-               throw new Exception(errMsg);
-        }        
+            String errMsg = String.format("We can't get a connection to the Nuxeo repo because the service context passed in was null and no repository name was passed in either.");
+            logger.error(errMsg);
+            throw new Exception(errMsg);
+        }
         //
         // If we couldn't find a repoSession from the service context (or the context was null) then we need to create a new one using
         // just the repo name
         //
         if (repoSession == null) {
-               NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
-               repoSession = client.openRepository(repoName);
+            NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
+            repoSession = client.openRepository(repoName);
         } else {
             if (logger.isDebugEnabled() == true) {
-               logger.warn("Reusing the current context's repository session.");
-            }          
+                logger.warn("Reusing the current context's repository session.");
+            }
         }
-        
+
         if (logger.isTraceEnabled()) {
             logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
         }
-        
+
         profiler.stop();
-        
+
         if (ctx != null) {
-               ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
+            ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
         }
-        
+
         return repoSession;
     }
 
@@ -1522,10 +1575,10 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
             NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
             // release session
             if (ctx != null) {
-               ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
-               if (ctx.getCurrentRepositorySession() == null) {
+                ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
+                if (ctx.getCurrentRepositorySession() == null) {
                     client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
-               }
+                }
             } else {
                 client.releaseRepository(repoSession); //repo session was acquired without a service context
             }
@@ -1539,12 +1592,11 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         }
     }
 
-       @Override
-       public void doWorkflowTransition(ServiceContext ctx, String id,
-                       DocumentHandler handler, TransitionDef transitionDef)
-                       throws BadRequestException, DocumentNotFoundException,
-                       DocumentException {
-               // This is a placeholder for when we change the StorageClient interface to treat workflow transitions as 1st class operations like 'get', 'create', 'update, 'delete', etc
-       }
-                
+    @Override
+    public void doWorkflowTransition(ServiceContext ctx, String id,
+            DocumentHandler handler, TransitionDef transitionDef)
+            throws BadRequestException, DocumentNotFoundException,
+            DocumentException {
+        // This is a placeholder for when we change the StorageClient interface to treat workflow transitions as 1st class operations like 'get', 'create', 'update, 'delete', etc
+    }
 }