]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-6953: Getting all unit tests passing again after changes for synchronization...
authorremillet <remillet@yahoo.com>
Thu, 2 Jun 2016 21:37:24 +0000 (14:37 -0700)
committerremillet <remillet@yahoo.com>
Thu, 2 Jun 2016 21:37:24 +0000 (14:37 -0700)
15 files changed:
services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/CollectionSpaceIntegrationTest.java
services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/RelationIntegrationTest.java
services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple.xml
services/JaxRsServiceProvider/src/main/resources/log4j.properties
services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityDocumentModelHandler.java
services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java
services/authorization-mgt/import/build.xml
services/client/src/main/java/org/collectionspace/services/client/AbstractPoxServiceClientImpl.java
services/client/src/main/java/org/collectionspace/services/client/AbstractServiceClientImpl.java
services/client/src/main/java/org/collectionspace/services/client/AuthorityClientImpl.java
services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClient.java
services/client/src/main/java/org/collectionspace/services/client/test/AbstractAuthorityServiceTest.java
services/client/src/main/java/org/collectionspace/services/client/test/AbstractServiceTestImpl.java
services/client/src/main/java/org/collectionspace/services/client/test/BaseServiceTest.java
services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandlerImpl.java

index 8fe6645c7cde57ed0adb63960142ea2b3aa65882..534cae94d1db3871364a59c4c311784ac9471e61 100644 (file)
@@ -47,6 +47,8 @@ import org.collectionspace.services.relation.RelationsCommon;
  * The Class CollectionSpaceIntegrationTest.
  */
 public abstract class CollectionSpaceIntegrationTest {
+    protected List<String> allRelationResourceIdsCreated = new ArrayList<String>();
+    protected List<String> allResourceIdsCreated = new ArrayList<String>();
 
        /*
         * Package scoped methods.
index 22eea86d83ebdd5b0022dc4812ddbe95582519ea..aec72528c5c14f075d04cc4dc6543ab1a324cfad 100644 (file)
@@ -33,11 +33,10 @@ import javax.xml.bind.JAXBContext;
 import javax.xml.bind.Marshaller;
 
 import org.testng.Assert;
+import org.testng.annotations.AfterClass;
 import org.testng.annotations.Test;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
 import org.collectionspace.services.client.CollectionObjectClient;
 import org.collectionspace.services.client.DimensionClient;
 import org.collectionspace.services.client.DimensionFactory;
@@ -45,10 +44,8 @@ import org.collectionspace.services.client.PayloadOutputPart;
 import org.collectionspace.services.client.PoxPayloadIn;
 import org.collectionspace.services.client.PoxPayloadOut;
 import org.collectionspace.services.collectionobject.CollectionobjectsCommon;
-
 import org.collectionspace.services.client.IntakeClient;
 import org.collectionspace.services.intake.IntakesCommon;
-
 import org.collectionspace.services.client.RelationClient;
 import org.collectionspace.services.client.workflow.WorkflowClient;
 import org.collectionspace.services.dimension.DimensionsCommon;
@@ -76,6 +73,14 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
        private static final int OBJECTS_TO_INTAKE = 1;
        
        
+    @AfterClass(alwaysRun = true)
+    public void cleanUp() {
+       relationClient.cleanup();
+       collectionObjectClient.cleanup();
+       intakeClient.cleanup();
+       dimensionClient.cleanup();
+    }
+    
     /**
      * Object as xml string.
      *
@@ -148,6 +153,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                        Assert.assertEquals(response.getStatus(), Response.Status.CREATED
                                        .getStatusCode());
                        collectionObjectCsid = extractId(response);
+                       collectionObjectClient.addToCleanup(collectionObjectCsid);
                } finally {
                        response.close();
                }
@@ -160,6 +166,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    dimensionCsid1 = extractId(response);
+                   dimensionClient.addToCleanup(dimensionCsid1);
            } finally {
                response.close();
            }
@@ -178,17 +185,21 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    relationCsid1 = extractId(response);
+                   relationClient.addToCleanup(relationCsid1);
            } finally {
                response.close();
            }       
            
            // Now lock the dimension record.
            
-               @SuppressWarnings("unused")
-               Response workflowResponse = dimensionClient.updateWorkflowWithTransition(
-                               dimensionCsid1, WorkflowClient.WORKFLOWTRANSITION_LOCK);
-           System.out.println("Locked dimension record with CSID=" + dimensionCsid1);
-           workflowResponse.close();
+           Response workflowResponse = null;
+           try {
+                       workflowResponse = dimensionClient.updateWorkflowWithTransition(
+                                       dimensionCsid1, WorkflowClient.WORKFLOWTRANSITION_LOCK);
+                   System.out.println("Locked dimension record with CSID=" + dimensionCsid1);
+           } finally {
+               workflowResponse.close();
+           }
            
            // Finally, try to delete the relationship
            
@@ -204,6 +215,14 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                workflowResponse = dimensionClient.updateWorkflowWithTransition(dimensionCsid1, WorkflowClient.WORKFLOWTRANSITION_DELETE);
            System.out.println("Locked dimension record with CSID=" + dimensionCsid1);
            workflowResponse.close();
+           
+           // Now unlock the dimension record so we can cleanup all the records after the test suite completes.
+           try {
+                       workflowResponse = dimensionClient.updateWorkflowWithTransition(
+                                       dimensionCsid1, WorkflowClient.WORKFLOWTRANSITION_UNLOCK);
+           } finally {
+               workflowResponse.close();
+           }
        }
        
        @Test void createCollectionObjectRelationshipToManyDimensions() {
@@ -222,6 +241,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                        Assert.assertEquals(response.getStatus(), Response.Status.CREATED
                                        .getStatusCode());
                        collectionObjectCsid = extractId(response);
+                       collectionObjectClient.addToCleanup(collectionObjectCsid);
                } finally {
                        response.close();
                }
@@ -234,6 +254,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    dimensionCsid1 = extractId(response);
+                   dimensionClient.addToCleanup(dimensionCsid1);
            } finally {
                response.close();
            }
@@ -246,6 +267,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    dimensionCsid2 = extractId(response);
+                   dimensionClient.addToCleanup(dimensionCsid2);
            } finally {
                response.close();
            }
@@ -258,6 +280,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    dimensionCsid3 = extractId(response);
+                   dimensionClient.addToCleanup(dimensionCsid3);
            } finally {
                response.close();
            }
@@ -277,6 +300,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    relationCsid1 = extractId(response);
+                   relationClient.addToCleanup(relationCsid1);
            } finally {
                response.close();
            }
@@ -297,11 +321,12 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            commonPart = multipart.addPart(relationClient.getCommonPartName(), relation);
            // Create the relationship
            response = relationClient.create(multipart);
-           @SuppressWarnings("unused")
+
                String relationCsid2 = null;
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    relationCsid2 = extractId(response);
+                   relationClient.addToCleanup(relationCsid2);
            } finally {
                response.close();
            }
@@ -322,11 +347,12 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            commonPart = multipart.addPart(relationClient.getCommonPartName(), relation);
            // Create the relationship
            response = relationClient.create(multipart);
-           @SuppressWarnings("unused")
+
                String relationCsid3 = null;
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    relationCsid3 = extractId(response);
+                   relationClient.addToCleanup(relationCsid3);
            } finally {
                response.close();
            }               
@@ -351,6 +377,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                        Assert.assertEquals(response.getStatus(), Response.Status.CREATED
                                        .getStatusCode());
                        collectionObjectCsid = extractId(response);
+                       collectionObjectClient.addToCleanup(collectionObjectCsid);
                } finally {
                        response.close();
                }
@@ -383,15 +410,24 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            commonPart = multipart.addPart(relation, MediaType.APPLICATION_XML_TYPE);
            commonPart.setLabel(relationClient.getCommonPartName());
 
-           // Make the call to crate
+           // Make the call to create the relationship
            Response relationresponse = relationClient.create(multipart);
                String relationCsid = null;
            try {
                    Assert.assertEquals(relationresponse.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
                    relationCsid = extractId(response);
+                   relationClient.addToCleanup(relationCsid);
            } finally {
                relationresponse.close();
            }
+           
+           // Now unlock the dimension record so we can cleanup all the records after the test suite completes.
+           try {
+                       workflowResponse = dimensionClient.updateWorkflowWithTransition(
+                                       dimensionCsid, WorkflowClient.WORKFLOWTRANSITION_UNLOCK);
+           } finally {
+               workflowResponse.close();
+           }
        }
        
        @Test
@@ -414,11 +450,11 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                        Assert.assertEquals(response.getStatus(), Response.Status.CREATED
                                        .getStatusCode());
                        collectionObjectCsid = extractId(response);
+                       collectionObjectClient.addToCleanup(collectionObjectCsid);
                } finally {
                        response.close();
                }
            
-           
            // Next, create an Intake object
            IntakesCommon intake = new IntakesCommon();
            fillIntake(intake, createIdentifier());
@@ -433,6 +469,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    intakeCsid = extractId(response);
+                   intakeClient.addToCleanup(intakeCsid);
            } finally {
                response.close();
            }
@@ -453,6 +490,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    relationCsid = extractId(response);
+                   relationClient.addToCleanup(relationCsid);
            } finally {
                response.close();
            }
@@ -538,6 +576,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                                                .getStatusCode());
                                collectionObjectCsid = extractId(response);
                                collectionObjectIDList.add(collectionObjectCsid);
+                               collectionObjectClient.addToCleanup(collectionObjectCsid);
                        } finally {
                                response.close();
                        }
@@ -558,6 +597,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
            try {
                    Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                    intakeCsid = extractId(response);
+                   intakeClient.addToCleanup(intakeCsid);
            } finally {
                response.close();
            }
@@ -580,6 +620,7 @@ public class RelationIntegrationTest extends CollectionSpaceIntegrationTest {
                    try {
                            Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());
                            relationCsid = extractId(response);
+                           relationClient.addToCleanup(relationCsid);
                    } finally {
                        response.close();
                    }
index 8f55a0d81e932b88239cb04a438e01741b5e0c73..badb978d1c0cc208327dbc27856483d4af07a5d8 100644 (file)
@@ -93,6 +93,5 @@
                                <filename>authrefs/res/foo.res.xml</filename>
                         </response>
                </test>
-
        </testGroup>
 </xmlReplay>
index 36e5757db6b249e1e1ed0aced491c3da1c48fcd8..e91afb29bd46f5f57ed734676d7b7cce99196f7e 100644 (file)
@@ -55,7 +55,7 @@ log4j.additivity.perf.collectionspace=false
 log4j.logger.org.collectionspace=WARN
 log4j.logger.org.collectionspace.services.nuxeo.client.java.NuxeoClientEmbedded=ERROR
 log4j.logger.org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl=ERROR
-log4j.logger.org.collectionspace.services.common.security.SecurityInterceptor=TRACE
+log4j.logger.org.collectionspace.services.common.security.SecurityInterceptor=ERROR
 log4j.logger.org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl=DEBUG
 #log4j.logger.org.collectionspace.services.nuxeo.client.java=ERROR
 #log4j.logger.org.collectionspace.services.common.storage.JDBCTools=ERROR
index d6e857432988c3410daabbbf4309e985882b364e..f7cf5993500d6327f91f3e8d347d46c97f66757f 100644 (file)
@@ -134,42 +134,49 @@ public abstract class AuthorityDocumentModelHandler<AuthCommon>
         // Get the rev number of the authority so we can compare with rev number of shared authority
         //
         DocumentModel docModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName, specifier);
-        Long localRev = (Long) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.REV);
-        String shortId = (String) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
-        //
-        // Using the short ID of the local authority, create a URN specifier to retrieve the SAS authority
-        //
-        Specifier sasSpecifier = new Specifier(SpecifierForm.URN_NAME, shortId);
-        PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(ctx, sasSpecifier, getEntityResponseType());
-        //
-        // If the authority on the SAS is newer, synch all the items and then the authority record as well
-        //
-        //
-        Long sasRev = getRevision(sasPayloadIn);
-        if (sasRev > localRev) {
-               //
-               // First, sync all the authority items
-               //
-               syncAllItems(ctx, sasSpecifier);
-               //
-               // Next, sync the authority resource/record itself
-               //
-               AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();
-               ctx.setProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY, AuthorityServiceUtils.DONT_UPDATE_REV); // Don't update the rev number, use the rev number for the SAS instance instead
-               PoxPayloadOut payloadOut = authorityResource.update(ctx, ctx.getResourceMap(), ctx.getUriInfo(), docModel.getName(), 
-                               sasPayloadIn);
-               if (payloadOut != null) {
-                       ctx.setOutput(payloadOut);
-                       result = true;
-               }
-               //
-               // We may need to transition the authority into a replicated state the first time we sync it.
-               //
-               String workflowState = docModel.getCurrentLifeCycleState();
-               if (workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED) == false) {
-                   String authorityCsid = docModel.getName();
-                       authorityResource.updateWorkflowWithTransition(ctx, ctx.getUriInfo(), authorityCsid, WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
-               }
+        if (docModel != null) {
+               Long localRev = (Long) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.REV);
+               String shortId = (String) NuxeoUtils.getProperyValue(docModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
+               //
+               // Using the short ID of the local authority, create a URN specifier to retrieve the SAS authority
+               //
+               Specifier sasSpecifier = new Specifier(SpecifierForm.URN_NAME, shortId);
+               PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(ctx, sasSpecifier, getEntityResponseType());
+               //
+               // If the authority on the SAS is newer, synch all the items and then the authority record as well
+               //
+               //
+               Long sasRev = getRevision(sasPayloadIn);
+               if (sasRev > localRev) {
+                       //
+                       // First, sync all the authority items
+                       //
+                       syncAllItems(ctx, sasSpecifier);
+                       //
+                       // Next, sync the authority resource/record itself
+                       //
+                       AuthorityResource authorityResource = (AuthorityResource) ctx.getResource();
+                       ctx.setProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY, AuthorityServiceUtils.DONT_UPDATE_REV); // Don't update the rev number, use the rev number for the SAS instance instead
+                       PoxPayloadOut payloadOut = authorityResource.update(ctx, ctx.getResourceMap(), ctx.getUriInfo(), docModel.getName(), 
+                                       sasPayloadIn);
+                       if (payloadOut != null) {
+                               ctx.setOutput(payloadOut);
+                               result = true;
+                       }
+                       //
+                       // We may need to transition the authority into a replicated state the first time we sync it.
+                       //
+                       String workflowState = docModel.getCurrentLifeCycleState();
+                       if (workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED) == false) {
+                           String authorityCsid = docModel.getName();
+                               authorityResource.updateWorkflowWithTransition(ctx, ctx.getUriInfo(), authorityCsid, WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
+                       }
+               }
+        } else {
+               String errMsg = String.format("Authority of type '%s' with identifier '%s' does not exist.",
+                               getServiceContext().getServiceName(), specifier.getURNValue());
+               logger.debug(errMsg);
+               throw new DocumentException(errMsg);
         }
         
         return result;
index c924de9a8399f3cc9eb92b043e13187313b11312..7f816c54cd92ba7b4e9d8b8164f0f3b0ec2944a4 100644 (file)
@@ -903,13 +903,18 @@ public abstract class AuthorityItemDocumentModelHandler<AICommon>
                inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
        }
        DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
-       Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
-       if (parentRev == null) {
-               parentRev = new Long(0);
+       if (inAuthorityDocModel != null) {
+               Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
+               if (parentRev == null) {
+                       parentRev = new Long(0);
+               }
+                       parentRev++;
+                       inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
+                       getRepositorySession().saveDocument(inAuthorityDocModel);
+       } else {
+               logger.warn(String.format("Containing authority '%s' for item '%s' has been deleted.  Item is orphaned, so revision numbers can't be updated.",
+                               inAuthorityCsid, documentModel.getName()));
        }
-               parentRev++;
-               inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
-               getRepositorySession().saveDocument(inAuthorityDocModel);
     }    
     
     /**
index 8617b4308b1f078d98eb5cd39b7657b33f21da62..0ea7137cf877b8a319917feb93bcaed9ebb9344a 100644 (file)
     <target name="import-windows" if="osfamily-windows" depends="setup_hibernate.cfg">
         <exec executable="cmd" failonerror="true">
             <arg value="/c" />
-            <arg value=" .bat" /> <!-- To debug, change command here to be 'mvnDebug.bat' -->
+            <arg value="mvn.bat" /> <!-- To debug, change command here to be 'mvnDebug.bat' -->
             <arg value="exec:java" />
             <arg value="-f" />
             <arg value="${basedir}/pom.xml" />
index 99fb6101a89cd5ad751ef54c394649cad500a8cf..70cae8558bda5fa131b6ae69ae8c0fb598efbbc2 100644 (file)
@@ -1,5 +1,8 @@
 package org.collectionspace.services.client;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import javax.ws.rs.core.Response;
 
 import org.testng.Assert;
@@ -15,6 +18,8 @@ public abstract class AbstractPoxServiceClientImpl<CLT extends AbstractCommonLis
        extends AbstractServiceClientImpl<CLT, PoxPayloadOut, String, P> 
        implements CollectionSpacePoxClient<CLT, P> {
        
+    protected List<String> allResourceIdsCreated = new ArrayList<String>();
+       
     public AbstractPoxServiceClientImpl(String clientPropertiesFilename) {
        super(clientPropertiesFilename);
     }
@@ -22,7 +27,24 @@ public abstract class AbstractPoxServiceClientImpl<CLT extends AbstractCommonLis
        public AbstractPoxServiceClientImpl() {
                super();
        }
-
+       
+       /**
+        * Will delete a set of resources that were explicitly attached to the client.
+        */
+       public void cleanup() {
+               for (String csid : this.allResourceIdsCreated) {
+                       this.delete(csid).close();
+               }
+       }
+       
+       /**
+        * Adds a CSID to the list of items that should get deleted when cleanup() is called.
+        * @param csid
+        */
+       public void addToCleanup(String csid) {
+               this.allResourceIdsCreated.add(csid);
+       }
+       
        @Override
        public ServiceDescription getServiceDescription() {
                ServiceDescription result = null;
index 5a1191c70f79a370d6a660cbe9dfb53ac159ee51..ad76e11aaf644779b89394026a02a6f23ef0c59c 100644 (file)
@@ -644,4 +644,9 @@ public abstract class AbstractServiceClientImpl<CLT, REQUEST_PT, RESPONSE_PT, P
             Long pageNumber) {
         return getProxy().readList(sortBy, pageSize, pageNumber);
     }
+    
+    @Override
+    public String getTenantName() {
+       return this.getProperty(TENANT_NAME_PROPERTY);
+    }
 }
