]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-5504: The refNames in relationship records are now updated when their correspo...
authorRichard Millet <richard.millet@berkeley.edu>
Thu, 20 Sep 2012 06:41:33 +0000 (23:41 -0700)
committerRichard Millet <richard.millet@berkeley.edu>
Thu, 20 Sep 2012 06:41:33 +0000 (23:41 -0700)
services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java
services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClient.java
services/common/src/main/java/org/collectionspace/services/common/ResourceBase.java
services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java
services/common/src/main/java/org/collectionspace/services/common/relation/RelationUtils.java
services/common/src/main/java/org/collectionspace/services/common/vocabulary/RefNameServiceUtils.java
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandlerImpl.java
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RepositoryJavaClientImpl.java

index 4c0894de049bbc9d40bf99a763fa352910535f67..afe733d0c1f56da5dfdd7b9d986b97bf93a43a70 100644 (file)
@@ -37,6 +37,7 @@ import org.collectionspace.services.common.context.ServiceContext;
 import org.collectionspace.services.common.document.DocumentException;
 import org.collectionspace.services.common.document.DocumentFilter;
 import org.collectionspace.services.common.document.DocumentWrapper;
+import org.collectionspace.services.common.repository.RepositoryClient;
 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
@@ -295,6 +296,43 @@ public abstract class AuthorityItemDocumentModelHandler<AICommon>
         handleInAuthority(wrapDoc.getWrappedObject());        
     }
 
+    /*
+     * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
+     * has changed, then we need to updated all the records that use that refname with the new/updated version
+     * 
+     * (non-Javadoc)
+     * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
+     */
+    public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
+       // Must call our super class' version first
+       super.completeUpdate(wrapDoc);
+       
+       //
+       // Look for and update authority references with the updated refName
+       //
+        if (hasRefNameUpdate() == true) {
+            // We have work to do.
+            if (logger.isDebugEnabled()) {
+                final String EOL = System.getProperty("line.separator");
+                logger.debug("Need to find and update references to authority item." + EOL
+                        + "   Old refName" + oldRefNameOnUpdate + EOL
+                        + "   New refName" + newRefNameOnUpdate);
+            }
+            ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
+            RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
+            RepositoryInstance repoSession = this.getRepositorySession();
+            
+            // Update all the existing records that have a field with the old refName in it
+            int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
+                    oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
+            
+            // Finished so log a message.
+            if (logger.isDebugEnabled()) {
+                logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
+            }
+        }
+    }
+    
     /*
      * Note that the Vocabulary service's document-model for items overrides this method.
      */
@@ -311,50 +349,15 @@ public abstract class AuthorityItemDocumentModelHandler<AICommon>
      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
      */
     @Override
+    // FIXME: Once we remove the refName field from the authority item schemas, we can remove this override method since our super does everthing for us now.
+    @Deprecated
     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
