]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
be24d57080f8f170c20051b04e3e60b089853146
[tmp/jakarta-migration.git] /
1 /**
2  * This document is a part of the source code and related artifacts
3  * for CollectionSpace, an open source collections management system
4  * for museums and related institutions:
5  *
6  * http://www.collectionspace.org
7  * http://wiki.collectionspace.org
8  *
9  * Copyright (c)) 2009 Regents of the University of California
10  *
11  * Licensed under the Educational Community License (ECL), Version 2.0.
12  * You may not use this file except in compliance with this License.
13  *
14  * You may obtain a copy of the ECL 2.0 License at
15  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 package org.collectionspace.services.client.test;
24
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.ws.rs.core.MediaType;
31 import javax.ws.rs.core.Response;
32
33 import org.collectionspace.services.OrganizationJAXBSchema;
34 import org.collectionspace.services.client.AbstractCommonListUtils;
35 import org.collectionspace.services.client.AuthorityClient;
36 import org.collectionspace.services.client.CollectionSpaceClient;
37 import org.collectionspace.services.client.ContactClient;
38 import org.collectionspace.services.client.ContactClientUtils;
39 import org.collectionspace.services.client.PayloadOutputPart;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.contact.AddressGroup;
43 import org.collectionspace.services.contact.AddressGroupList;
44 import org.collectionspace.services.contact.ContactsCommon;
45 import org.collectionspace.services.client.OrgAuthorityClient;
46 import org.collectionspace.services.client.OrgAuthorityClientUtils;
47 import org.collectionspace.services.jaxb.AbstractCommonList;
48 import org.collectionspace.services.organization.OrgauthoritiesCommon;
49 import org.collectionspace.services.organization.OrganizationsCommon;
50 import org.collectionspace.services.organization.OrgTermGroup;
51 import org.collectionspace.services.organization.OrgTermGroupList;
52
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.testng.Assert;
56 import org.testng.annotations.AfterClass;
57 import org.testng.annotations.Test;
58
59 /**
60  * OrgAuthorityServiceTest, carries out tests against a
61  * deployed and running OrgAuthority Service.
62  *
63  * $LastChangedRevision$
64  * $LastChangedDate$
65  */
66 public class OrgAuthorityServiceTest extends AbstractAuthorityServiceTest<OrgauthoritiesCommon, OrganizationsCommon> {
67
68     /** The logger. */
69     private final String CLASS_NAME = OrgAuthorityServiceTest.class.getName();
70     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
71
72     /**
73      * Default constructor.  Used to set the short ID for all tests authority items
74      */
75     public OrgAuthorityServiceTest() {
76         super();
77         TEST_SHORTID = "TestOrg";
78     }
79     
80     @Override
81     public String getServicePathComponent() {
82         return OrgAuthorityClient.SERVICE_PATH_COMPONENT;
83     }
84
85     @Override
86     protected String getServiceName() {
87         return OrgAuthorityClient.SERVICE_NAME;
88     }
89     
90     private final String TEST_ORG_NAME = "Test Org";
91     private final String TEST_ORG_MAIN_BODY_NAME = "The real official test organization";
92     private final String TEST_ORG_FOUNDING_PLACE = "Anytown, USA";
93     private final String TEST_ORG_FOUNDING_DATE = "May 26, 1907";
94     
95     /** The known item resource short ID. */
96     private String knownItemResourceShortIdentifer = null;
97     
98     /** The known contact resource id. */
99     private String knownContactResourceId = null;
100     
101     /** The all contact resource ids created. */
102     private Map<String, String> allContactResourceIdsCreated = new HashMap<String, String>();
103
104     /**
105      * 
106      */
107     protected void setKnownItemResource(String id, String shortIdentifer) {
108         knownItemResourceId = id;
109         knownItemResourceShortIdentifer = shortIdentifer;
110     }
111
112     /* (non-Javadoc)
113      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
114      */
115     @Override
116     protected CollectionSpaceClient getClientInstance() {
117         return new OrgAuthorityClient();
118     }
119
120         @Override
121         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
122         return new OrgAuthorityClient(clientPropertiesFilename);
123         }
124
125     @Override
126     protected PoxPayloadOut createInstance(String identifier) {
127         OrgAuthorityClient client = new OrgAuthorityClient();
128         String displayName = "displayName-" + identifier;
129         PoxPayloadOut multipart = OrgAuthorityClientUtils.createOrgAuthorityInstance(
130                 displayName, identifier, client.getCommonPartName());
131         return multipart;
132     }
133
134     @Override
135     protected PoxPayloadOut createItemInstance(String parentCsid, String identifier) {
136         String headerLabel = new OrgAuthorityClient().getItemCommonPartName();
137         
138         String shortId = TEST_SHORTID + identifier;
139         Map<String, String> testOrgMap = new HashMap<String, String>();
140         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
141         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, TEST_ORG_FOUNDING_DATE);
142         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, TEST_ORG_FOUNDING_PLACE);
143         
144         List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
145         OrgTermGroup term = new OrgTermGroup();
146         term.setTermDisplayName(TEST_ORG_NAME);
147         term.setTermName(TEST_ORG_NAME);
148         term.setMainBodyName(TEST_ORG_MAIN_BODY_NAME);
149         terms.add(term);
150
151         return OrgAuthorityClientUtils.createOrganizationInstance(identifier, testOrgMap, terms, headerLabel);
152     }
153
154         @Override
155         protected String createItemInAuthority(AuthorityClient client, String authorityId, String shortId) {
156                 return createItemInAuthority(client, authorityId, shortId, null /*refname*/);
157         }
158     
159     /**
160      * Creates the item in authority.
161      *
162      * @param vcsid the vcsid
163      * @param authRefName the auth ref name
164      * @return the string
165      */
166     private String createItemInAuthority(AuthorityClient client, String vcsid, String shortId, String authRefName) {
167
168         final String testName = "createItemInAuthority";
169         if (logger.isDebugEnabled()) {
170             logger.debug(testName + ":...");
171         }
172         
173         Map<String, String> testOrgMap = new HashMap<String, String>();
174         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
175         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, TEST_ORG_FOUNDING_DATE);
176         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, TEST_ORG_FOUNDING_PLACE);
177         
178         List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
179         OrgTermGroup term = new OrgTermGroup();
180         term.setTermDisplayName(TEST_ORG_NAME);
181         term.setTermName(TEST_ORG_NAME);
182         term.setMainBodyName(TEST_ORG_MAIN_BODY_NAME);
183         terms.add(term);
184         
185         Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String, List<String>>();
186         List<String> testOrgContactNames = new ArrayList<String>();
187         testOrgContactNames.add("joe@example.org");
188         testOrgContactNames.add("sally@example.org");
189         testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
190
191         String newID = OrgAuthorityClientUtils.createItemInAuthority(
192                 vcsid, authRefName, testOrgMap, terms, testOrgRepeatablesMap, (OrgAuthorityClient) client);
193
194         // Store the ID returned from the first item resource created
195         // for additional tests below.
196         if (knownItemResourceId == null) {
197             setKnownItemResource(newID, shortId);
198             if (logger.isDebugEnabled()) {
199                 logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId);
200             }
201         }
202
203         // Store the IDs from any item resources created
204         // by tests, along with the IDs of their parents, so these items
205         // can be deleted after all tests have been run.
206         allResourceItemIdsCreated.put(newID, vcsid);
207
208         return newID;
209     }
210
211     /**
212      * Creates the contact.
213      *
214      * @param testName the test name
215      */
216     @Test(dataProvider = "testName", groups = {"create"},
217                 dependsOnMethods = {"createItem"})
218     public void createContact(String testName) {
219         setupCreate();
220         String newID = createContactInItem(knownResourceId, knownItemResourceId);
221     }
222
223     /**
224      * Creates the contact in item.
225      *
226      * @param parentcsid the parentcsid
227      * @param itemcsid the itemcsid
228      * @return the string
229      */
230     private String createContactInItem(String parentcsid, String itemcsid) {
231
232         final String testName = "createContactInItem";
233         if (logger.isDebugEnabled()) {
234             logger.debug(getTestBanner(testName, CLASS_NAME));
235         }
236         setupCreate();
237
238         // Submit the request to the service and store the response.
239         OrgAuthorityClient client = new OrgAuthorityClient();
240         String identifier = createIdentifier();
241         PoxPayloadOut multipart =
242                 ContactClientUtils.createContactInstance(parentcsid,
243                 itemcsid, identifier, new ContactClient().getCommonPartName());
244
245         String newID = null;
246         Response res = client.createContact(parentcsid, itemcsid, multipart);
247         try {
248             assertStatusCode(res, testName);
249             newID = OrgAuthorityClientUtils.extractId(res);
250         } finally {
251                 if (res != null) {
252                 res.close();
253             }
254         }
255
256         // Store the ID returned from the first contact resource created
257         // for additional tests below.
258         if (knownContactResourceId == null) {
259             knownContactResourceId = newID;
260             if (logger.isDebugEnabled()) {
261                 logger.debug(testName + ": knownContactResourceId=" + knownContactResourceId);
262             }
263         }
264
265         // Store the IDs from any contact resources created
266         // by tests, along with the IDs of their parent items,
267         // so these items can be deleted after all tests have been run.
268         allContactResourceIdsCreated.put(newID, itemcsid);
269
270         return newID;
271     }
272
273     /**
274      * Creates the contact list.
275      *
276      * @param testName the test name
277      * @throws Exception the exception
278      */
279     @Test(dataProvider = "testName", groups = {"createList"},
280                 dependsOnMethods = {"createItemList"})
281     public void createContactList(String testName) throws Exception {
282         // Add contacts to the initially-created, known item record.
283         for (int j = 0; j < nItemsToCreateInList; j++) {
284             createContact(testName);
285         }
286     }
287
288     // ---------------------------------------------------------------
289     // CRUD tests : READ tests
290     // ---------------------------------------------------------------
291     // Success outcomes
292     /* (non-Javadoc)
293      * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#read(java.lang.String)
294      */
295     @Override
296 //    @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
297 //    groups = {"read"}, dependsOnGroups = {"create"})
298     public void read(String testName) throws Exception {
299         readInternal(testName, knownResourceId, null);
300     }
301
302     /**
303      * Read by name.
304      *
305      * @param testName the test name
306      * @throws Exception the exception
307      */
308 //    @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
309 //    groups = {"read"}, dependsOnGroups = {"create"})
310     public void readByName(String testName) throws Exception {
311         readInternal(testName, null, knownResourceShortIdentifer);
312     }
313
314     protected void readInternal(String testName, String CSID, String shortId) {
315         // Perform setup.
316         setupRead();
317
318         // Submit the request to the service and store the response.
319         OrgAuthorityClient client = new OrgAuthorityClient();
320         Response res = null;
321         if (CSID != null) {
322             res = client.read(CSID);
323         } else if (shortId != null) {
324             res = client.readByName(shortId);
325         } else {
326             Assert.fail("readInternal: Internal error. One of CSID or shortId must be non-null");
327         }
328         try {
329             assertStatusCode(res, testName);            
330             //FIXME: remove the following try catch once Aron fixes signatures
331             try {
332                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
333                 OrgauthoritiesCommon orgAuthority = (OrgauthoritiesCommon) extractPart(input,
334                         new OrgAuthorityClient().getCommonPartName(), OrgauthoritiesCommon.class);
335                 if (logger.isDebugEnabled()) {
336                     logger.debug(objectAsXmlString(orgAuthority, OrgauthoritiesCommon.class));
337                 }
338                 Assert.assertNotNull(orgAuthority);
339             } catch (Exception e) {
340                 throw new RuntimeException(e);
341             }
342         } finally {
343                 if (res != null) {
344                 res.close();
345             }
346         }
347     }
348
349     /**
350      * Read item in Named Auth.
351      * 
352      * TODO Enable this if we really need this - it is a funky case, where we would have
353      * the shortId of the item, but the CSID of the parent authority!? Unlikely.
354      *
355      * @param testName the test name
356      * @throws Exception the exception
357     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
358     groups = {"readItem"}, dependsOnGroups = {"read"})
359     public void readItemInNamedAuth(String testName) throws Exception {
360     readItemInternal(testName, null, knownResourceShortIdentifer, knownItemResourceId, null);
361     }
362      */
363     
364     /**
365      * Read named item.
366      *
367      * @param testName the test name
368      * @throws Exception the exception
369      */
370     @Test(dataProvider = "testName", groups = {"readItem"},
371                 dependsOnMethods = {"readItemInNamedAuth"})
372     public void readNamedItem(String testName) throws Exception {
373         readItemInternal(testName, knownResourceId, null, null, knownItemResourceShortIdentifer);
374     }
375     
376     /**
377      * Read item in Named Auth.
378      *
379      * @param testName the test name
380      * @throws Exception the exception
381      */
382     @Test(dataProvider = "testName", groups = {"readItem"},
383                 dependsOnMethods = {"readItem"})
384     public void readItemInNamedAuth(String testName) throws Exception {
385         readItemInternal(testName, null, knownResourceShortIdentifer, knownItemResourceId, null);
386     }
387
388     /**
389      * Read Named item in Named Auth.
390      *
391      * @param testName the test name
392      * @throws Exception the exception
393      */
394     @Test(dataProvider = "testName", groups = {"readItem"},
395                 dependsOnMethods = {"readItem"})
396     public void readNamedItemInNamedAuth(String testName) throws Exception {
397         readItemInternal(testName, null, knownResourceShortIdentifer, null, knownItemResourceShortIdentifer);
398     }
399
400     protected void readItemInternal(String testName,
401             String authCSID, String authShortId, String itemCSID, String itemShortId)
402             throws Exception {
403         // Perform setup.
404         setupRead();
405
406         // Submit the request to the service and store the response.
407         OrgAuthorityClient client = new OrgAuthorityClient();
408         Response res = null;
409         if (authCSID != null) {
410             if (itemCSID != null) {
411                 res = client.readItem(authCSID, itemCSID);
412             } else if (itemShortId != null) {
413                 res = client.readNamedItem(authCSID, itemShortId);
414             } else {
415                 Assert.fail("readInternal: Internal error. One of CSID or shortId must be non-null");
416             }
417         } else if (authShortId != null) {
418             if (itemCSID != null) {
419                 res = client.readItemInNamedAuthority(authShortId, itemCSID);
420             } else if (itemShortId != null) {
421                 res = client.readNamedItemInNamedAuthority(authShortId, itemShortId);
422             } else {
423                 Assert.fail("readInternal: Internal error. One of CSID or shortId must be non-null");
424             }
425         } else {
426             Assert.fail("readInternal: Internal error. One of authCSID or authShortId must be non-null");
427         }
428         try {
429             assertStatusCode(res, testName);
430             // Check whether we've received a organization.
431             PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
432             OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
433                     client.getItemCommonPartName(), OrganizationsCommon.class);
434             Assert.assertNotNull(organization);
435             boolean showFull = true;
436             if (showFull && logger.isDebugEnabled()) {
437                 logger.debug(testName + ": returned payload:");
438                 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
439             }
440
441             // Check that the organization item is within the expected OrgAuthority.
442             Assert.assertEquals(organization.getInAuthority(), knownResourceId);
443
444             // Verify the number and contents of values in a repeatable field,
445             // as created in the instance record used for testing.
446             List<String> contactNames = organization.getContactNames().getContactName();
447             Assert.assertTrue(contactNames.size() > 0);
448             Assert.assertNotNull(contactNames.get(0));
449
450         } finally {
451                 if (res != null) {
452                 res.close();
453             }
454         }
455     }
456     
457     @Override
458     protected void verifyReadItemInstance(OrganizationsCommon item) throws Exception {
459         List<String> contactNames = item.getContactNames().getContactName();
460         Assert.assertTrue(contactNames.size() > 0);
461         Assert.assertNotNull(contactNames.get(0));
462     }
463     
464     /**
465      * Verify illegal item display name.
466      *
467      * @param testName the test name
468      * @throws Exception the exception
469      */
470     @Test(dataProvider = "testName")
471     public void verifyIllegalItemDisplayName(String testName) throws Exception {
472         // Perform setup for read.
473         setupRead();
474         //
475         // First read our known resource.
476         //
477         OrgAuthorityClient client = new OrgAuthorityClient();
478         Response res = client.readItem(knownResourceId, knownItemResourceId);
479         OrganizationsCommon organization = null;
480         try {
481             assertStatusCode(res, testName);            
482             // Check whether organization has expected displayName.
483             PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
484             organization = (OrganizationsCommon) extractPart(input,
485                     client.getItemCommonPartName(), OrganizationsCommon.class);
486             Assert.assertNotNull(organization);
487         } finally {
488                 if (res != null) {
489                 res.close();
490             }
491         }
492         
493         //
494         // Make an invalid UPDATE request, without a display name
495         //
496         OrgTermGroupList termList = organization.getOrgTermGroupList();
497         Assert.assertNotNull(termList);
498         List<OrgTermGroup> terms = termList.getOrgTermGroup();
499         Assert.assertNotNull(terms);
500         Assert.assertTrue(terms.size() > 0);
501         terms.get(0).setTermDisplayName(null);
502         terms.get(0).setTermName(null);
503         
504         setupUpdateWithInvalidBody(); // we expect a failure
505         // Submit the updated resource to the service and store the response.
506         PoxPayloadOut output = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
507         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(),
508                         organization);
509         res = client.updateItem(knownResourceId, knownItemResourceId, output);
510         try {
511                 assertStatusCode(res, testName);
512         } finally {
513                 if (res != null) {
514                 res.close();
515             }
516         }
517     }
518
519     /**
520      * Read contact.
521      *
522      * @param testName the test name
523      * @throws Exception the exception
524      */
525     @Test(dataProvider = "testName", groups = {"readItem"},
526                 dependsOnMethods = {"readItem"})
527     public void readContact(String testName) throws Exception {
528         // Perform setup.
529         setupRead();
530
531         // Submit the request to the service and store the response.
532         OrgAuthorityClient client = new OrgAuthorityClient();
533         Response res =client.readContact(knownResourceId, knownItemResourceId,
534                 knownContactResourceId);
535         try {
536             assertStatusCode(res, testName);            
537             // Check whether we've received a contact.
538             PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
539             ContactsCommon contact = (ContactsCommon) extractPart(input,
540                     new ContactClient().getCommonPartName(), ContactsCommon.class);
541             Assert.assertNotNull(contact);
542             boolean showFull = true;
543             if (showFull && logger.isDebugEnabled()) {
544                 logger.debug(testName + ": returned payload:");
545                 logger.debug(objectAsXmlString(contact, ContactsCommon.class));
546             }
547             Assert.assertEquals(contact.getInAuthority(), knownResourceId);
548             Assert.assertEquals(contact.getInItem(), knownItemResourceId);
549         } finally {
550                 if (res != null) {
551                 res.close();
552             }
553         }
554     }
555
556     /**
557      * Read contact non existent.
558      *
559      * @param testName the test name
560      */
561     @Test(dataProvider = "testName", groups = {"readItem"},
562                 dependsOnMethods = {"readContact"})
563     public void readContactNonExistent(String testName) {
564         // Perform setup.
565         setupReadNonExistent();
566
567         // Submit the request to the service and store the response.
568         OrgAuthorityClient client = new OrgAuthorityClient();
569         Response res = client.readContact(knownResourceId, knownItemResourceId, NON_EXISTENT_ID);
570         try {
571             int statusCode = res.getStatus();
572
573             // Check the status code of the response: does it match
574             // the expected response(s)?
575             if (logger.isDebugEnabled()) {
576                 logger.debug(testName + ": status = " + statusCode);
577             }
578             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
579                     invalidStatusCodeMessage(testRequestType, statusCode));
580             Assert.assertEquals(statusCode, testExpectedStatusCode);
581         } finally {
582                 if (res != null) {
583                 res.close();
584             }
585         }
586     }
587
588     /**
589      * Read item list.
590      */
591     @Override
592 //      @Test(groups = {"readList"}, dependsOnMethods = {"readList"})
593     public void readItemList(String testName) {
594         readItemList(knownAuthorityWithItems, null);
595     }
596
597     /**
598      * Read item list by authority name.
599      */
600     @Override
601 //    @Test(dataProvider = "testName",
602 //              dependsOnMethods = {"readItem"})
603     public void readItemListByName(String testName) {
604         readItemList(null, READITEMS_SHORT_IDENTIFIER);
605     }
606
607     /**
608      * Read item list.
609      *
610      * @param vcsid the vcsid
611      * @param name the name
612      */
613     private void readItemList(String vcsid, String name) {
614
615         final String testName = "readItemList";
616         // Perform setup.
617         setupReadList();
618
619         // Submit the request to the service and store the response.
620         OrgAuthorityClient client = new OrgAuthorityClient();
621         Response res = null;
622         if (vcsid != null) {
623             res = client.readItemList(vcsid, null, null);
624         } else if (name != null) {
625             res = client.readItemListForNamedAuthority(name, null, null);
626         } else {
627             Assert.fail("readItemList passed null csid and name!");
628         }
629         
630         AbstractCommonList list = null;
631         try {
632             assertStatusCode(res, testName);            
633             list = res.readEntity(AbstractCommonList.class);
634         } finally {
635                 if (res != null) {
636                 res.close();
637             }
638         }
639         
640         List<AbstractCommonList.ListItem> items = list.getListItem();
641         int nItemsReturned = items.size();
642         // There will be 'nItemsToCreateInList'
643         // items created by the createItemList test,
644         // all associated with the same parent resource.
645         int nExpectedItems = nItemsToCreateInList;
646         if (logger.isDebugEnabled()) {
647             logger.debug(testName + ": Expected "
648                     + nExpectedItems + " items; got: " + nItemsReturned);
649         }
650         Assert.assertEquals(nItemsReturned, nExpectedItems);
651
652         for (AbstractCommonList.ListItem item : items) {
653             String value =
654                     AbstractCommonListUtils.ListItemGetElementValue(item, OrganizationJAXBSchema.REF_NAME);
655             Assert.assertTrue((null != value), "Item refName is null!");
656             value =
657                     AbstractCommonListUtils.ListItemGetElementValue(item, OrganizationJAXBSchema.TERM_DISPLAY_NAME);
658             Assert.assertTrue((null != value), "Item termDisplayName is null!");
659         }
660         if (logger.isTraceEnabled()) {
661             AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
662         }
663     }
664
665     /**
666      * Read contact list.
667      */
668     @Test(groups = {"readList"},
669                 dependsOnMethods = {"org.collectionspace.services.client.test.AbstractAuthorityServiceTest.readItemList"})
670     public void readContactList() {
671         readContactList(knownResourceId, knownItemResourceId);
672     }
673
674     /**
675      * Read contact list.
676      *
677      * @param parentcsid the parentcsid
678      * @param itemcsid the itemcsid
679      */
680     private void readContactList(String parentcsid, String itemcsid) {
681         final String testName = "readContactList";
682         // Perform setup.
683         setupReadList();
684
685         // Submit the request to the service and store the response.
686         OrgAuthorityClient client = new OrgAuthorityClient();
687         Response res = client.readContactList(parentcsid, itemcsid);
688         AbstractCommonList list = null;
689         try {
690             assertStatusCode(res, testName);
691             list = res.readEntity(AbstractCommonList.class);
692         } finally {
693                 if (res != null) {
694                 res.close();
695             }
696         }
697
698         List<AbstractCommonList.ListItem> listitems =
699             list.getListItem();
700         int nItemsReturned = listitems.size();
701         // There will be one item created, associated with a
702         // known parent resource, by the createItem test.
703         //
704         // In addition, there will be 'nItemsToCreateInList'
705         // additional items created by the createItemList test,
706         // all associated with the same parent resource.
707         int nExpectedItems = nItemsToCreateInList + 1;
708         if (logger.isDebugEnabled()) {
709             logger.debug(testName + ": Expected "
710                     + nExpectedItems + " items; got: " + nItemsReturned);
711         }
712         Assert.assertEquals(nItemsReturned, nExpectedItems);
713
714         // Optionally output additional data about list members for debugging.
715         boolean iterateThroughList = false;
716         if (iterateThroughList && logger.isDebugEnabled()) {
717             AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
718         }
719     }
720
721     /**
722      * Update contact.
723      *
724      * @param testName the test name
725      * @throws Exception the exception
726      */
727     @Test(dataProvider = "testName", groups = {"update"},
728                 dependsOnMethods = {"org.collectionspace.services.client.test.AbstractAuthorityServiceTest.updateItem"})
729     public void updateContact(String testName) throws Exception {
730         // Perform setup.
731         setupUpdate();
732
733         // Retrieve the contents of a resource to update.
734         OrgAuthorityClient client = new OrgAuthorityClient();
735         Response res = client.readContact(knownResourceId, knownItemResourceId, knownContactResourceId);
736         ContactsCommon contact = null;
737         try {
738             assertStatusCode(res, testName);            
739             if (logger.isDebugEnabled()) {
740                 logger.debug("got Contact to update with ID: "
741                         + knownContactResourceId
742                         + " in item: " + knownItemResourceId
743                         + " in parent: " + knownResourceId);
744             }
745             PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
746             contact = (ContactsCommon) extractPart(input,
747                     new ContactClient().getCommonPartName(), ContactsCommon.class);
748             Assert.assertNotNull(contact);
749         } finally {
750                 if (res != null) {
751                 res.close();
752             }
753         }
754
755         // Verify the contents of this resource
756         AddressGroupList addressGroupList = contact.getAddressGroupList();
757         Assert.assertNotNull(addressGroupList);
758         List<AddressGroup> addressGroups = addressGroupList.getAddressGroup();
759         Assert.assertNotNull(addressGroups);
760         Assert.assertTrue(addressGroups.size() > 0);
761         String addressPlace1 = addressGroups.get(0).getAddressPlace1();
762         Assert.assertNotNull(addressPlace1);
763
764         // Update the contents of this resource.
765         addressGroups.get(0).setAddressPlace1("updated-" + addressPlace1);
766         contact.setAddressGroupList(addressGroupList);
767         if (logger.isDebugEnabled()) {
768             logger.debug("to be updated Contact");
769             logger.debug(objectAsXmlString(contact,
770                     ContactsCommon.class));
771         }
772
773         // Submit the updated resource to the service and store the response.
774         PoxPayloadOut output = new PoxPayloadOut(ContactClient.SERVICE_PAYLOAD_NAME);
775         PayloadOutputPart commonPart = output.addPart(contact, MediaType.APPLICATION_XML_TYPE);
776         commonPart.setLabel(new ContactClient().getCommonPartName());
777
778         res = client.updateContact(knownResourceId, knownItemResourceId, knownContactResourceId, output);
779         try {
780                 assertStatusCode(res, testName);
781                 // Retrieve the updated resource and verify that its contents exist.
782                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
783                 ContactsCommon updatedContact =
784                         (ContactsCommon) extractPart(input,
785                         new ContactClient().getCommonPartName(), ContactsCommon.class);
786                 Assert.assertNotNull(updatedContact);
787         
788                 // Verify that the updated resource received the correct data.
789                 Assert.assertEquals(updatedContact.getAddressGroupList().getAddressGroup().get(0).getAddressPlace1(),
790                         contact.getAddressGroupList().getAddressGroup().get(0).getAddressPlace1(),
791                         "Data in updated object did not match submitted data.");
792         } finally {
793                 if (res != null) {
794                 res.close();
795             }
796         }
797     }
798
799     /**
800      * Update non existent contact.
801      *
802      * @param testName the test name
803      * @throws Exception the exception
804      */
805     @Test(dataProvider = "testName", groups = {"update"},
806                 dependsOnMethods = {"updateContact", "testContactSubmitRequest"})
807     public void updateNonExistentContact(String testName) throws Exception {
808         // Currently a no-op test
809     }
810
811     // ---------------------------------------------------------------
812     // CRUD tests : DELETE tests
813     // ---------------------------------------------------------------
814     // Success outcomes
815     // Note: delete sub-resources in ascending hierarchical order,
816     // before deleting their parents.
817     /**
818      * Delete contact.
819      *
820      * @param testName the test name
821      * @throws Exception the exception
822      */
823     @Test(dataProvider = "testName", groups = {"delete"},
824                 dependsOnMethods = {"updateContact"})
825     public void deleteContact(String testName) throws Exception {
826         // Perform setup.
827         setupDelete();
828
829         if (logger.isDebugEnabled()) {
830             logger.debug("parentcsid =" + knownResourceId
831                     + " itemcsid = " + knownItemResourceId
832                     + " csid = " + knownContactResourceId);
833         }
834
835         // Submit the request to the service and store the response.
836         OrgAuthorityClient client = new OrgAuthorityClient();
837         Response res = client.deleteContact(knownResourceId, knownItemResourceId, knownContactResourceId);
838         try {
839             assertStatusCode(res, testName);
840         } finally {
841                 if (res != null) {
842                 res.close();
843             }
844         }
845     }
846
847     @Override
848     public void delete(String testName) throws Exception {
849         // Do nothing.  See localDelete().  This ensure proper test order.
850     }
851     
852     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
853     public void localDelete(String testName) throws Exception {
854         super.delete(testName);
855     }
856
857     @Override
858     public void deleteItem(String testName) throws Exception {
859         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
860         // its dependencies will get run first and then we can call the base class' delete method.
861     }
862     
863     @Test(dataProvider = "testName", groups = {"delete"},
864         dependsOnMethods = {"verifyIllegalItemDisplayName", "testContactSubmitRequest", "deleteContact"})
865     public void localDeleteItem(String testName) throws Exception {
866         super.deleteItem(testName);
867     }    
868     
869     /**
870      * Delete non existent contact.
871      *
872      * @param testName the test name
873      */
874     @Test(dataProvider = "testName", groups = {"delete"},
875                 dependsOnMethods = {"deleteContact"})
876     public void deleteNonExistentContact(String testName) {
877         // Perform setup.
878         setupDeleteNonExistent();
879
880         // Submit the request to the service and store the response.
881         OrgAuthorityClient client = new OrgAuthorityClient();
882         Response res = client.deleteContact(knownResourceId, knownItemResourceId, NON_EXISTENT_ID);
883         try {
884             assertStatusCode(res, testName);
885         } finally {
886                 if (res != null) {
887                 res.close();
888             }
889         }
890     }
891
892     /**
893      * Test contact submit request.
894      */
895     @Test(dependsOnMethods = {"createContact", "readContact", "testItemSubmitRequest"})
896     public void testContactSubmitRequest() {
897
898         // Expected status code: 200 OK
899         final int EXPECTED_STATUS = Response.Status.OK.getStatusCode();
900
901         // Submit the request to the service and store the response.
902         String method = ServiceRequestType.READ.httpMethodName();
903         String url = getContactResourceURL(knownResourceId,
904                 knownItemResourceId, knownContactResourceId);
905         int statusCode = submitRequest(method, url);
906
907         // Check the status code of the response: does it match
908         // the expected response(s)?
909         if (logger.isDebugEnabled()) {
910             logger.debug("testContactSubmitRequest: url=" + url
911                     + " status=" + statusCode);
912         }
913         Assert.assertEquals(statusCode, EXPECTED_STATUS);
914
915     }
916
917     // ---------------------------------------------------------------
918     // Cleanup of resources created during testing
919     // ---------------------------------------------------------------
920     /**
921      * Deletes all resources created by tests, after all tests have been run.
922      *
923      * This cleanup method will always be run, even if one or more tests fail.
924      * For this reason, it attempts to remove all resources created
925      * at any point during testing, even if some of those resources
926      * may be expected to be deleted by certain tests.
927      */
928     @AfterClass(alwaysRun = true)
929     @Override
930     public void cleanUp() {
931         String noTest = System.getProperty("noTestCleanup");
932         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
933             if (logger.isDebugEnabled()) {
934                 logger.debug("Skipping Cleanup phase ...");
935             }
936             return;
937         }
938         if (logger.isDebugEnabled()) {
939             logger.debug("Cleaning up temporary resources created for testing ...");
940         }
941
942         String parentResourceId;
943         String itemResourceId;
944         String contactResourceId;
945         // Clean up contact resources.
946         parentResourceId = knownResourceId;
947         OrgAuthorityClient client = new OrgAuthorityClient();
948         for (Map.Entry<String, String> entry : allContactResourceIdsCreated.entrySet()) {
949             contactResourceId = entry.getKey();
950             itemResourceId = entry.getValue();
951             // Note: Any non-success responses from the delete operation
952             // below are ignored and not reported.
953             client.deleteContact(parentResourceId, itemResourceId, contactResourceId).close();
954         }
955
956         // Clean up parent resources.
957         super.cleanUp();
958
959     }
960
961     // ---------------------------------------------------------------
962     // Utility methods used by tests above
963     // ---------------------------------------------------------------
964     /* (non-Javadoc)
965      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
966      */
967     /**
968      * Gets the item service path component.
969      *
970      * @return the item service path component
971      */
972     public String getItemServicePathComponent() {
973         return AuthorityClient.ITEMS;
974     }
975
976     /**
977      * Gets the contact service path component.
978      *
979      * @return the contact service path component
980      */
981     public String getContactServicePathComponent() {
982         return ContactClient.SERVICE_PATH_COMPONENT;
983     }
984
985     /**
986      * Returns the root URL for the item service.
987      *
988      * This URL consists of a base URL for all services, followed by
989      * a path component for the owning parent, followed by the
990      * path component for the items.
991      *
992      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
993      * parent authority resource of the relevant item resource.
994      *
995      * @return The root URL for the item service.
996      */
997     protected String getItemServiceRootURL(String parentResourceIdentifier) {
998         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
999     }
1000
1001     /**
1002      * Returns the URL of a specific item resource managed by a service, and
1003      * designated by an identifier (such as a universally unique ID, or UUID).
1004      *
1005      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
1006      * parent authority resource of the relevant item resource.
1007      *
1008      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
1009      * item resource.
1010      *
1011      * @return The URL of a specific item resource managed by a service.
1012      */
1013     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
1014         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
1015     }
1016
1017     /**
1018      * Returns the root URL for the contact service.
1019      *
1020      * This URL consists of a base URL for all services, followed by
1021      * a path component for the owning authority, followed by the
1022      * path component for the owning item, followed by the path component
1023      * for the contact service.
1024      *
1025      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
1026      * parent authority resource of the relevant item resource.
1027      *
1028      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
1029      * item resource.
1030      *
1031      * @return The root URL for the contact service.
1032      */
1033     protected String getContactServiceRootURL(String parentResourceIdentifier,
1034             String itemResourceIdentifier) {
1035         return getItemResourceURL(parentResourceIdentifier, itemResourceIdentifier) + "/"
1036                 + getContactServicePathComponent();
1037     }
1038
1039     /**
1040      * Returns the URL of a specific contact resource managed by a service, and
1041      * designated by an identifier (such as a universally unique ID, or UUID).
1042      *
1043      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
1044      * parent resource of the relevant item resource.
1045      *
1046      * @param  resourceIdentifier  An identifier (such as a UUID) for an
1047      * item resource.
1048      *
1049      * @return The URL of a specific resource managed by a service.
1050      */
1051     protected String getContactResourceURL(String parentResourceIdentifier,
1052             String itemResourceIdentifier, String contactResourceIdentifier) {
1053         return getContactServiceRootURL(parentResourceIdentifier,
1054                 itemResourceIdentifier) + "/" + contactResourceIdentifier;
1055     }
1056
1057         @Override
1058         public void authorityTests(String testName) {
1059                 // TODO Auto-generated method stub
1060                 
1061         }
1062
1063         @Override
1064         protected OrganizationsCommon updateItemInstance(OrganizationsCommon organizationsCommon) {
1065                             
1066             OrgTermGroupList termList = organizationsCommon.getOrgTermGroupList();
1067             Assert.assertNotNull(termList);
1068             List<OrgTermGroup> terms = termList.getOrgTermGroup();
1069             Assert.assertNotNull(terms);
1070             Assert.assertTrue(terms.size() > 0);
1071             terms.get(0).setTermDisplayName("updated-" + terms.get(0).getTermDisplayName());
1072             terms.get(0).setTermName("updated-" + terms.get(0).getTermName());
1073             organizationsCommon.setOrgTermGroupList(termList);
1074
1075             return organizationsCommon;
1076         }
1077
1078         @Override
1079         protected void compareUpdatedItemInstances(OrganizationsCommon original,
1080                         OrganizationsCommon updated) throws Exception {
1081             
1082             OrgTermGroupList originalTermList = original.getOrgTermGroupList();
1083             Assert.assertNotNull(originalTermList);
1084             List<OrgTermGroup> originalTerms = originalTermList.getOrgTermGroup();
1085             Assert.assertNotNull(originalTerms);
1086             Assert.assertTrue(originalTerms.size() > 0);
1087             
1088             OrgTermGroupList updatedTermList = updated.getOrgTermGroupList();
1089             Assert.assertNotNull(updatedTermList);
1090             List<OrgTermGroup> updatedTerms = updatedTermList.getOrgTermGroup();
1091             Assert.assertNotNull(updatedTerms);
1092             Assert.assertTrue(updatedTerms.size() > 0);
1093             
1094             Assert.assertEquals(updatedTerms.get(0).getTermDisplayName(),
1095                 originalTerms.get(0).getTermDisplayName(),
1096                 "Value in updated record did not match submitted data.");
1097         }
1098
1099         @Override
1100         protected PoxPayloadOut createInstance(String commonPartName,
1101                         String identifier) {
1102         String shortId = identifier;
1103         String displayName = "displayName-" + shortId;
1104         //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
1105         PoxPayloadOut result = OrgAuthorityClientUtils.createOrgAuthorityInstance(
1106                 displayName, shortId, commonPartName);
1107         return result;
1108         }
1109
1110         @Override
1111         protected PoxPayloadOut createNonExistenceInstance(String commonPartName,
1112                         String identifier) {
1113         String shortId = identifier;
1114         String displayName = "displayName-" + shortId;
1115         //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
1116         PoxPayloadOut result = OrgAuthorityClientUtils.createOrgAuthorityInstance(
1117                 displayName, shortId, commonPartName);
1118         return result;
1119         }
1120         
1121     protected PoxPayloadOut createNonExistenceItemInstance(String commonPartName,
1122                 String identifier) {
1123         Map<String, String> nonexOrgMap = new HashMap<String, String>();
1124         nonexOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, "nonExistent");
1125         PoxPayloadOut result =
1126                 OrgAuthorityClientUtils.createOrganizationInstance(
1127                 knownResourceRefName,
1128                 nonexOrgMap, OrgAuthorityClientUtils.getTermGroupInstance(TEST_ORG_NAME), commonPartName);
1129         return result;
1130     }
1131
1132         @Override
1133         protected OrgauthoritiesCommon updateInstance(OrgauthoritiesCommon orgauthoritiesCommon) {
1134                 OrgauthoritiesCommon result = new OrgauthoritiesCommon();
1135                 
1136         result.setDisplayName("updated-" + orgauthoritiesCommon.getDisplayName());
1137         result.setVocabType("updated-" + orgauthoritiesCommon.getVocabType());
1138         
1139                 return result;
1140         }
1141
1142         @Override
1143         protected void compareUpdatedInstances(OrgauthoritiesCommon original,
1144                         OrgauthoritiesCommon updated) throws Exception {
1145         // Verify that the updated resource received the correct data.
1146         Assert.assertEquals(updated.getDisplayName(),
1147                         original.getDisplayName(),
1148                 "Display name in updated object did not match submitted data.");
1149         }
1150 }