index 6309042c4aeef47b47494a08ca0032f88849c2d6..d3041dc6a04fbba65c976f397580d744ccced028 100644 (file)
@@ -111,11 +111,14 @@ public abstract class AuthorityClientImpl<AUTHORITY_COMMON_TYPE, AUTHORITY_ITEM_
        boolean result = true;
        
        Response response = getProxy().sync("-1"); // Check to see if the Authority (in general) supports sync for any of its instances
-       int status = response.getStatus();
-       if (status == Response.Status.FORBIDDEN.getStatusCode()) {
-               result = false;
+       try {
+               int status = response.getStatus();
+               if (status == Response.Status.FORBIDDEN.getStatusCode()) {
+                       result = false;
+               }
+       } finally {
+               response.close();
        }
-       response.close();
        
        return result;
     }
index fa495f3d36aa6a00af669a06ab91af7a4f6e1cdb..34a646095e810a0ff99979a19406f9ae10471a85 100644 (file)
@@ -39,6 +39,7 @@ public interface CollectionSpaceClient<CLT, REQUEST_TYPE, RESPONSE_TYPE, P exten
        public final static String CSID_PATH_PARAM_VAR = "{csid}";
     public final static String COLLECTIONSPACE_CORE_SCHEMA = "collectionspace_core";
     
