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