-        // First, get a copy of the old displayName
-        // oldDisplayNameOnUpdate = (String) wrapDoc.getWrappedObject().getProperty(authorityItemCommonSchemaName,
-        //        AuthorityItemJAXBSchema.DISPLAY_NAME);
-        oldDisplayNameOnUpdate = getPrimaryDisplayName(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName,
-                getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
-        oldRefNameOnUpdate = (String) wrapDoc.getWrappedObject().getProperty(authorityItemCommonSchemaName,
-                AuthorityItemJAXBSchema.REF_NAME);
+       // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
         super.handleUpdate(wrapDoc);
-
-        // Now, check the new display and handle the refname update.
-        String newDisplayName = (String) getPrimaryDisplayName(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName,
-                authorityItemTermGroupXPathBase,
-                AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
-        if (newDisplayName != null && !newDisplayName.equals(oldDisplayNameOnUpdate)) {
-            // Need to update the refName, and then fix all references.
-            newRefNameOnUpdate = handleItemRefNameUpdateForDisplayName(wrapDoc.getWrappedObject(), newDisplayName);
-        } else {
-            // Mark as not needing attention in completeUpdate phase.
-            newRefNameOnUpdate = null;
-            oldRefNameOnUpdate = null;
-        }
-    }
-
-    /**
-     * Handle refName updates for changes to display name.
-     * Assumes refName is already correct. Just ensures it is right.
-     *
-     * @param docModel the doc model
-     * @param newDisplayName the new display name
-     * @throws Exception the exception
-     */
-    protected String handleItemRefNameUpdateForDisplayName(DocumentModel docModel,
-            String newDisplayName) throws Exception {
-        RefName.AuthorityItem authItem = RefName.AuthorityItem.parse(oldRefNameOnUpdate);
-        if (authItem == null) {
-            String err = "Authority Item has illegal refName: " + oldRefNameOnUpdate;
-            logger.debug(err);
-            throw new IllegalArgumentException(err);
+        if (this.hasRefNameUpdate() == true) {
+               DocumentModel docModel = wrapDoc.getWrappedObject();
+            docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, this.newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what is in the collectionspace_core:refName field               
         }
-        authItem.displayName = newDisplayName;
-        String updatedRefName = authItem.toString();
-        docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, updatedRefName); // Maybe set collectionspace_core schema here?
-        return updatedRefName;
     }
     
     /**
index d5bd51fa730cb9838fd07c6ee980fd8042b353f2..19ddf315c6aa80babfeba535792ce4f78d71512a 100644 (file)
@@ -37,14 +37,30 @@ import org.collectionspace.services.common.authorityref.AuthorityRefList;
 public interface CollectionSpaceClient<CLT, REQUEST_TYPE, RESPONSE_TYPE, P extends CollectionSpaceProxy<CLT>> {
 
     public final static String COLLECTIONSPACE_CORE_SCHEMA = "collectionspace_core";
+    
     public final static String COLLECTIONSPACE_CORE_TENANTID = "tenantId";
+    public final static String CORE_TENANTID = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_TENANTID;
+    
     public final static String COLLECTIONSPACE_CORE_URI = "uri";
+    public final static String CORE_URI = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_URI;    
+    
     public final static String COLLECTIONSPACE_CORE_REFNAME = "refName";
+    public final static String CORE_REFNAME = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_REFNAME;
+    
     public final static String COLLECTIONSPACE_CORE_CREATED_AT = "createdAt";
+    public final static String CORE_CREATED_AT = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_CREATED_AT;
+    
     public final static String COLLECTIONSPACE_CORE_UPDATED_AT = "updatedAt";
+    public final static String CORE_UPDATED_AT = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_UPDATED_AT;
+    
     public final static String COLLECTIONSPACE_CORE_CREATED_BY = "createdBy";
+    public final static String CORE_CREATED_BY = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_CREATED_BY;
+
     public final static String COLLECTIONSPACE_CORE_UPDATED_BY = "updatedBy";
+    public final static String CORE_UPDATED_BY = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_UPDATED_BY;
+
     public final static String COLLECTIONSPACE_CORE_WORKFLOWSTATE = "workflowState";
+    public final static String CORE_WORKFLOWSTATE = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_WORKFLOWSTATE;
     
     public static final String AUTH_PROPERTY = "cspace.auth";
     public static final String PASSWORD_PROPERTY = "cspace.password";
index 7034abfd89092f1724d110ec38300d87955d7045..499149492c05a61665a509d7089834d55de7ccb7 100644 (file)
@@ -326,7 +326,7 @@ public abstract class ResourceBase
 \r
     protected AbstractCommonList finish_getList(ServiceContext ctx, DocumentHandler handler) {\r
         try {\r
-            getRepositoryClient(ctx).getFiltered(ctx, handler);\r
+            getRepositoryClient(ctx).getFiltered(ctx, handler); // REM - Side effect of this call sets the handler's common part list value\r
             return (AbstractCommonList) handler.getCommonPartList();\r
         } catch (Exception e) {\r
             throw bigReThrow(e, ServiceMessages.LIST_FAILED);\r
index c839030a60a6e5281de3c501f7910bcef76b8cc1..7c1b4d4033b34e507d92c3eadd60863751af2128 100644 (file)
@@ -21,6 +21,7 @@ import java.util.ArrayList;
 import java.util.List;\r
 import javax.ws.rs.core.MultivaluedMap;\r
 import org.collectionspace.authentication.AuthN;\r
+import org.collectionspace.services.client.CollectionSpaceClient;\r
 import org.collectionspace.services.client.IClientQueryParams;\r
 import org.collectionspace.services.common.context.ServiceContext;\r
 \r
@@ -43,7 +44,8 @@ public class DocumentFilter {
     /** The order by clause. */\r
     protected String orderByClause;    // Filtering clause. Omit the "ORDER BY".\r
     public static final String EMPTY_ORDER_BY_CLAUSE = "";\r
-    public static final String ORDER_BY_LAST_UPDATED = "collectionspace_core:updatedAt DESC";\r
+    public static final String ORDER_BY_LAST_UPDATED = CollectionSpaceClient.CORE_UPDATED_AT + " DESC";\r
+    public static final String ORDER_BY_CREATED_AT = CollectionSpaceClient.CORE_CREATED_AT + " DESC";\r
     /** The start page. */\r
     protected int startPage;           // Pagination offset for list results\r
     /** The page size. */\r
index b19a685a5c686420304d0ccf0542562becd4674b..c0c3ccf51766bbe4f40d79cf5c64a3de0845db7f 100644 (file)
@@ -1,19 +1,67 @@
 package org.collectionspace.services.common.relation;
 
+import org.collectionspace.services.client.CollectionSpaceClient;
+import org.collectionspace.services.client.IRelationsManager;
 import org.collectionspace.services.client.PoxPayloadIn;
 import org.collectionspace.services.client.PoxPayloadOut;
-import org.collectionspace.services.common.api.Tools;
 import org.collectionspace.services.common.context.ServiceContext;
-import org.collectionspace.services.common.document.DocumentFilter;
-import org.collectionspace.services.common.query.QueryContext;
+import org.collectionspace.services.common.document.DocumentException;
+import org.collectionspace.services.common.document.DocumentNotFoundException;
 import org.collectionspace.services.common.repository.RepositoryClient;
-import org.collectionspace.services.nuxeo.util.NuxeoUtils;
+import org.nuxeo.ecm.core.api.ClientException;
+import org.nuxeo.ecm.core.api.DocumentModel;
 import org.nuxeo.ecm.core.api.DocumentModelList;
 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-public class RelationUtils {
+public class RelationUtils {   
+    private static final Logger logger = LoggerFactory.getLogger(RelationUtils.class);
+       
+       private static final int DEFAUT_PAGE_SIZE = 1000;
+
+       /*
+        * Performs an NXQL query to find refName references in relationship records.
+        */
+       private static DocumentModelList findRelationsWithRefName(
+            RepositoryInstance repoSession,
+                       String refName,
+                       String targetField,
+                       String orderByField,
+            int pageSize,
+            int pageNum,
+            boolean computeTotal) {
+               DocumentModelList result = null;
+               
+               String escapedRefName = refName.replace("'", "\\'"); // We need to escape single quotes for NXQL
+               String query = String.format("SELECT * FROM %s WHERE %s:%s = '%s'", // e.g., "SELECT * FROM Relation WHERE relations_common:subjectRefName = 'urn:cspace:core.collectionspace.org:placeauthorities:name(place):item:name(Amystan1348082103923)\'Amystan\''"
+                               IRelationsManager.DOC_TYPE,
+                               IRelationsManager.SERVICE_COMMONPART_NAME,
+                               targetField,
+                               escapedRefName);
+               
+               if (logger.isDebugEnabled() == true) {
+                       logger.debug(String.format("findRelationsWithRefName NXQL query is %s", query));
+               }
 
-    private static void updateRefNamesInRelations(
+               try {
+                       result = repoSession.query(query, null,
+                               pageSize, pageNum, computeTotal);
+               } catch (ClientException e) {
+                       if (logger.isDebugEnabled() == true) {
+                               logger.debug(String.format("Exception caught while looking for refNames in relationship records for updating: refName %s",
+                                               refName), e);
+                       }
+               }
+               
+               return result;
+       }
+       
+       /*
+        * Find all the relationship records with the targetField (either subjectRefName or objectRefName) set to the old refName and
+        * update it to contain the new refName.
+        */
+    public static void updateRefNamesInRelations(
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
             RepositoryInstance repoSession,
@@ -21,19 +69,36 @@ public class RelationUtils {
             String oldRefName,
             String newRefName) {
        
-        DocumentFilter filter = new DocumentFilter();
-        String oldOrderBy = filter.getOrderByClause();
-        if (Tools.isEmpty(oldOrderBy) == true){
-            filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
-        }
-        QueryContext queryContext = new QueryContext(ctx, handler);
-
-        RepositoryInstance repoSession = null;
-        
-        DocumentModelList docList = null;
-        String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
-        docList = repoSession.query(query);
+                       DocumentModelList docModelList = findRelationsWithRefName( // FIXME: REM - Step through the pages correctly.
+                                       repoSession,
+                                       oldRefName,
+                                       targetField,
+                                       CollectionSpaceClient.CORE_CREATED_AT,
+                                       DEFAUT_PAGE_SIZE,
+                                       0,
+                                       true);
+                       
+                       if (docModelList != null) {
+                               for (DocumentModel docModel : docModelList) {
+                                       try {
+                                               docModel.setProperty(IRelationsManager.SERVICE_COMMONPART_NAME, targetField, newRefName);
+                                               repoSession.saveDocument(docModel);
+                                       } catch (ClientException e) {
+                                               logger.error(String.format("Could not update field '%s' with updated refName '%s' for relations record CSID=%s",
+                                                               targetField, newRefName, docModel.getName()));
+                                       }
+                               }
+                               //
+                               // Flush the results
+                               //
+                               try {
+                                       repoSession.save();
+                               } catch (ClientException e) {
+                                       // TODO Auto-generated catch block
+                                       logger.error("Could not flush results of relation-refName payload updates to Nuxeo repository");
+                               }
+                       } else {
+                               // if docModelList was null then we already wrote out the error message to the logs
+                       }
     }
-       
-
 }
index 3b004d7da1cc49c58b60910aff05f8afdf4736de..67065302fffd776b729d1c329affc4e7d91bb5ce 100644 (file)
@@ -39,6 +39,7 @@ import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
 import org.slf4j.Logger;\r
 import org.slf4j.LoggerFactory;\r
 \r
+import org.collectionspace.services.client.CollectionSpaceClient;\r
 import org.collectionspace.services.client.IRelationsManager;\r
 import org.collectionspace.services.client.PoxPayloadIn;\r
 import org.collectionspace.services.client.PoxPayloadOut;\r
@@ -61,6 +62,7 @@ import org.collectionspace.services.common.document.DocumentNotFoundException;
 import org.collectionspace.services.common.document.DocumentUtils;\r
 import org.collectionspace.services.common.document.DocumentWrapper;\r
 import org.collectionspace.services.common.query.QueryManager;\r
+import org.collectionspace.services.common.relation.RelationUtils;\r
 import org.collectionspace.services.common.repository.RepositoryClient;\r
 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;\r
 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;\r
@@ -68,7 +70,6 @@ import org.collectionspace.services.common.security.SecurityUtils;
 import org.collectionspace.services.config.service.ServiceBindingType;\r
 import org.collectionspace.services.jaxb.AbstractCommonList;\r
 import org.collectionspace.services.nuxeo.util.NuxeoUtils;\r
-import org.jboss.resteasy.spi.ResteasyProviderFactory;\r
 \r
 /**\r
  * RefNameServiceUtils is a collection of services utilities related to refName\r
@@ -209,7 +210,6 @@ public class RefNameServiceUtils {
     private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class);\r
     private static ArrayList<String> refNameServiceTypes = null;\r
 \r
-    \r
     public static void updateRefNamesInRelations(\r
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,\r
             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,\r
@@ -219,13 +219,12 @@ public class RefNameServiceUtils {
        //\r
        // First, look for and update all the places where the refName is the "subject" of the relationship\r
        //\r
-       updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName);\r
+       RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName);\r
        \r
        //\r
        // Next, look for and update all the places where the refName is the "object" of the relationship\r
        //\r
-       updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName);\r
-       \r
+       RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName);\r
     }\r
     \r
     public static List<AuthRefConfigInfo> getConfiguredAuthorityRefs(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {\r
@@ -396,11 +395,12 @@ public class RefNameServiceUtils {
         int currentPage = 0;\r
         int docsInCurrentPage = 0;\r
         final String WHERE_CLAUSE_ADDITIONS_VALUE = null;\r
-        final String ORDER_BY_VALUE = "collectionspace_core:createdAt";\r
+        final String ORDER_BY_VALUE = CollectionSpaceClient.CORE_CREATED_AT; // "collectionspace_core:createdAt";\r
 \r
-        if (!(repoClient instanceof RepositoryJavaClientImpl)) {\r
+        if (repoClient instanceof RepositoryJavaClientImpl == false) {\r
             throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!");\r
         }\r
+        \r
         try { // REM - How can we deal with transaction and timeout issues here?\r
             final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP;\r
             DocumentModelList docList;\r
@@ -478,7 +478,7 @@ public class RefNameServiceUtils {
 \r
         ArrayList<String> docTypes = new ArrayList<String>();\r
 \r
-        String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings,\r
+        String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings, // REM - Side effect that docTypes array gets set.  Any others?\r
                 queriedServiceBindings, authRefFieldsByService);\r
         if (query == null) { // found no authRef fields - nothing to query\r
             return null;\r
@@ -652,7 +652,7 @@ public class RefNameServiceUtils {
 \r
             ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();\r
             try {\r
-                findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, foundProps);\r
+                findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, foundProps); // REM - side effect that foundProps is set\r
                 for (RefNameServiceUtils.AuthRefInfo ari : foundProps) {\r
                     if (ilistItem != null) {\r
                         if (nRefsFoundInDoc == 0) {    // First one?\r
index 98ab558c6eac865480880797208b1e0c479f9b90..1000f7b7a70acca80a57bd3d49b3575810b898c1 100644 (file)
@@ -37,6 +37,7 @@ import org.collectionspace.services.client.PoxPayloadOut;
 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
 import org.collectionspace.services.common.api.RefName;
 import org.collectionspace.services.common.api.RefName.RefNameInterface;
+import org.collectionspace.services.common.api.Tools;
 import org.collectionspace.services.common.authorityref.AuthorityRefList;
 import org.collectionspace.services.common.context.ServiceContext;
 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
@@ -79,6 +80,9 @@ public abstract class DocumentModelHandler<T, TL>
     private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
     private RepositoryInstance repositorySession;
 
+    protected String oldRefNameOnUpdate = null;
+    protected String newRefNameOnUpdate = null;
+    
     /*
      * Map Nuxeo's life cycle object to our JAX-B based life cycle object
      */
@@ -369,14 +373,9 @@ public abstract class DocumentModelHandler<T, TL>
        
                if (action == Action.CREATE || action == Action.UPDATE) {
             //
-            // Add the resource's refname
+            // Add/update the resource's refname
             //
-            RefNameInterface refname = getRefName(ctx, documentModel); // Sub-classes may override the getRefName() method called here.
-            if (refname != null) {
-               String refnameStr = refname.toString();
-                   documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
-                               CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, refnameStr);
-            }
+                       handleRefNameChanges(ctx, documentModel);
             //
             // Add updatedAt timestamp and updateBy user
             //
@@ -386,6 +385,38 @@ public abstract class DocumentModelHandler<T, TL>
                                        CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
                }               
     }
+    
+    protected boolean hasRefNameUpdate() {
+       boolean result = false;
+       
+       if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
+               if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
+                       result = true; // refNames are different so updates are needed
+               }
+       }
+       
+       return result;
+    }
+    
+    private void handleRefNameChanges(ServiceContext ctx, DocumentModel docModel) throws ClientException {
+       // First get the old refName
+       this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
+                       CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
+       // Next, get the new refName
+        RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
+        if (refName != null) {
+               this.newRefNameOnUpdate = refName.toString();
+        } else {
+               logger.error(String.format("refName for document is missing.  Document CSID=%s", docModel.getName()));
+        }
+        //
+        // Set the refName if it is an update or if the old refName was empty or null
+        //
+        if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
+               docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
+                               CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
+        }
+    }
         
     /*
      * If we see the "rtSbj" query param then we need to perform a CMIS query.  Currently, we have only one
index 5a19e398d7cbd90feb48811a172b05ea1fa9b7c3..8ae614f17448676110dcc188efba79b1f6c3a220 100644 (file)
@@ -104,9 +104,6 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
     /** The logger. */
     private final Logger logger = LoggerFactory.getLogger(RemoteDocumentModelHandlerImpl.class);
     private final static String CR = "\r\n";