+    public final static String COLLECTIONSPACE_CORE_CSID = "csid";
     public final static String COLLECTIONSPACE_CORE_TENANTID = "tenantId";
     public final static String CORE_TENANTID = COLLECTIONSPACE_CORE_SCHEMA + ":" + COLLECTIONSPACE_CORE_TENANTID;
     
@@ -71,6 +72,7 @@ public interface CollectionSpaceClient<CLT, REQUEST_TYPE, RESPONSE_TYPE, P exten
     public static final String URL_PROPERTY = "cspace.url";
     public static final String USER_PROPERTY = "cspace.user";
     public static final String TENANT_PROPERTY = "cspace.tenant";
+    public static final String TENANT_NAME_PROPERTY = "cspace.tenantID";
     
     // JAX-RS path for getting service description meta information
        public static final String SERVICE_DESCRIPTION_PATH = "description";
@@ -250,4 +252,6 @@ public interface CollectionSpaceClient<CLT, REQUEST_TYPE, RESPONSE_TYPE, P exten
      * @param clientPropertiesFilename
      */
        public void setClientProperties(String clientPropertiesFilename);
+       
+       public String getTenantName();
 }
index de18d234c7eabec58b526befdc59dbc2b32986af..703a616354a8e7f35afb7f74ddb2d5058314e2aa 100644 (file)
@@ -6,8 +6,8 @@ import java.util.List;
 import java.util.Map;
 
 import javax.ws.rs.core.Response;
