]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9aae6506f1fe6fe8d9a814b1e68f34f054504f19
[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 © 2009 Regents of the University of California
10  *
11  * Licensed under the Educational Community License (ECL), Version 2.0.
12  * You may not use this file except in compliance with this License.
13  *
14  * You may obtain a copy of the ECL 2.0 License at
15  * https://source.collectionspace.org/collection-space/LICENSE.txt
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 package org.collectionspace.services.client.test;
24
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.ws.rs.core.Response;
31
32 import org.collectionspace.services.OrganizationJAXBSchema;
33 import org.collectionspace.services.PersonJAXBSchema;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.OrgAuthorityClient;
36 import org.collectionspace.services.client.OrgAuthorityClientUtils;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
39 import org.collectionspace.services.common.authorityref.AuthorityRefList;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.collectionspace.services.organization.MainBodyGroup;
42 import org.collectionspace.services.organization.MainBodyGroupList;
43 import org.collectionspace.services.organization.OrganizationsCommon;
44
45 import org.jboss.resteasy.client.ClientResponse;
46
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
48 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * LoaninAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Loanin (aka Loans In) Service.
59  *
60  * $LastChangedRevision$
61  * $LastChangedDate$
62  */
63 public class OrgAuthorityAuthRefsTest extends BaseServiceTest {
64
65    /** The logger. */
66     private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
67     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
68
69     // Instance variables specific to this test.
70     final String SERVICE_PATH_COMPONENT = "orgauthorities";
71     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
72     final String ORG_AUTHORITY_NAME = "TestOrgAuth";
73     
74
75     private String knownResourceId = null;
76     private String knownResourceRefName = null;
77     
78     /** The known item id. */
79     private String knownItemResourceId = null;
80     
81     /** The all resource ids created. */
82     private List<String> allResourceIdsCreated = new ArrayList<String>();
83     
84     /** The all item resource ids created. */
85     private Map<String, String> allItemResourceIdsCreated =
86         new HashMap<String, String>();
87     
88     /** The person ids created. */
89     private List<String> personIdsCreated = new ArrayList<String>();
90     
91     // CSID for the instance of the test Person authority
92     // created during testing.
93     private String personAuthCSID = null;
94     
95     /** The organization contact person refNames. */
96     private String organizationContactPersonRefName1 = null;
97     private String organizationContactPersonRefName2 = null;
98
99     // The refName of an Organization item that represents
100     // the sub-body organization of a second Organization item.
101     private String subBodyRefName = null;
102     
103     /** The number of authorityreferences expected. */
104     private final int NUM_AUTH_REFS_EXPECTED = 3;
105
106     protected void setKnownResource( String id, String refName ) {
107         knownResourceId = id;
108         knownResourceRefName = refName;
109     }
110
111     /* (non-Javadoc)
112      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
113      */
114     @Override
115     protected CollectionSpaceClient getClientInstance() {
116         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
117     }
118     
119     /* (non-Javadoc)
120      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
121      */
122     @Override
123         protected AbstractCommonList getAbstractCommonList(
124                         ClientResponse<AbstractCommonList> response) {
125         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
126     }
127
128     // ---------------------------------------------------------------
129     // CRUD tests : CREATE tests
130     // ---------------------------------------------------------------
131     // Success outcomes
132     /**
133      * Creates the with auth refs.
134      *
135      * @param testName the test name
136      * @throws Exception the exception
137      */
138     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
139     public void createWithAuthRefs(String testName) throws Exception {
140
141         if (logger.isDebugEnabled()) {
142             logger.debug(testBanner(testName, CLASS_NAME));
143         }
144         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
145
146         // Create a new Organization Authority resource.
147         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
148         String shortId = createIdentifier();
149         String displayName = "TestOrgAuth-" + shortId;
150         String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
151         MultipartOutput multipart =
152             OrgAuthorityClientUtils.createOrgAuthorityInstance(
153                                 displayName, shortId, orgAuthClient.getCommonPartName());
154
155         // Submit the request to the service and store the response.
156         ClientResponse<Response> res = orgAuthClient.create(multipart);
157         try {
158                 int statusCode = res.getStatus();
159                 // Check the status code of the response: does it match
160                 // the expected response(s)?
161                 //
162                 // Specifically:
163                 // Does it fall within the set of valid status codes?
164                 // Does it exactly match the expected status code?
165                 if(logger.isDebugEnabled()){
166                     logger.debug(testName + ": status = " + statusCode);
167                 }
168                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
169                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
170                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
171         
172                 // Store the IDs from every resource created by tests,
173                 // so they can be deleted after tests have been run.
174                 String newId = extractId(res);
175                 if (knownResourceId == null){
176                         setKnownResource( newId, baseRefName );
177                 }
178                 allResourceIdsCreated.add(newId);
179         } finally {
180             res.releaseConnection();
181         }        
182
183         // Create all the person refs and entities
184         createPersonRefs();
185
186         // Create all the organization sub-body refs and entities
187         createSubBodyOrgRefs();
188
189         // Initialize values for a new Organization item, to be created within
190         // the newly-created Organization Authority resource.
191         //
192         // One or more fields in the Organization item record will
193         // contain references to Persons, via their refNames, as
194         // per the initialization(s) below.
195         Map<String, String> testOrgMap = new HashMap<String,String>();
196         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
197         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
198
199         Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
200         List<String> testOrgContactNames = new ArrayList<String>();
201         testOrgContactNames.add(organizationContactPersonRefName1);
202         testOrgContactNames.add(organizationContactPersonRefName2);
203         testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
204         List<String> testOrgSubBodies = new ArrayList<String>();
205         testOrgSubBodies.add(subBodyRefName);
206         testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
207
208         MainBodyGroupList mainBodyList = new MainBodyGroupList();
209         List<MainBodyGroup> mainBodyGroups = mainBodyList.getMainBodyGroup();
210         MainBodyGroup mainBodyGroup = new MainBodyGroup();
211         mainBodyGroup.setShortName("Test Organization-" + shortId);
212         mainBodyGroup.setLongName("Test Organization Name");
213         mainBodyGroups.add(mainBodyGroup);
214
215         // Finishing creating the new Organization item, then
216         // submit the request to the service and store the response.
217         knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
218                         knownResourceId, knownResourceRefName, testOrgMap,
219                         testOrgRepeatablesMap, mainBodyList, orgAuthClient);
220
221         // Store the IDs from every item created by tests,
222         // so they can be deleted after tests have been run.
223         allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
224     }
225     
226     /**
227      * Creates the person refs.
228      */
229     protected void createPersonRefs() {
230         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
231         // Create a temporary PersonAuthority resource, and its corresponding
232         // refName by which it can be identified.
233         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
234             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
235         
236         ClientResponse<Response> res = personAuthClient.create(multipart);
237         try {
238             int statusCode = res.getStatus();
239             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
240                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
241             Assert.assertEquals(statusCode, STATUS_CREATED);
242             personAuthCSID = extractId(res);
243         } finally {
244             res.releaseConnection();
245         }
246
247         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
248         
249         // Create temporary Person resources, and their corresponding refNames
250         // by which they can be identified.
251         String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", authRefName);
252         personIdsCreated.add(csid);
253         organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
254
255         // Create temporary Person resources, and their corresponding refNames
256         // by which they can be identified.
257         csid = createPerson("Chelsie", "Contact", "chelsieContact", authRefName);
258         personIdsCreated.add(csid);
259         organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
260     }
261     
262     /**
263      * Creates the person.
264      *
265      * @param firstName the first name
266      * @param surName the sur name
267      * @param shortId
268      * @param authRefName
269      * @return the string
270      */
271     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
272         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
273         Map<String, String> personInfo = new HashMap<String,String>();
274         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
275         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
276         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
277         MultipartOutput multipart = 
278             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
279                         authRefName, personInfo, personAuthClient.getItemCommonPartName());
280         
281         String result = null;
282         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
283         try {
284                 int statusCode = res.getStatus();
285         
286                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
287                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
288                 Assert.assertEquals(statusCode, STATUS_CREATED);
289                 result = extractId(res);
290         } finally {
291                 res.releaseConnection();
292         }
293         
294         return result;
295     }
296
297     private void createSubBodyOrgRefs() {
298         // Create a temporary sub-body Organization resource, and its corresponding refName
299         // by which it can be identified.
300         //
301         // This sub-body Organization resource will be created in the same
302         // Organization authority as its parent Organization resource.
303
304         String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
305         allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
306         subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
307     }
308
309     protected String createSubBodyOrganization(String subBodyName) {
310         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
311         Map<String, String> subBodyOrgMap = new HashMap<String,String>();
312         String shortId = createIdentifier();
313         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
314         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
315             subBodyName + "-" + shortId);
316         subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
317         subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
318         MultipartOutput multipart =
319             OrgAuthorityClientUtils.createOrganizationInstance(
320                 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
321
322         String result = null;
323         ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
324         try {
325             int statusCode = res.getStatus();
326             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
327                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
328             Assert.assertEquals(statusCode, STATUS_CREATED);
329             result = extractId(res);
330         } finally {
331             res.releaseConnection();
332         }
333
334         return result;
335     }
336
337     // Success outcomes
338     /**
339      * Read and check auth refs.
340      *
341      * @param testName the test name
342      * @throws Exception the exception
343      */
344     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
345         dependsOnMethods = {"createWithAuthRefs"})
346     public void readAndCheckAuthRefs(String testName) throws Exception {
347
348         if (logger.isDebugEnabled()) {
349             logger.debug(testBanner(testName, CLASS_NAME));
350         }
351         // Perform setup.
352         testSetup(STATUS_OK, ServiceRequestType.READ);
353
354         // Submit the request to the service and store the response.
355         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
356         ClientResponse<MultipartInput> res =
357             orgAuthClient.readItem(knownResourceId, knownItemResourceId);
358         int statusCode = res.getStatus();
359
360         // Check the status code of the response: does it match
361         // the expected response(s)?
362         if(logger.isDebugEnabled()){
363             logger.debug(testName + ".read: status = " + statusCode);
364         }
365         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
366             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
367         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
368
369         MultipartInput input = (MultipartInput) res.getEntity();
370         OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
371             orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
372         Assert.assertNotNull(organization);
373         if(logger.isDebugEnabled()){
374             logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
375         }
376         // Check one or more of the authority fields in the Organization item
377         Assert.assertEquals(organization.getContactNames().getContactName().get(0),
378                 organizationContactPersonRefName1);
379         Assert.assertEquals(organization.getContactNames().getContactName().get(1),
380                 organizationContactPersonRefName2);
381         Assert.assertEquals(organization.getSubBodies().getSubBody().get(0),
382                 subBodyRefName);
383
384         // Get the auth refs and check them
385         // FIXME - need to create this method in the client
386         // and get the ID for the organization item
387         ClientResponse<AuthorityRefList> res2 =
388            orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
389         statusCode = res2.getStatus();
390
391         if(logger.isDebugEnabled()){
392             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
393         }
394         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
395             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
396         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
397         AuthorityRefList list = res2.getEntity();
398         
399         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
400         int numAuthRefsFound = items.size();
401         if(logger.isDebugEnabled()){
402             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
403                 " authority references, found " + numAuthRefsFound);
404         }
405         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
406             "Did not find all expected authority references! " +
407             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
408
409         // Optionally output additional data about list members for debugging.
410         boolean iterateThroughList = true;
411         if(iterateThroughList && logger.isDebugEnabled()){
412             int i = 0;
413             for(AuthorityRefList.AuthorityRefItem item : items){
414                 logger.debug(testName + ": list-item[" + i + "] Field:" +
415                     item.getSourceField() + "=" +
416                     item.getItemDisplayName());
417                 logger.debug(testName + ": list-item[" + i + "] refName=" +
418                     item.getRefName());
419                 logger.debug(testName + ": list-item[" + i + "] URI=" +
420                     item.getUri());
421                 i++;
422             }
423         }
424     }
425
426     // ---------------------------------------------------------------
427     // Cleanup of resources created during testing
428     // ---------------------------------------------------------------
429
430     /**
431      * Deletes all resources created by tests, after all tests have been run.
432      *
433      * This cleanup method will always be run, even if one or more tests fail.
434      * For this reason, it attempts to remove all resources created
435      * at any point during testing, even if some of those resources
436      * may be expected to be deleted by certain tests.
437      */
438     @AfterClass(alwaysRun=true)
439     public void cleanUp() {
440         String noTest = System.getProperty("noTestCleanup");
441         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
442             if (logger.isDebugEnabled()) {
443                 logger.debug("Skipping Cleanup phase ...");
444             }
445             return;
446         }
447         if (logger.isDebugEnabled()) {
448             logger.debug("Cleaning up temporary resources created for testing ...");
449         }
450         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
451         // Delete Person resource(s) (before PersonAuthority resources).
452         for (String resourceId : personIdsCreated) {
453             // Note: Any non-success responses are ignored and not reported.
454             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
455         }
456         // Delete PersonAuthority resource(s).
457         // Note: Any non-success response is ignored and not reported.
458         if(personAuthCSID!=null) {
459                 personAuthClient.delete(personAuthCSID).releaseConnection();
460         }
461         
462         String parentResourceId;
463         String itemResourceId;
464         OrgAuthorityClient client = new OrgAuthorityClient();
465         // Clean up item resources.
466         for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
467             itemResourceId = entry.getKey();
468             parentResourceId = entry.getValue();
469             // Note: Any non-success responses from the delete operation
470             // below are ignored and not reported.
471             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
472         }
473         
474         // Clean up parent resources.
475         for (String resourceId : allResourceIdsCreated) {
476             // Note: Any non-success responses from the delete operation
477             // below are ignored and not reported.
478             client.delete(resourceId).releaseConnection();
479         }
480     }
481
482     // ---------------------------------------------------------------
483     // Utility methods used by tests above
484     // ---------------------------------------------------------------
485     /* (non-Javadoc)
486      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
487      */
488     @Override
489     public String getServicePathComponent() {
490         return SERVICE_PATH_COMPONENT;
491     }
492 }