-
-    protected String oldRefNameOnUpdate = null;
-    protected String newRefNameOnUpdate = null;
     
     /* (non-Javadoc)
      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#setServiceContext(org.collectionspace.services.common.context.ServiceContext)
@@ -187,13 +184,15 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
         }
     }
        
-    /* (non-Javadoc)
+    /* NOTE: The authority item doc handler overrides (after calling) this method.  It performs refName updates.  In this
+     * method we just update any and all relationship records that use refNames that have changed.
+     * (non-Javadoc)
      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
      */
     @Override
     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
         DocumentModel docModel = wrapDoc.getWrappedObject();
-        //return at least those document part(s) that were received
+        // We need to return at least those document part(s) and corresponding payloads that were received
         Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
         PoxPayloadIn input = ctx.getInput();
@@ -223,10 +222,12 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
                                        docModel.getName());
                }
         }
-        
+        //
+        //  If the resource's service supports hierarchy then we need to perform a little more work
+        //
         if (supportsHierarchy() == true) {
             handleRelationsPayload(wrapDoc, true); // refNames in relations payload should refer to pre-updated record refName value
-            handleItemRefNameReferenceUpdate(); // if our record's refName changed, we need to update all the references -including relations.
+            handleRefNameReferencesUpdate(); // if our refName changed, we need to update any and all relationship records that used the old one
         }
     }
 