-import org.apache.http.HttpStatus;
 
+import org.apache.http.HttpStatus;
 import org.collectionspace.services.client.AbstractCommonListUtils;
 import org.collectionspace.services.client.AuthorityClient;
 import org.collectionspace.services.client.CollectionSpaceClient;
@@ -21,12 +21,14 @@ import org.collectionspace.services.client.workflow.WorkflowClient;
 import org.collectionspace.services.description.ServiceDescription;
 import org.collectionspace.services.jaxb.AbstractCommonList;
 import org.collectionspace.services.relation.RelationsCommon;
+import org.collectionspace.services.relation.RelationsCommonList;
+import org.collectionspace.services.relation.RelationsCommonList.RelationListItem;
 import org.collectionspace.services.relation.RelationshipType;
-
 import org.dom4j.Document;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.Assert;
+import org.testng.SkipException;
 import org.testng.annotations.Test;
 
 /**
@@ -39,6 +41,7 @@ import org.testng.annotations.Test;
  * All CRUD related authority test classes should extend this class.
  * 
  */
+@SuppressWarnings("rawtypes")
 public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHORITY_ITEM_TYPE> 
        extends AbstractPoxServiceTestImpl<AbstractCommonList, AUTHORITY_COMMON_TYPE> {
 
@@ -66,9 +69,17 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
     protected int nItemsToCreateInList = 5;
     protected String TEST_SHORTID = "johnWayneActor";
 
+       protected List<String> knownSASItemIdentifiersWithRelationsList = new ArrayList<String>();
        protected String knownSASAuthorityResourceWithRelationsId = null;
        protected String knownSASAuthorityResourceWithRelationsShortId = null;
 
+       //
+       // Used to test hierarchical relationship synchronization
+       //
+       private String continentShortId;
+       private String countryShortId;
+       private String cityShortId;
+
     /*
      * Abstract methods that subclasses must override/implement
      */
@@ -164,11 +175,32 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
                return String.format("urn:cspace:name(%s)", shortId);
        }
        
+       /*
+        * Returns the CSID using the authority short ID.  Passed in client must be for the correct authority type -i.e., the on
+        * that corresponds to the CSID.
+        */
+       protected String getCsidFromShortId(AuthorityClient client, String authShortId, String itemShortId) {
+               String result = null;
+               
+               Response res = client.readNamedItemInNamedAuthority(authShortId, itemShortId);
+               try {
+                       result = extractCsid(res);
+               } catch (Exception e) {
+                       logger.error(String.format("Could not get CSID for authority item '%s' in authority '%s' of type '%s'.",
+                                       itemShortId, authShortId, client.getServiceName()), e);
+               } finally {
+                       res.close();
+               }
+               
+               return result;
+       }
+
+       
     /**
      * Sets up create tests.
      */
     protected void setupSync() {
-        testExpectedStatusCode = this.STATUS_OK;
+        testExpectedStatusCode = STATUS_OK;
         testRequestType = ServiceRequestType.SYNC;
         testSetup(testExpectedStatusCode, testRequestType);
     }
@@ -178,7 +210,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
      *
      * @return the client
      */
-    protected AuthorityClient getSASClientInstance() {
+       protected AuthorityClient getSASClientInstance() {
        return (AuthorityClient) this.getClientInstance(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME);
     }
 
@@ -245,8 +277,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         Assert.assertEquals(statusCode, EXPECTED_STATUS);
     }    
 
-    
-    @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
+       @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
        dependsOnMethods = {"readItem"})
     public void verifyIgnoredUpdateWithInAuthority(String testName) throws Exception {
        // Perform setup.
@@ -312,7 +343,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
        }
     }
     
-    @Test(dataProvider = "testName", dependsOnMethods = {"CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"CRUDTests"})
     public void createItem(String testName) {
         // Perform setup.
         setupCreate();
@@ -328,25 +359,46 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
             }
         }
     }
