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