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