+    
+    /**
+     * Verify that we can test synchronization with this authority.  Otherwise, we skip the test.
+     */
+       private void assertSupportsSync() {
+       //
+       // Test to see if the authority on our locally tenant supports sync
+       //
+       AuthorityClient client = (AuthorityClient) this.getClientInstance();
+       if (client.supportsSync() == false) {
+               throw new SkipException(String.format("Skipped the test since this authority '%s' doesn't support synchronization.",
+                               client.getServiceName()));
+       }
+       //
+       // Test to see if the test tenancy's authority supports synchronization.
+       // 
+       AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
+       if (sasClient.supportsSync() == false) {
+               String tenantName = sasClient.getTenantName();
+               throw new SkipException(String.format("Skipped the test since this authority '%s' doesn't support synchronization on the server's tenant '%s'.",
+                               sasClient.getServiceName(), tenantName != null ? tenantName : "unknown"));
+       }
+    }
         
     /**
      * Sync the local with the SAS
      * @throws Exception 
      */
-    @Test(dataProvider = "testName", dependsOnMethods = {"createSASItemList", "CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"createSASItemList", "CRUDTests"})
     public void syncWithSAS(String testName) throws Exception {
         //
         // First check to see if the authority supports synchronization.
         //
-       AuthorityClient client = (AuthorityClient) this.getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }
+       assertSupportsSync();
        
         //
         // Create an empty instance of the authority, so we can sync items with it.  We're
        // using the short ID of the SAS authority.  The short ID of the local and the SAS will (must) be the same.
         //
+        AuthorityClient client = (AuthorityClient) getClientInstance();
        String localAuthorityId = null;
         try {
                        localAuthorityId = createResource(client, testName, knownSASAuthorityResourceShortId, false);
@@ -382,8 +434,57 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
                        Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED));  // After a sync, the parent should be in the "Replicated" state
         } finally {
                response.close();
-        }        
+        }
+    }
+    
+       @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthorityWithRelations", "CRUDTests"})
+    public void syncWithSASWithRelations(String testName) throws Exception {
+        //
+        // First check to see if the authority supports synchronization.
+        //
+       assertSupportsSync();
+               
+        //
+        // Create an empty instance of the authority, so we can sync items with it.  We're
+       // using the short ID of the SAS authority.  The short ID of the local and the SAS will (must) be the same.
+        //
+       AuthorityClient client = (AuthorityClient) this.getClientInstance();
+       String localAuthorityId = null;
+        try {
+                       localAuthorityId = createResource(client, testName, knownSASAuthorityResourceWithRelationsShortId, false);
+               } catch (Exception e) {
+                       Assert.assertNotNull(localAuthorityId);
+               }
+
+       //
+       // Now we can try to sync the SAS authority with the local one we just created.
+       //
+        setupSync();
+       Response response = client.syncByName(knownSASAuthorityResourceWithRelationsShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
+        try {
+               int statusCode = response.getStatus();
+               Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+                       invalidStatusCodeMessage(testRequestType, statusCode));
+               Assert.assertEquals(statusCode, testExpectedStatusCode);
+        } finally {
+               response.close();
+        }
         
+        //
+        // Check to see if the parent authority (local) is in the "Replicated" state.
+        //
+        setupRead();
+       response = client.readByName(knownSASAuthorityResourceWithRelationsShortId); // Notice we're using the Short ID (short ID is the same on the local and SAS)
+        try {
+               int statusCode = response.getStatus();
+               Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+                       invalidStatusCodeMessage(testRequestType, statusCode));
+               Assert.assertEquals(statusCode, testExpectedStatusCode);
+                       String workflowState = this.extractAuthorityWorkflowState(response);
+                       Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED));  // After a sync, the parent should be in the "Replicated" state
+        } finally {
+               response.close();
+        }
     }
     
     /**
@@ -391,20 +492,18 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
      * with the correct short IDs.
      * 
      */
-    @Test(dataProvider = "testName", dependsOnMethods = {"syncWithSAS", "CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"syncWithSAS", "CRUDTests"})
     public void veryifySyncWithSAS(String testName) {
         //
        // First check to see if we support sync.
        //
-        AuthorityClient client = (AuthorityClient) getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }        
-
+       assertSupportsSync();
+       
        // Perform setup.
         setupReadList();
 
         // Submit the request to the service and store the response.
+        AuthorityClient client = (AuthorityClient) getClientInstance();
         Response res = null;
         res = client.readItemListForNamedAuthority(knownSASAuthorityResourceShortId, null, null);
 
@@ -459,20 +558,120 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
                res.close();
         }
     }