@@ -1387,39 +1388,21 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
 
     /**
      * Checks to see if the refName has changed, and if so, 
-     * uses utilities to find all references and update them.
+     * uses utilities to find all references and update them to use the new refName.
      * @throws Exception 
      */
-    protected void handleItemRefNameReferenceUpdate() throws Exception {
+    protected void handleRefNameReferencesUpdate() throws Exception {
         if (hasRefNameUpdate() == true) {
-            // We have work to do.
-            if (logger.isDebugEnabled()) {
-                final String EOL = System.getProperty("line.separator");
-                logger.debug("Need to find and update references to Item." + EOL
-                        + "   Old refName" + oldRefNameOnUpdate + EOL
-                        + "   New refName" + newRefNameOnUpdate);
-            }
             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
-            
             RepositoryInstance repoSession = this.getRepositorySession();
+            
+            // Update all the relationship records that referred to the old refName
             RefNameServiceUtils.updateRefNamesInRelations(ctx, repoClient, repoSession,
                     oldRefNameOnUpdate, newRefNameOnUpdate);
-            
-            int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
-                    oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
-            
-            // Finished so log a message.
-            if (logger.isDebugEnabled()) {
-                logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
-            }
         }
     }
     
-    protected boolean hasRefNameUpdate() {
-       return (newRefNameOnUpdate != null && oldRefNameOnUpdate != null);
-    }
-
     protected String getRefNameUpdate() {
        String result = null;
        
index 58e9a83003020f4982f3f73e2369ea967df24518..b68c2ad9801a20ff567feac2d69fae8355e99d4c 100644 (file)
@@ -820,7 +820,7 @@ public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn,
         RepositoryInstance repoSession = null;
         try {
             handler.prepare(Action.GET_ALL);
-            repoSession = getRepositorySession(ctx); //Need a refcount here for the repository session?
+            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);