]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
14f7142e7d3e57ec5da6f9223778551f72fb931c
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.client.test;
2
3 import java.lang.reflect.Array;
4 import java.util.ArrayList;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.ws.rs.core.Response;
10
11 import org.collectionspace.services.client.AbstractCommonListUtils;
12 import org.collectionspace.services.client.AuthorityClient;
13 import org.collectionspace.services.client.AuthorityClientImpl;
14 import org.collectionspace.services.client.AuthorityProxy;
15 import org.collectionspace.services.client.CollectionSpaceClient;
16 import org.collectionspace.services.client.PayloadInputPart;
17 import org.collectionspace.services.client.PayloadOutputPart;
18 import org.collectionspace.services.client.PoxPayloadIn;
19 import org.collectionspace.services.client.PoxPayloadOut;
20 import org.collectionspace.services.client.XmlTools;
21 import org.collectionspace.services.client.workflow.WorkflowClient;
22 import org.collectionspace.services.jaxb.AbstractCommonList;
23 import org.dom4j.Document;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.testng.Assert;
27 import org.testng.annotations.Test;
28
29 /**
30  * 
31  * @author remillet
32  *
33  * @param <AUTHORITY_COMMON_TYPE>
34  * @param <AUTHORITY_ITEM_TYPE>
35  * 
36  * All CRUD related authority test classes should extend this class.
37  * 
38  */
39 public abstract class AbstractAuthorityServiceTest<AUTHORITY_COMMON_TYPE, AUTHORITY_ITEM_TYPE> 
40         extends AbstractPoxServiceTestImpl<AbstractCommonList, AUTHORITY_COMMON_TYPE> {
41
42     private final Logger logger = LoggerFactory.getLogger(AbstractAuthorityServiceTest.class);
43         
44     protected String knownResourceShortIdentifer = null;
45         protected static final String READITEMS_SHORT_IDENTIFIER = "resourceWithItems" + random.nextInt(1000); 
46         protected String knownAuthorityWithItems = null;
47         protected String knownAuthorityWithItemsIdentifier = null;
48         
49         protected static final String SAS_IDENTIFIER = "SAS";
50
51         private static final int SAS_ITEMLIST_SIZE = 5; 
52         protected String knownSASAuthorityResourceId = null;
53         protected String knownSASAuthorityResourceIdentifier = null;
54         protected List<String> knownSASItemIdentifiersList = new ArrayList<String>();
55         protected String knownSASItemResourceId = null;
56         protected HashMap<String, String> allSASResourceItemIdsCreated = new HashMap<String, String>(); /* itemURN, parentURN */;
57
58         protected String knownResourceRefName = null;
59     protected String knownItemResourceId = null;
60     protected String knownItemResourceShortIdentifer = null;    
61     protected int nItemsToCreateInList = 5;
62     protected String TEST_SHORTID = "johnWayneActor";
63
64     /*
65      * Abstract methods that subclasses must override/implement
66      */
67     
68     /**
69      * 
70      * @param testName
71      */
72     public abstract void authorityTests(String testName);
73         
74         /**
75          * 
76          * @param client
77          * @param vcsid
78          * @return
79          */
80         abstract protected String createItemInAuthority(AuthorityClient client, String vcsid, String shortId);
81         
82     
83     /**
84      * 
85      * @param authorityItem
86      * @return
87      */
88     protected abstract AUTHORITY_ITEM_TYPE updateItemInstance(final AUTHORITY_ITEM_TYPE authorityItem);    
89     
90     /**
91      * 
92      * @param original
93      * @param updated
94      * @throws Exception
95      */
96     protected abstract void compareUpdatedItemInstances(AUTHORITY_ITEM_TYPE original, AUTHORITY_ITEM_TYPE updated) throws Exception;
97     
98     /**
99      * 
100      * @param id
101      * @param shortIdentifer
102      */
103     protected void setKnownItemResource(String id, String shortIdentifer ) {
104         knownItemResourceId = id;
105         knownItemResourceShortIdentifer = shortIdentifer;
106     }
107
108     /**
109      * 
110      * @param id
111      * @param shortIdentifer
112      * @param refName
113      */
114     protected void setKnownResource(String id, String shortIdentifer,
115             String refName) {
116         knownResourceId = id;
117         knownResourceShortIdentifer = shortIdentifer;
118         knownResourceRefName = refName;
119     }
120
121     /**
122      * 
123      * @return
124      */
125         protected String getSASAuthorityIdentifier() {
126                 // TODO Auto-generated method stub
127                 return this.getKnowResourceIdentifier() + SAS_IDENTIFIER;
128         }
129     
130         /**
131          * 
132          * @param shortId
133          * @return
134          */
135         protected String getUrnIdentifier(String shortId) {
136                 return String.format("urn:cspace:name(%s)", shortId);
137         }
138         
139     /**
140      * Sets up create tests.
141      */
142     protected void setupSync() {
143         testExpectedStatusCode = this.STATUS_OK;
144         testRequestType = ServiceRequestType.SYNC;
145         testSetup(testExpectedStatusCode, testRequestType);
146     }
147     
148     /**
149      * Gets a client to the SAS (Shared Authority Server)
150      *
151      * @return the client
152      */
153     protected AuthorityClient getSASClientInstance() {
154         return (AuthorityClient) this.getClientInstance(CollectionSpaceClient.SAS_CLIENT_PROPERTIES_FILENAME);
155     }
156
157     /**
158      * Returns the root URL for a service.
159      *
160      * This URL consists of a base URL for all services, followed by
161      * a path component for the owning vocabulary, followed by the 
162      * path component for the items.
163      *
164      * @return The root URL for a service.
165      */
166     protected String getItemServiceRootURL(String parentResourceIdentifier) {
167         return getResourceURL(parentResourceIdentifier) + "/" + getServicePathItemsComponent();
168     }
169
170     /**
171      * Returns the URL of a specific resource managed by a service, and
172      * designated by an identifier (such as a universally unique ID, or UUID).
173      *
174      * @param  resourceIdentifier  An identifier (such as a UUID) for a resource.
175      *
176      * @return The URL of a specific resource managed by a service.
177      */
178     protected String getItemResourceURL(String parentResourceIdentifier, String resourceIdentifier) {
179         return getItemServiceRootURL(parentResourceIdentifier) + "/" + resourceIdentifier;
180     }
181         
182     /**
183      * For authorities we override this method so we can save the shortid.
184      */
185     @Override
186     protected String createWithIdentifier(String testName, String identifier) throws Exception {
187         String csid = createResource(testName, identifier);
188         // Store the ID returned from the first resource created
189         // for additional tests below.
190         if (getKnowResourceId() == null) {
191                 setKnownResource(csid, identifier /*shortId*/, null /*refname*/ );
192             if (logger.isDebugEnabled()) {
193                 logger.debug(testName + ": Setting knownResourceId=" + getKnowResourceId());
194             }
195         }
196         
197         return identifier;
198     }    
199     
200     @Test(dependsOnMethods = {"readItem", "CRUDTests"})
201     public void testItemSubmitRequest() {
202
203         // Expected status code: 200 OK
204         final int EXPECTED_STATUS = Response.Status.OK.getStatusCode();
205
206         // Submit the request to the service and store the response.
207         String method = ServiceRequestType.READ.httpMethodName();
208         String url = getItemResourceURL(knownResourceId, knownItemResourceId);
209         int statusCode = submitRequest(method, url);
210
211         // Check the status code of the response: does it match
212         // the expected response(s)?
213         if (logger.isDebugEnabled()) {
214             logger.debug("testItemSubmitRequest: url=" + url
215                     + " status=" + statusCode);
216         }
217         Assert.assertEquals(statusCode, EXPECTED_STATUS);
218     }    
219
220     
221     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
222         dependsOnMethods = {"readItem"})
223     public void verifyIgnoredUpdateWithInAuthority(String testName) throws Exception {
224         // Perform setup.
225         setupUpdate();
226
227         // Submit the request to the service and store the response.
228         AuthorityClient client = (AuthorityClient)this.getClientInstance();
229         Response res = client.readItem(knownResourceId, knownItemResourceId);
230         AUTHORITY_ITEM_TYPE vitem = null;
231         try {
232                 int statusCode = res.getStatus();
233         
234                 // Check the status code of the response: does it match
235                 // the expected response(s)?
236                 if (logger.isDebugEnabled()) {
237                         logger.debug(testName + " read authority:" + knownResourceId + "/Item:"
238                                         + knownItemResourceId + " status = " + statusCode);
239                 }
240                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
241                                 invalidStatusCodeMessage(testRequestType, statusCode));
242                 Assert.assertEquals(statusCode, Response.Status.OK.getStatusCode());
243         
244                 vitem = extractItemCommonPartValue(res);
245                 Assert.assertNotNull(vitem);
246                 // Try to Update with new parent vocab (use self, for test).
247                 Assert.assertEquals(client.getInAuthority(vitem), knownResourceId,
248                                 "VocabularyItem inAuthority does not match knownResourceId.");
249                 client.setInAuthority(vitem, knownItemResourceId);
250
251         } finally {
252                 res.close();
253         }
254         
255         // Submit the updated resource to the service and store the response.
256         PoxPayloadOut output = this.createItemRequestTypeInstance(vitem);
257         res = client.updateItem(knownResourceId, knownItemResourceId, output);
258         try {
259                 int statusCode = res.getStatus();
260         
261                 // Check the status code of the response: does it match the expected response(s)?
262                 if (logger.isDebugEnabled()) {
263                         logger.debug(testName + ": status = " + statusCode);
264                 }
265                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
266                                 invalidStatusCodeMessage(testRequestType, statusCode));
267                 Assert.assertEquals(statusCode, testExpectedStatusCode);
268         } finally {
269                 res.close();
270         }
271         
272         res = client.readItem(knownResourceId, knownItemResourceId);
273         try {
274                 // Retrieve the updated resource and verify that the parent did not change
275                 AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res);
276                 Assert.assertNotNull(updatedVocabularyItem);
277         
278                 // Verify that the updated resource received the correct data.
279                 Assert.assertEquals(client.getInAuthority(updatedVocabularyItem),
280                                 knownResourceId,
281                                 "VocabularyItem allowed update to the parent (inAuthority).");
282         } finally {
283                 res.close();
284         }
285     }
286     
287     @Test(dataProvider = "testName", dependsOnMethods = {"CRUDTests"})
288     public void createItem(String testName) {
289         // Perform setup.
290         setupCreate();
291
292         String newID = createItemInAuthority((AuthorityClient) getClientInstance(), knownResourceId, getTestAuthorityItemShortId());
293
294         // Store the ID returned from the first item resource created
295         // for additional tests below.
296         if (knownItemResourceId == null) {
297             knownItemResourceId = newID;
298             if (null != testName && logger.isDebugEnabled()) {
299                 logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId);
300             }
301         }
302     }
303         
304     /**
305      * Sync the local with the SAS
306      * @throws Exception 
307      */
308     @Test(dataProvider = "testName", dependsOnMethods = {"createSASItemList", "CRUDTests"})
309     public void syncWithSAS(String testName) throws Exception {
310         //
311         // First check to see if the authority supports synchronization.
312         //
313         AuthorityClient client = (AuthorityClient) this.getClientInstance();
314         if (client.supportsSync() == false) {
315                 return; // Exit the test since this authority doesn't support synchronization
316         }
317         
318         //
319         // Create an empty instance of the authority, so we can sync items with it.  We're
320         // using the short ID of the SAS authority.  The short ID of the local and the SAS will (must) be the same.
321         //
322         String localAuthorityId = null;
323         try {
324                         localAuthorityId = createResource(client, testName, knownSASAuthorityResourceIdentifier, false);
325                 } catch (Exception e) {
326                         Assert.assertNotNull(localAuthorityId);
327                 }
328
329         //
330         // Now we can try to sync the SAS authority with the local one we just created.
331         //
332         setupSync();
333         Response response = client.syncByName(knownSASAuthorityResourceIdentifier); // Notice we're using the Short ID (short ID is the same on the local and SAS)
334         try {
335                 int statusCode = response.getStatus();
336                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
337                         invalidStatusCodeMessage(testRequestType, statusCode));
338                 Assert.assertEquals(statusCode, testExpectedStatusCode);
339         } finally {
340                 response.close();
341         }
342         
343         //
344         // Check to see if the parent authority (local) is in the "Replicated" state.
345         //
346         setupRead();
347         response = client.readByName(knownSASAuthorityResourceIdentifier); // Notice we're using the Short ID (short ID is the same on the local and SAS)
348         try {
349                 int statusCode = response.getStatus();
350                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
351                         invalidStatusCodeMessage(testRequestType, statusCode));
352                 Assert.assertEquals(statusCode, testExpectedStatusCode);
353                         String workflowState = this.extractAuthorityWorkflowState(response);
354                         Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED));  // After a sync, the parent should be in the "Replicated" state
355         } finally {
356                 response.close();
357         }        
358         
359     }
360     
361     /**
362      * Check to make sure the sync with the SAS returned the correct number of items as well as items
363      * with the correct short IDs.
364      * 
365      */
366     @Test(dataProvider = "testName", dependsOnMethods = {"syncWithSAS", "CRUDTests"})
367     public void veryifySyncWithSAS(String testName) {
368         // Perform setup.
369         setupReadList();
370
371         // Submit the request to the service and store the response.
372         AuthorityClient client = (AuthorityClient) getClientInstance();
373         Response res = null;
374         res = client.readItemListForNamedAuthority(knownSASAuthorityResourceIdentifier, null, null);
375
376         try {
377                 int statusCode = res.getStatus();
378         
379                 // Check the status code of the response: does it match
380                 // the expected response(s)?
381                 if (logger.isDebugEnabled()) {
382                     logger.debug("  " + testName + ": status = " + statusCode);
383                 }
384                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
385                         invalidStatusCodeMessage(testRequestType, statusCode));
386                 Assert.assertEquals(statusCode, testExpectedStatusCode);
387         
388                 AbstractCommonList list = res.readEntity(AbstractCommonList.class);
389                 List<AbstractCommonList.ListItem> items = list.getListItem();
390                 int nItemsReturned = items.size();
391                 long nItemsTotal = list.getTotalItems();
392                 if (logger.isDebugEnabled()) {
393                     logger.debug("  " + testName + ": Expected "
394                             + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal);
395                 }
396                 Assert.assertEquals(nItemsTotal, SAS_ITEMLIST_SIZE);
397         
398                         for (AbstractCommonList.ListItem item : items) {
399                                 String shortId = AbstractCommonListUtils.ListItemGetElementValue(
400                                                 item, AuthorityClient.SHORT_IDENTIFIER);
401                                 Assert.assertTrue(knownSASItemIdentifiersList.contains(shortId)); // The local short ID should be in SAS list
402                                 
403                                 String workflowState = AbstractCommonListUtils.ListItemGetElementValue(
404                                                 item, CollectionSpaceClient.COLLECTIONSPACE_CORE_WORKFLOWSTATE);
405                                 Assert.assertTrue(workflowState.contains(WorkflowClient.WORKFLOWSTATE_REPLICATED)); // Workflow state must show up in a "replicated" state
406                                 
407                                 String refName = AbstractCommonListUtils.ListItemGetElementValue(
408                                                 item, AuthorityClient.REF_NAME);
409                                 Assert.assertTrue((refName != null), "Item refName is null or not set in the item list!");
410                                 String termDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
411                                                 AuthorityClient.TERM_DISPLAY_NAME);
412                                 String vocabDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
413                                                 AuthorityClient.VOCAB_DISPLAY_NAME);
414                                 // One of these names needs to be set.
415                                 Assert.assertTrue(!(termDisplayName == null && vocabDisplayName == null), "The item's display name is null or not set in the item list!");
416                         }
417                 
418                 if(logger.isTraceEnabled()){
419                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
420                 }
421         } finally {
422                 res.close();
423         }
424     }
425         
426     /**
427      * SAS - Create a new authority on the SAS server.
428      * @param testName
429      */    
430     @Test(dataProvider = "testName", dependsOnMethods = {"createItem", "CRUDTests"})
431     public void createSASAuthority(String testName) {
432         //
433         // First check to see if the authority supports synchronization.
434         //
435         AuthorityClient client = (AuthorityClient) this.getClientInstance();
436         if (client.supportsSync() == false) {
437                 return; // Exit the test since this authority doesn't support synchronization
438         }
439         
440         // Perform setup.
441         setupCreate();
442
443         try {
444                 String newID = createResource(getSASClientInstance(), testName, getSASAuthorityIdentifier(), true);
445                 knownSASAuthorityResourceId = newID;
446                 knownSASAuthorityResourceIdentifier = getShortId(getSASClientInstance(), knownSASAuthorityResourceId);
447             if (logger.isDebugEnabled()) {
448                 String.format("Created SAS authority '%s' with CSID=%s.", getSASAuthorityIdentifier(), newID);
449             }
450         } catch (Exception e) {
451                 logger.info(String.format("Failed to create SAS authority '%s'.", getSASAuthorityIdentifier()));
452         }
453     }
454
455     /**
456      * SAS - Create an item in the SAS authority on the SAS server.
457      * @param testName
458      */
459     @Test(dataProvider = "testName", dependsOnMethods = {"createSASAuthority", "CRUDTests"})
460     public void createSASItemList(String testName) {
461         //
462         // First check to see if the authority supports synchronization.
463         //
464         AuthorityClient client = (AuthorityClient) this.getClientInstance();
465         if (client.supportsSync() == false) {
466                 return; // Exit the test since this authority doesn't support synchronization
467         }
468         
469         // Perform setup.
470         setupCreate();
471
472         for (int i = 0; i < SAS_ITEMLIST_SIZE; i++) {
473                 String shortId = "SassyActor" + System.currentTimeMillis() + Math.abs(random.nextInt()); // short ID needs to be unique
474                 String newID = createItemInAuthority(getSASClientInstance(), knownSASAuthorityResourceId, shortId);
475         
476                         // Store the ID returned from the first item resource created
477                 // for additional tests below.
478                 if (knownSASItemResourceId == null) {
479                         knownSASItemResourceId = newID;
480                     if (null != testName && logger.isDebugEnabled()) {
481                         logger.debug(testName + ": knownSASItemResourceId=" + knownSASItemResourceId);
482                     }
483                 }
484                 
485                 knownSASItemIdentifiersList.add(shortId);
486
487                 //
488                 // Keep track of the SAS authority items we create, so we can delete them from
489                 // the *local* authority after we perform a sync operation.  We need to keep track
490                 // of the URN (not the CSID) since the CSIDs will differ on the SAS vs local.
491                 //
492                 this.allSASResourceItemIdsCreated.put(this.getUrnIdentifier(shortId), getUrnIdentifier(getSASAuthorityIdentifier()));
493         }
494         
495     }
496     
497     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
498                 dependsOnMethods = {"createItem"})
499     public void createItemList(String testName) throws Exception {
500         knownAuthorityWithItems = createResource(testName, READITEMS_SHORT_IDENTIFIER);
501         knownAuthorityWithItemsIdentifier = getShortId(knownAuthorityWithItems);
502         for (int j = 0; j < nItemsToCreateInList; j++) {
503                 createItemInAuthority((AuthorityClient) getClientInstance(), knownAuthorityWithItems, this.getTestAuthorityItemShortId(true));
504         }
505     }
506     
507     private String getShortId(AuthorityClient client, String authorityCsid) throws Exception {
508         String result = null;
509         
510         // Submit the request to the service and store the response.
511         Response res = client.read(authorityCsid);
512         try {
513                 int statusCode = res.getStatus();
514                 result = this.extractAuthorityShortId(res);
515         } finally {
516                 res.close();
517         }
518         
519         return result;
520     }
521     
522     private String getShortId(String authorityCsid) throws Exception {
523         AuthorityClient client = (AuthorityClient) getClientInstance();
524         return getShortId(client, authorityCsid);
525     }
526
527     /**
528      * Read by name.
529      *
530      * @param testName the test name
531      * @throws Exception the exception
532      */
533     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
534                 dependsOnMethods = {"CRUDTests"})
535     public void readByName(String testName) throws Exception {
536         // Perform setup.
537         setupRead();
538
539         // Submit the request to the service and store the response.
540         AuthorityClient client = (AuthorityClient) this.getClientInstance();
541         Response res = client.readByName(getKnowResourceIdentifier());
542         try {
543                 int statusCode = res.getStatus();
544         
545                 // Check the status code of the response: does it match
546                 // the expected response(s)?
547                 if (logger.isDebugEnabled()) {
548                     logger.debug(testName + ": status = " + statusCode);
549                 }
550                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
551                         invalidStatusCodeMessage(testRequestType, statusCode));
552                 Assert.assertEquals(statusCode, testExpectedStatusCode);
553                 
554                 AUTHORITY_COMMON_TYPE commonPart = extractCommonPartValue(res);
555                 Assert.assertNotNull(commonPart);
556         } finally {
557                 res.close();
558         }
559     }
560     
561     /**
562      * Extracts the common part item from a service's item payload.
563      * 
564      * @param res
565      * @return
566      * @throws Exception
567      */
568         public AUTHORITY_ITEM_TYPE extractItemCommonPartValue(Response res) throws Exception {
569                 AUTHORITY_ITEM_TYPE result = null;
570                 
571         AuthorityClient client = (AuthorityClient) getClientInstance();
572                 PayloadInputPart payloadInputPart = extractPart(res, client.getItemCommonPartName());
573                 if (payloadInputPart != null) {
574                         result = (AUTHORITY_ITEM_TYPE) payloadInputPart.getBody();
575                 }
576                 Assert.assertNotNull(result,
577                                 "Part or body of part " + client.getCommonPartName() + " was unexpectedly null.");
578                 
579                 return result;
580         }
581                 
582         
583     /**
584      * Extracts the short ID from a service request payload
585      * 
586      * @param res
587      * @return
588      * @throws Exception
589      */
590         protected String extractAuthorityShortId(Response res) throws Exception {
591                 String result = null;
592                 
593         PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType()));         
594                 Document document = input.getDOMDocument();
595                 result = XmlTools.getElementValue(document, "//" + AuthorityClient.SHORT_IDENTIFIER);
596
597                 return result;
598         }    
599         
600     
601     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
602                 dependsOnMethods = {"readItem"})
603     public void readItemNonExistent(String testName) {
604         // Perform setup.
605         setupReadNonExistent();
606
607         // Submit the request to the service and store the response.
608         AuthorityClient client = (AuthorityClient) getClientInstance();
609         Response res = client.readItem(knownResourceId, NON_EXISTENT_ID);
610         try {
611                 int statusCode = res.getStatus();
612         
613                 // Check the status code of the response: does it match
614                 // the expected response(s)?
615                 if (logger.isDebugEnabled()) {
616                     logger.debug(testName + ": status = " + statusCode);
617                 }
618                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
619                         invalidStatusCodeMessage(testRequestType, statusCode));
620                 Assert.assertEquals(statusCode, testExpectedStatusCode);
621         } finally {
622                 res.close();
623         }
624     }
625         
626     @Test(dataProvider = "testName",
627                 dependsOnMethods = {"createItem"})
628     public void readItem(String testName) throws Exception {
629         // Perform setup.
630         setupRead();
631
632         // Submit the request to the service and store the response.
633         AuthorityClient client = (AuthorityClient) getClientInstance();
634         Response res = client.readItem(knownResourceId, knownItemResourceId);
635         try {
636                 int statusCode = res.getStatus();
637         
638                 // Check the status code of the response: does it match
639                 // the expected response(s)?
640                 if (logger.isDebugEnabled()) {
641                     logger.debug(testName + ": status = " + statusCode);
642                 }
643                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
644                         invalidStatusCodeMessage(testRequestType, statusCode));
645                 Assert.assertEquals(statusCode, testExpectedStatusCode);
646         
647                 AUTHORITY_ITEM_TYPE itemCommonPart = extractItemCommonPartValue(res);
648                 Assert.assertNotNull(itemCommonPart);
649                 Assert.assertEquals(client.getInAuthority(itemCommonPart), knownResourceId);
650                 verifyReadItemInstance(itemCommonPart);
651         } finally {
652                 res.close();
653         }
654     }
655     
656     protected abstract void verifyReadItemInstance(AUTHORITY_ITEM_TYPE item) throws Exception;
657         
658     @Test(dataProvider = "testName",
659                 dependsOnMethods = {"testItemSubmitRequest", "updateItem", "verifyIgnoredUpdateWithInAuthority"})    
660     public void deleteItem(String testName) throws Exception {
661         // Perform setup.
662         setupDelete();
663
664         // Submit the request to the service and store the response.
665         AuthorityClient client = (AuthorityClient) getClientInstance();
666         Response res = client.deleteItem(knownResourceId, knownItemResourceId);
667         int statusCode;
668         try {
669                 statusCode = res.getStatus();
670         } finally {
671                 res.close();
672         }
673
674         // Check the status code of the response: does it match
675         // the expected response(s)?
676         if (logger.isDebugEnabled()) {
677             logger.debug("delete: status = " + statusCode);
678         }
679         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
680                 invalidStatusCodeMessage(testRequestType, statusCode));
681         Assert.assertEquals(statusCode, testExpectedStatusCode);
682     }
683     
684     protected void readItemListInt(String vcsid, String shortId, String testName) {
685         // Perform setup.
686         setupReadList();
687
688         // Submit the request to the service and store the response.
689         AuthorityClient client = (AuthorityClient) getClientInstance();
690         Response res = null;
691         if (vcsid != null) {
692             res = client.readItemList(vcsid, null, null);
693         } else if (shortId != null) {
694             res = client.readItemListForNamedAuthority(shortId, null, null);
695         } else {
696             Assert.fail("Internal Error: readItemList both vcsid and shortId are null!");
697         }
698         try {
699                 int statusCode = res.getStatus();
700         
701                 // Check the status code of the response: does it match
702                 // the expected response(s)?
703                 if (logger.isDebugEnabled()) {
704                     logger.debug("  " + testName + ": status = " + statusCode);
705                 }
706                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
707                         invalidStatusCodeMessage(testRequestType, statusCode));
708                 Assert.assertEquals(statusCode, testExpectedStatusCode);
709         
710                 AbstractCommonList list = res.readEntity(AbstractCommonList.class);
711                 List<AbstractCommonList.ListItem> items = list.getListItem();
712                 int nItemsReturned = items.size();
713                 long nItemsTotal = list.getTotalItems();
714                 if (logger.isDebugEnabled()) {
715                     logger.debug("  " + testName + ": Expected "
716                             + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal);
717                 }
718                 Assert.assertEquals(nItemsTotal, nItemsToCreateInList);
719         
720                         for (AbstractCommonList.ListItem item : items) {
721                                 String refName = AbstractCommonListUtils.ListItemGetElementValue(
722                                                 item, AuthorityClient.REF_NAME);
723                                 Assert.assertTrue((refName != null), "Item refName is null or not set in the item list!");
724                                 String termDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
725                                                 AuthorityClient.TERM_DISPLAY_NAME);
726                                 String vocabDisplayName = AbstractCommonListUtils.ListItemGetElementValue(item,
727                                                 AuthorityClient.VOCAB_DISPLAY_NAME);
728                                 // One of these names needs to be set.
729                                 Assert.assertTrue(!(termDisplayName == null && vocabDisplayName == null), "The item's display name is null or not set in the item list!");
730                         }
731                 
732                 if(logger.isTraceEnabled()){
733                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
734                 }
735         } finally {
736                 res.close();
737         }
738     }
739     
740     @Test(dataProvider = "testName", dependsOnMethods = {"createItemList"})
741     public void readItemList(String testName) {
742         readItemListInt(knownAuthorityWithItems, null, testName);
743     }
744
745     @Test(dataProvider = "testName", dependsOnMethods = {"readItemList"})
746     public void readItemListByName(String testName) {
747         readItemListInt(null, knownAuthorityWithItemsIdentifier, testName);
748     }
749
750     @Test(dataProvider = "testName",
751                 dependsOnMethods = {"deleteItem"})
752     public void deleteNonExistentItem(String testName) {
753         // Perform setup.
754         setupDeleteNonExistent();
755
756         // Submit the request to the service and store the response.
757         AuthorityClient client = (AuthorityClient) getClientInstance();
758         Response res = client.deleteItem(knownResourceId, NON_EXISTENT_ID);
759         int statusCode;
760         try {
761                 statusCode = res.getStatus();
762         } finally {
763                 res.close();
764         }
765
766         // Check the status code of the response: does it match
767         // the expected response(s)?
768         if (logger.isDebugEnabled()) {
769             logger.debug(testName + ": status = " + statusCode);
770         }
771         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
772                 invalidStatusCodeMessage(testRequestType, statusCode));
773         Assert.assertEquals(statusCode, testExpectedStatusCode);
774     }
775     
776     protected String getServicePathItemsComponent() {
777         return AuthorityClient.ITEMS;
778     }
779     
780         public PoxPayloadOut createItemRequestTypeInstance(AUTHORITY_ITEM_TYPE itemTypeInstance) {
781                 PoxPayloadOut result = null;
782                 
783         AuthorityClient client = (AuthorityClient) getClientInstance();
784         PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathItemsComponent());
785         PayloadOutputPart part = payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance);
786         result = payloadOut;
787                 
788                 return result;
789         }
790
791         /**
792          * Update an Authority item.
793          * 
794          * @param testName
795          * @throws Exception
796          */
797     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
798                 dependsOnMethods = {"readItem", "CRUDTests", "verifyIgnoredUpdateWithInAuthority"})
799     public void updateItem(String testName) throws Exception {
800         // Perform setup.
801         setupUpdate();
802         AUTHORITY_ITEM_TYPE theUpdate = null;
803
804         // Retrieve the contents of a resource to update.
805         AuthorityClient client = (AuthorityClient)this.getClientInstance();
806         Response res = client.readItem(knownResourceId, knownItemResourceId);
807         try {
808                 if (logger.isDebugEnabled()) {
809                     logger.debug(testName + ": read status = " + res.getStatus());
810                 }
811                 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
812         
813                 if (logger.isDebugEnabled()) {
814                     logger.debug("got Authority item to update with ID: "
815                             + knownItemResourceId
816                             + " in authority: " + knownResourceId);
817                 }
818                 AUTHORITY_ITEM_TYPE authorityItem = extractItemCommonPartValue(res);
819                 Assert.assertNotNull(authorityItem);
820
821                 // Update the contents of this resource.
822                 theUpdate = updateItemInstance(authorityItem);
823                 if (logger.isDebugEnabled()) {
824                     logger.debug("\n\nTo be updated fields: CSID = "  + knownItemResourceId + "\n"
825                                 + objectAsXmlString(theUpdate));
826                 }
827         } finally {
828                 res.close();
829         }
830
831         // Submit the updated resource to the service and store the response.
832         PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate);
833         res = client.updateItem(knownResourceId, knownItemResourceId, output);
834         try {
835                 int statusCode = res.getStatus();
836         
837                 // Check the status code of the response: does it match the expected response(s)?
838                 if (logger.isDebugEnabled()) {
839                     logger.debug("updateItem: status = " + statusCode);
840                 }
841                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
842                         invalidStatusCodeMessage(testRequestType, statusCode));
843                 Assert.assertEquals(statusCode, testExpectedStatusCode);
844         
845                 // Retrieve the updated resource and verify that its contents exist.
846                 AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res);
847                 Assert.assertNotNull(updatedVocabularyItem);
848
849                 compareUpdatedItemInstances(theUpdate, updatedVocabularyItem);
850         } finally {
851                 res.close();
852         }
853     }
854     
855     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
856                 dependsOnMethods = {"readItem", "CRUDTests", "veryifySyncWithSAS"})
857     public void updateLocalItemWithSync(String testName) throws Exception {
858         // Perform setup.
859         setupUpdate();
860         AUTHORITY_ITEM_TYPE theUpdate = null;
861
862         // Retrieve the contents of a shared authority item that we're going to update.
863         AUTHORITY_ITEM_TYPE sasAuthorityItem = null;
864         AuthorityClient sasClient = (AuthorityClient) this.getSASClientInstance();
865         Response res = sasClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceIdentifier, knownSASItemIdentifiersList.get(0));
866         try {
867                 if (logger.isDebugEnabled()) {
868                     logger.debug(testName + ": read status = " + res.getStatus());
869                 }
870                 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
871         
872                 sasAuthorityItem = extractItemCommonPartValue(res);  // This is a SAS authority item
873                 Assert.assertNotNull(sasAuthorityItem);
874         } finally {
875                 res.close();
876         }
877
878         // Update the contents of this authority item so we can post an UPDATE to the server
879         theUpdate = updateItemInstance(sasAuthorityItem);
880
881         // Submit the updated authority item and check the response.
882         PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate);
883         res = sasClient.updateNamedItemInNamedAuthority(knownSASAuthorityResourceIdentifier, knownSASItemIdentifiersList.get(0), output);
884         AUTHORITY_ITEM_TYPE updatedAuthorityItem = null;
885         try {
886                 int statusCode = res.getStatus();
887         
888                 // Check the status code of the response: does it match the expected response(s)?
889                 if (logger.isDebugEnabled()) {
890                     logger.debug("updateItem: status = " + statusCode);
891                 }
892                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
893                         invalidStatusCodeMessage(testRequestType, statusCode));
894                 Assert.assertEquals(statusCode, testExpectedStatusCode);
895         
896                 // Retrieve the updated authority item and verify that its contents exist.
897                 updatedAuthorityItem = extractItemCommonPartValue(res);
898                 Assert.assertNotNull(updatedAuthorityItem);
899
900                 compareUpdatedItemInstances(theUpdate, updatedAuthorityItem);
901         } finally {
902                 res.close();
903         }
904         
905         // Synchronize the item's parent authority and verify the update we just made
906         // to the SAS appears locally
907         setupSync();
908         AuthorityClient localClient = (AuthorityClient) this.getClientInstance();
909         Response response = localClient.syncByName(knownSASAuthorityResourceIdentifier); // Notice we're using the Short ID (short ID is the same on the local and SAS)
910         try {
911                 int statusCode = response.getStatus();
912                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), invalidStatusCodeMessage(testRequestType, statusCode));
913                 Assert.assertEquals(statusCode, testExpectedStatusCode);
914         } finally {
915                 response.close();
916         }        
917         
918         setupRead();
919         res = localClient.readNamedItemInNamedAuthority(knownSASAuthorityResourceIdentifier, knownSASItemIdentifiersList.get(0));
920         try {
921                 Assert.assertEquals(res.getStatus(), testExpectedStatusCode);
922                 AUTHORITY_ITEM_TYPE syncedAuthorityItem = extractItemCommonPartValue(res);
923                 Assert.assertNotNull(syncedAuthorityItem);
924                 compareUpdatedItemInstances(sasAuthorityItem, updatedAuthorityItem);
925         } finally {
926                 res.close();
927         }
928     }    
929     
930     protected abstract PoxPayloadOut createNonExistenceItemInstance(String commonPartName, String identifier);
931     
932     /* (non-Javadoc)
933      * @see org.collectionspace.services.client.test.ServiceTest#updateNonExistent(java.lang.String)
934      */
935     @Test(dataProvider = "testName",
936         dependsOnMethods = {"create", "update", "updateNonExistent"})
937     public void updateNonExistentItem(String testName) throws Exception {
938         // Perform setup.
939         setupUpdateNonExistent();
940
941         // Submit the request to the service and store the response.
942         // Note: The ID used in this 'create' call may be arbitrary.
943         // The only relevant ID may be the one used in update(), below.
944         AuthorityClient client = (AuthorityClient)this.getClientInstance();
945         PoxPayloadOut multipart = createNonExistenceItemInstance(client.getItemCommonPartName(), NON_EXISTENT_ID);
946         Response res = client.updateItem(knownResourceId, NON_EXISTENT_ID, multipart);
947         try {
948                 int statusCode = res.getStatus();
949         
950                 // Check the status code of the response: does it match
951                 // the expected response(s)?
952                 if (logger.isDebugEnabled()) {
953                         logger.debug(testName + ": status = " + statusCode);
954                 }
955                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
956                                 invalidStatusCodeMessage(testRequestType, statusCode));
957                 Assert.assertEquals(statusCode, testExpectedStatusCode);
958         } finally {
959                 res.close();
960         }
961     }
962         
963     //
964     // Methods to persuade TestNG to follow the correct test dependency path
965     //
966     
967     @Test(dataProvider = "testName",
968                 dependsOnMethods = {"createItem"})
969     public void baseAuthorityTests(String testName) {
970         // Do nothing.  Here just to setup a test dependency chain.
971     }
972     
973     /*
974      * For convenience and terseness, this test method is the base of the test execution dependency chain.  Other test methods may
975      * refer to this method in their @Test annotation declarations.
976      */
977     @Override
978     @Test(dataProvider = "testName",
979                 dependsOnMethods = {
980                         "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"})    
981         public void CRUDTests(String testName) {
982                 // TODO Auto-generated method stub
983         }
984         
985     @Override
986     public void cleanUp() {
987         String noTest = System.getProperty("noTestCleanup");
988         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
989             if (logger.isDebugEnabled()) {
990                 logger.debug("Skipping Cleanup phase ...");
991             }
992             return;
993         }
994         
995         AuthorityClient client = (AuthorityClient) this.getClientInstance();
996         String parentResourceId;
997         String itemResourceId;
998         //
999         // Clean up all authority item resources.
1000         //
1001         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
1002             itemResourceId = entry.getKey();
1003             parentResourceId = entry.getValue();
1004             Response response = client.deleteItem(parentResourceId, itemResourceId);
1005             try {
1006                 int status = response.getStatus();
1007                 if (status != Response.Status.OK.getStatusCode()) {
1008                         logger.debug(String.format("Could not deleted authority item '%s' in authority '%s'.",
1009                                         itemResourceId, parentResourceId));
1010                 }
1011             } finally {
1012                 response.close();
1013             }
1014         }
1015         //
1016         // Clean up authority items that were the result of a sync with the SAS
1017         // all the IDs are URN (not CSIDs).  The URNs work for the local items as well
1018         // as the SAS items.
1019         //
1020         for (Map.Entry<String, String> entry : allSASResourceItemIdsCreated.entrySet()) {
1021             itemResourceId = entry.getKey();
1022             parentResourceId = entry.getValue();
1023             // Note: Any non-success responses from the delete operation
1024             // below are ignored and not reported.
1025             client.deleteItem(parentResourceId, itemResourceId).close();
1026         }
1027         //
1028         // Clean up authority items on the SAS using the SAS client.
1029         //
1030         client = (AuthorityClient) this.getSASClientInstance();
1031         for (Map.Entry<String, String> entry : allSASResourceItemIdsCreated.entrySet()) {
1032             itemResourceId = entry.getKey();
1033             parentResourceId = entry.getValue();
1034             client.deleteItem(parentResourceId, itemResourceId).close();
1035         }
1036         //
1037         // Finally, call out superclass's cleanUp method to deleted the local authorities
1038         //
1039         super.cleanUp();
1040         //
1041         // Call out superclass's cleanUp method to delete the SAS authorities
1042         //
1043         super.cleanUp(client);        
1044     }
1045     
1046         protected String getTestAuthorityItemShortId() {
1047                 return getTestAuthorityItemShortId(false);
1048         }
1049
1050         protected String getTestAuthorityItemShortId(boolean makeUnique) {
1051                 String result = TEST_SHORTID;
1052                 
1053                 if (makeUnique == true) {
1054                         result = result + System.currentTimeMillis() + Math.abs(random.nextInt());
1055                 }
1056                 
1057                 return result;
1058         }
1059 }