+    
+       @Test(dataProvider = "testName", dependsOnMethods = {"syncWithSASWithRelations", "CRUDTests"})
+    public void veryifySyncWithSASWithRelations(String testName) {
+        //
+       // First check to see if we support sync.
+       //
+       assertSupportsSync();
+       
+       // Perform setup.
+        setupReadList();
+
+        // Submit the request to the service and store the response.
+        AuthorityClient client = (AuthorityClient) getClientInstance();
+        Response res = null;
+        res = client.readItemListForNamedAuthority(knownSASAuthorityResourceWithRelationsShortId, null, null);
+
+        try {
+               int statusCode = res.getStatus();
+               // Check the status code of the response: does it match
+               // the expected response(s)?
+               Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+                       invalidStatusCodeMessage(testRequestType, statusCode));
+               Assert.assertEquals(statusCode, testExpectedStatusCode);
+       
+               AbstractCommonList list = res.readEntity(AbstractCommonList.class);
+               long nItemsTotal = list.getTotalItems();
+               Assert.assertEquals(nItemsTotal, knownSASItemIdentifiersWithRelationsList.size());
+               //
+               // Verify that each of our local items has a corresponding remote item
+               //
+               List<AbstractCommonList.ListItem> itemList = list.getListItem();
+                       for (AbstractCommonList.ListItem item : itemList) {
+                               String shortId = AbstractCommonListUtils.ListItemGetElementValue(
+                                               item, AuthorityClient.SHORT_IDENTIFIER);
+                               Assert.assertTrue(knownSASItemIdentifiersWithRelationsList.contains(shortId)); // The local short ID should be in SAS list
+                               
+                               String workflowState = AbstractCommonListUtils.ListItemGetElementValue(
+                                               item, CollectionSpaceClient.COLLECTIONSPACE_CORE_WORKFLOWSTATE);
+                               Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED)); // Workflow state must show up in a "replicated" state
+                               
+                               String refName = AbstractCommonListUtils.ListItemGetElementValue(
+                                               item, AuthorityClient.REF_NAME);
+                               Assert.assertTrue((refName != null), "Item refName is null or not set in the item list!");
+                               String termDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
+                                               AuthorityClient.TERM_DISPLAY_NAME);
+                               String vocabDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
+                                               AuthorityClient.VOCAB_DISPLAY_NAME);
+                               // One of these names needs to be set.
+                               Assert.assertTrue(!(termDisplayName == null && vocabDisplayName == null), "The item's display name is null or not set in the item list!");
+                       }               
+        } finally {
+               res.close();
+        }
+        
+        //
+        // Verify the relationship hierarchy is correct.
+        //
+       AuthorityClient authorityClient = (AuthorityClient) getClientInstance();
+        ServiceDescription serviceDescription = authorityClient.getServiceDescription();
+        final String authorityItemDocumentType = serviceDescription == null ? "unknown" : serviceDescription.getSubresourceDocumentType();
+        
+        verifyBroaderRelationship(authorityClient, knownSASAuthorityResourceWithRelationsShortId, cityShortId, countryShortId, authorityItemDocumentType);
+        verifyBroaderRelationship(authorityClient, knownSASAuthorityResourceWithRelationsShortId, countryShortId, continentShortId, authorityItemDocumentType);
+    }
+    
+    /**
+     * Verifies a broader relationship exists between the subject and object.
+     * 
+     * @param authorityClient
+     * @param authorityShortId
+     * @param subjectShortId
+     * @param objectShortId
+     * @param authorityItemDocumentType
+     */
+    private void verifyBroaderRelationship(AuthorityClient authorityClient, String authorityShortId, String subjectShortId, String objectShortId, String authorityItemDocumentType) {
+        setupReadList();
+        RelationClient relationClient = new RelationClient();
+        Response res = relationClient.readList(getCsidFromShortId(authorityClient, authorityShortId, subjectShortId),
+                       authorityItemDocumentType,
+                       RelationshipType.HAS_BROADER.value(),
+                       getCsidFromShortId(authorityClient, authorityShortId, objectShortId),
+                       authorityItemDocumentType);
+        try {
+               int statusCode = res.getStatus();
+               Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+                       invalidStatusCodeMessage(testRequestType, statusCode));
+               Assert.assertEquals(statusCode, testExpectedStatusCode);
+               
+               RelationsCommonList list = (RelationsCommonList) res.readEntity(RelationsCommonList.class);
+               Assert.assertEquals(list.getTotalItems(), 1); // Should be exactly one relationship
+               RelationListItem relationListItem = list.getRelationListItem().get(0);
+               //
+               // Check the subject and object refnames to see if the contain the correct short identifiers
+               //
+               Assert.assertTrue(relationListItem.getSubject().getRefName().contains(subjectShortId)); // The subject refname should contain our known short ID
+               Assert.assertTrue(relationListItem.getSubject().getRefName().contains(authorityShortId)); // The subject refname should contain our known short ID
+               // Now check the object refname
+               Assert.assertTrue(relationListItem.getObject().getRefName().contains(objectShortId)); // The object refname should contain our known short ID
+               Assert.assertTrue(relationListItem.getObject().getRefName().contains(authorityShortId)); // The object refname should contain our known short ID
+        } finally {
+               res.close();
+        }
+    }
         
     /**
      * SAS - Create a new authority on the SAS server.
      * @param testName
      */    
-    @Test(dataProvider = "testName", dependsOnMethods = {"createItem", "CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"createItem", "CRUDTests"})
     public void createSASAuthority(String testName) {
         //
         // First check to see if the authority supports synchronization.
         //
-       AuthorityClient client = (AuthorityClient) this.getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }
+       assertSupportsSync();
        
         // Perform setup.
         setupCreate();
@@ -489,21 +688,19 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         }
     }
     
