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