-    @Test(dataProvider = "testName", dependsOnMethods = {"deleteLocalItemWithSync", "CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"deleteLocalItemWithSync", "CRUDTests"})
     public void createSASAuthorityWithRelations(String testName) {
         //
         // First check to see if the authority supports synchronization.
         //
-       AuthorityClient client = (AuthorityClient) getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }
-       
+               assertSupportsSync();
+               
         // Perform setup.
         setupCreate();
         //
         // Create a new authority on the remote server
         //
+        AuthorityClient client = (AuthorityClient) getClientInstance();
         try {
                String newID = createResource(getSASClientInstance(), testName, getSASAuthorityWithRelationsIdentifier(), true);
                knownSASAuthorityResourceWithRelationsId = newID;
@@ -514,57 +711,84 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         //
         // Add three items to the remote authority
         //
-        String continentShortId = "Continent" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
+        continentShortId = "Continent" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
         String continentCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, continentShortId);
-        this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(continentShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
+        knownSASItemIdentifiersWithRelationsList.add(continentShortId);
+        allSASResourceItemIdsCreated.put(this.getUrnIdentifier(continentShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
         
-        String countryShortId = "Country" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
+        countryShortId = "Country" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
         String countryCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, countryShortId);
-        this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(countryShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
+        knownSASItemIdentifiersWithRelationsList.add(countryShortId);
+        allSASResourceItemIdsCreated.put(this.getUrnIdentifier(countryShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
 
-        String cityShortId = "City" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
+        cityShortId = "City" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
         String cityCSID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceWithRelationsId, cityShortId);
-        this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(cityShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
+        knownSASItemIdentifiersWithRelationsList.add(cityShortId);
+        allSASResourceItemIdsCreated.put(this.getUrnIdentifier(cityShortId), getUrnIdentifier(getSASAuthorityWithRelationsIdentifier()));
         //
         // Create a set of hierarchical relationships between the items
         //
         ServiceDescription serviceDescription = client.getServiceDescription();
-        final String authorityItemDocumentType = serviceDescription == null ? "unknown" : serviceDescription.getSubresourceDocumentType();
+        final String authorityItemDocumentType = serviceDescription == null ? "unknown" : serviceDescription.getSubresourceDocumentType();        
+        RelationClient relationClient = new RelationClient(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME); // Get a Relation service client to the SAS
         
+        boolean success = false;
+        try {
+                       createBroaderRelationship(relationClient, cityCSID, countryCSID, authorityItemDocumentType);
+                       createBroaderRelationship(relationClient, countryCSID, continentCSID, authorityItemDocumentType);
+                       success = true;
+               } catch (Exception e) {
+                       logger.error(e.getMessage());
+               }
+
+        Assert.assertTrue(success);
+    }
+    
+    /**
+     * Creates a broader relationship record between the subject and the object
+     * @param relationClient
+     * @throws Exception 
+     */
+    private void createBroaderRelationship(RelationClient relationClient, String subjectCSID, String objectCSID, String docType) throws Exception {
         RelationsCommon relationCommon = new RelationsCommon();
-        relationCommon.setSubjectCsid(countryCSID);
-        relationCommon.setSubjectDocumentType(authorityItemDocumentType);
-        relationCommon.setObjectCsid(continentCSID);
-        relationCommon.setObjectDocumentType(authorityItemDocumentType);
+        
+        relationCommon.setSubjectCsid(subjectCSID);
+        relationCommon.setSubjectDocumentType(docType);
+        relationCommon.setObjectCsid(objectCSID);
+        relationCommon.setObjectDocumentType(docType);
         relationCommon.setRelationshipType(RelationshipType.HAS_BROADER.value());
         relationCommon.setPredicateDisplayName(RelationshipType.HAS_BROADER.value());
         
-        RelationClient relationClient = new RelationClient(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME); // Get a Relation service client to the SAS
         PoxPayloadOut payloadOut = relationClient.createRequestTypeInstance(relationCommon);
         Response res = relationClient.create(payloadOut);
-        if (res.getStatus() != HttpStatus.SC_CREATED) {
-               logger.error("Could not create Relationship.");
+        try {
+               if (res.getStatus() == HttpStatus.SC_CREATED) {
+                       String relationCSID = extractId(res);
+                       allRelationResourceIdsCreated.add(relationCSID); // keep track of what we create so we can cleanup later
+               } else {
+                       String errMsg = "Could not create Relationship.";
+                       logger.error(errMsg);
+                       throw new Exception(errMsg);
+               }
+        } finally {
+               res.close();
         }
-
-}
+    }
 
     /**
      * SAS - Create an item in the SAS authority on the SAS server.
      * @param testName
      */
-    @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthority", "CRUDTests"})
+       @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthority", "CRUDTests"})
     public void createSASItemList(String testName) {
         //
         // First check to see if the authority supports synchronization.
         //
-       AuthorityClient client = (AuthorityClient) this.getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }
+       assertSupportsSync();
        
-        // Perform setup.
+        // Perform setup for create.
         setupCreate();
-
+        
         for (int i = 0; i < SAS_ITEMLIST_SIZE; i++) {
                String shortId = "SassyActor" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
                String newID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceId, shortId);
@@ -600,7 +824,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         }
     }
     
-    private String getShortId(AuthorityClient client, String authorityCsid) throws Exception {
+       private String getShortId(AuthorityClient client, String authorityCsid) throws Exception {
        String result = null;
        
         // Submit the request to the service and store the response.
@@ -615,7 +839,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         return result;
     }
     
-    private String getShortId(String authorityCsid) throws Exception {
+       private String getShortId(String authorityCsid) throws Exception {
         AuthorityClient client = (AuthorityClient) getClientInstance();
         return getShortId(client, authorityCsid);
     }
@@ -693,6 +917,15 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
                return result;
        }    
        
+       protected String extractCsid(Response res) throws Exception {
+               String result = null;
+               
+        PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType()));                
+               Document document = input.getDOMDocument();
+               result = XmlTools.getElementValue(document, "//" + AuthorityClient.COLLECTIONSPACE_CORE_CSID);
+
+               return result;
+       }    
     
     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
                dependsOnMethods = {"readItem"})
@@ -878,7 +1111,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
                
         AuthorityClient client = (AuthorityClient) getClientInstance();
         PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathItemsComponent());
-        PayloadOutputPart part = payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance);
+        payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance);
         result = payloadOut;
                
                return result;
@@ -948,21 +1181,17 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         }
     }
     
-    @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
+       @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
                dependsOnMethods = {"updateLocalItemWithSync", "CRUDTests"})
     public void deleteLocalItemWithSync(String testName) throws Exception {
        final int itemIndexToDelete = 1;
         //
        // First check to see if we support sync.
        //
-        AuthorityClient client = (AuthorityClient) getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }        
+       assertSupportsSync();
        
         // Perform test setup for a DELETE.
         setupDelete();
-        AUTHORITY_ITEM_TYPE theUpdate = null;
 
         // Delete an item from the SAS server
         AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
@@ -1001,22 +1230,19 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
      * We create a new item on the SAS, perform a sync with the local authority, and verify the local authority contains a copy
      * of the SAS item. 
      */
-    @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
+       @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
                dependsOnMethods = {"veryifySyncWithSAS", "CRUDTests"})
     public void updateLocalItemWithSync(String testName) throws Exception {
         //
        // First check to see if we support sync.
        //
-        AuthorityClient client = (AuthorityClient) getClientInstance();
-       if (client.supportsSync() == false) {
-               return; // Exit the test since this authority doesn't support synchronization
-       }        
+       assertSupportsSync();
        
         // Perform setup.
         setupUpdate();
-        AUTHORITY_ITEM_TYPE theUpdate = null;
 
         // Retrieve the contents of a shared authority item that we're going to update.
+        AUTHORITY_ITEM_TYPE theUpdate = null;
         AUTHORITY_ITEM_TYPE sasAuthorityItem = null;
         AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
         Response res = sasClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceShortId, knownSASItemIdentifiersList.get(0));
@@ -1184,11 +1410,11 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         //
         // Clean up authority items on the SAS using the SAS client.
         //
-        client = (AuthorityClient) this.getSASClientInstance();
+        AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
         for (Map.Entry<String, String> entry : allSASResourceItemIdsCreated.entrySet()) {
             itemResourceId = entry.getKey();
             parentResourceId = entry.getValue();
-            client.deleteItem(parentResourceId, itemResourceId).close();
+            sasClient.deleteItem(parentResourceId, itemResourceId).close();
         }
         //
         // Finally, call out superclass's cleanUp method to deleted the local authorities
@@ -1197,7 +1423,7 @@ public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHOR
         //
         // Call out superclass's cleanUp method to delete the SAS authorities
         //
-        super.cleanUp(client);        
+        super.cleanUp(sasClient);
     }
     
        protected String getTestAuthorityItemShortId() {
index f34eb0d3fe1ace7397632c9fa510a6af45198b50..486bc41973355d4ade3f07b2f9ef08ea59e1d416 100644 (file)
@@ -457,22 +457,27 @@ public abstract class AbstractServiceTestImpl<CLT, CPT, REQUEST_TYPE, RESPONSE_T
         // Submit the request to the service and store the response.
         CollectionSpaceClient client = this.getClientInstance();
         Response res = client.readList();
-        CLT list = res.readEntity(this.getCommonListType());
-        int statusCode = res.getStatus();
-
-        // Check the status code of the response: does it match
-        // the expected response(s)?
-        if (logger.isDebugEnabled()) {
-            logger.debug(testName + ": status = " + statusCode);
-        }
-        Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
-                invalidStatusCodeMessage(testRequestType, statusCode));
-        Assert.assertEquals(statusCode, testExpectedStatusCode);
-
-        // Optionally output additional data about list members for debugging.
-        boolean iterateThroughList = true;
-        if (iterateThroughList && logger.isTraceEnabled()) {
-            printList(testName, list);
+        
+        try {
+               CLT list = res.readEntity(this.getCommonListType());
+               int statusCode = res.getStatus();
+       
+               // Check the status code of the response: does it match
+               // the expected response(s)?
+               if (logger.isDebugEnabled()) {
+                   logger.debug(testName + ": status = " + statusCode);
+               }
+               Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
+                       invalidStatusCodeMessage(testRequestType, statusCode));
+               Assert.assertEquals(statusCode, testExpectedStatusCode);
+       
+               // Optionally output additional data about list members for debugging.
+               boolean iterateThroughList = true;
+               if (iterateThroughList && logger.isTraceEnabled()) {
+                   printList(testName, list);
+               }
+        } finally {
+               res.close();
         }
     }
     
index e6217c1f6eb6d7653bdfc93172d64043c73081ec..7581ed36b67457e4bbc2116a73b6b1efdf7dbd8f 100644 (file)
@@ -96,6 +96,8 @@ public abstract class BaseServiceTest<CLT> {
     protected String knownResourceId = null;
     /* Use this to keep track of resources to delete */
     protected List<String> allResourceIdsCreated = new ArrayList<String>();
+    /* Use this to keep track of relationship resources to delete */
+    protected List<String> allRelationResourceIdsCreated = new ArrayList<String>();
     /* Use this to track authority items */
     protected Map<String, String> allResourceItemIdsCreated = new HashMap<String, String>(); /* itemCsid, parentCsid */
     /* A runtime/command-line parameter to indicate if we should delete all the test related resource objects */
@@ -774,6 +776,14 @@ public abstract class BaseServiceTest<CLT> {
             // Note: Any non-success responses are ignored and not reported.
             client.delete(resourceId).close();
         }
+        //
+        // Clean up relationship records we created during testing
+        //
+        for (String resourceId : allRelationResourceIdsCreated) {
+            // Note: Any non-success responses are ignored and not reported.
+            client.delete(resourceId).close();
+        }
+        
     }
        
        //
index 370a6dea6e5b4f8b3c9395506461eedc22ece799..f832cd303e895c17063b8d750d1b0b9bdb7bf965 100644 (file)
@@ -1174,7 +1174,7 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
      *
      */
     private RelationsCommonList updateRelations(
-            String itemCSID, PoxPayloadIn input, DocumentWrapper<DocumentModel> wrapDoc, boolean fUpdate)
+            String itemCSID, PoxPayloadIn input, DocumentWrapper<DocumentModel> wrapDoc, boolean forUpdate)
             throws Exception {
         if (logger.isTraceEnabled()) {
             logger.trace("AuthItemDocHndler.updateRelations for: " + itemCSID);
@@ -1200,7 +1200,7 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
         UriInfo uriInfo = ctx.getUriInfo();
         MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
 
-        if (fUpdate) {
+        if (forUpdate) {
             //Run getList() once as sent to get childListOuter:
             String predicate = RelationshipType.HAS_BROADER.value();
             queryParams.putSingle(IRelationsManager.PREDICATE_QP, predicate);
@@ -1229,13 +1229,6 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
             if (logger.isTraceEnabled()) {
                 logger.trace("AuthItemDocHndler.updateRelations for: " + itemCSID + " got existing relations.");
             }
-        } else {
-               // For debugging purpose only.
-            if (logger.isDebugEnabled()) {
-               String debugMsg = "AuthItemDocHndler.updateRelations for: " + itemCSID + " with an fUpdate value of FALSE.";
-                logger.debug(debugMsg);
-                throw new Exception(debugMsg);
-            }
         }
 
         for (RelationsCommonList.RelationListItem inboundItem : inboundList) {
@@ -1300,7 +1293,7 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
             String dump = dumpLists(itemCSID, parentList, childList, actionList);
             logger.trace("~~~~~~~~~~~~~~~~~~~~~~dump~~~~~~~~~~~~~~~~~~~~~~~~" + CR + dump);
         }
-        if (fUpdate) {
+        if (forUpdate) {
             if (logger.isTraceEnabled()) {
                 logger.trace("AuthItemDocHndler.updateRelations for: " + itemCSID + " deleting "
                         + parentList.size() + " existing parents and " + childList.size() + " existing children.");
@@ -1411,14 +1404,14 @@ public abstract class   RemoteDocumentModelHandlerImpl<T, TL>
     // Nevertheless, we should complete the item save before we do work on the relations, especially
     // since a save on Create might fail, and we would not want to create relations for something
     // that may not be created...
-    private void handleRelationsPayload(DocumentWrapper<DocumentModel> wrapDoc, boolean fUpdate) throws Exception {
+    private void handleRelationsPayload(DocumentWrapper<DocumentModel> wrapDoc, boolean forUpdate) throws Exception {
        ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
         PoxPayloadIn input = ctx.getInput();
         DocumentModel documentModel = (wrapDoc.getWrappedObject());
         String itemCsid = documentModel.getName();
 
         //Updates relations part
-        RelationsCommonList relationsCommonList = updateRelations(itemCsid, input, wrapDoc, fUpdate);
+        RelationsCommonList relationsCommonList = updateRelations(itemCsid, input, wrapDoc, forUpdate);
 
         PayloadOutputPart payloadOutputPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME, relationsCommonList);  //FIXME: REM - We should check for a null relationsCommonList and not create the new common list payload
         ctx.setProperty(RelationClient.SERVICE_COMMON_LIST_NAME, payloadOutputPart);