]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f705278bf13ad9f6751095feea036dd86c6cc2d8
[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.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.jaxb.AbstractCommonList;
43 import org.collectionspace.services.organization.MainBodyGroup;
44 import org.collectionspace.services.organization.MainBodyGroupList;
45 import org.collectionspace.services.organization.OrganizationsCommon;
46
47 import org.jboss.resteasy.client.ClientResponse;
48
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<AbstractCommonList> {
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 PERSON_AUTHORITY_NAME = "TestPersonAuth";
71     final String ORG_AUTHORITY_NAME = "TestOrgAuth";
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
83     protected String knownItemResourceId = null;
84         
85     private String knownResourceRefName = null;
86             
87     /** The person ids created. */
88     private List<String> personIdsCreated = new ArrayList<String>();
89     
90     // CSID for the instance of the test Person authority
91     // created during testing.
92     private String personAuthCSID = null;
93     
94     /** The organization contact person refNames. */
95     private String organizationContactPersonRefName1 = null;
96     private String organizationContactPersonRefName2 = null;
97
98     // The refName of an Organization item that represents
99     // the sub-body organization of a second Organization item.
100     private String subBodyRefName = null;
101     
102     /** The number of authorityreferences expected. */
103     private final int NUM_AUTH_REFS_EXPECTED = 2;       // Place authRef not legal, should not be returned.
104
105     protected void setKnownResource( String id, String refName ) {
106         knownResourceId = id;
107         knownResourceRefName = refName;
108     }
109
110     /* (non-Javadoc)
111      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
112      */
113     @Override
114     protected CollectionSpaceClient getClientInstance() {
115         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
116     }
117     
118     /* (non-Javadoc)
119      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
120      */
121     @Override
122         protected AbstractCommonList getCommonList(
123                         ClientResponse<AbstractCommonList> response) {
124         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
125     }
126
127     // ---------------------------------------------------------------
128     // CRUD tests : CREATE tests
129     // ---------------------------------------------------------------
130     // Success outcomes
131     /**
132      * Creates the with auth refs.
133      *
134      * @param testName the test name
135      * @throws Exception the exception
136      */
137     @Test(dataProvider="testName")
138     public void createWithAuthRefs(String testName) throws Exception {
139         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
140
141         // Create a new Organization Authority resource.
142         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
143         String shortId = createIdentifier();
144         String displayName = "TestOrgAuth-" + shortId;
145         //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
146         PoxPayloadOut multipart =
147             OrgAuthorityClientUtils.createOrgAuthorityInstance(
148                                 displayName, shortId, orgAuthClient.getCommonPartName());
149
150         // Submit the request to the service and store the response.
151         ClientResponse<Response> res = orgAuthClient.create(multipart);
152         try {
153                 int statusCode = res.getStatus();
154                 // Check the status code of the response: does it match
155                 // the expected response(s)?
156                 //
157                 // Specifically:
158                 // Does it fall within the set of valid status codes?
159                 // Does it exactly match the expected status code?
160                 if(logger.isDebugEnabled()){
161                     logger.debug(testName + ": status = " + statusCode);
162                 }
163                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
164                     invalidStatusCodeMessage(testRequestType, statusCode));
165                 Assert.assertEquals(statusCode, testExpectedStatusCode);
166         
167                 // Store the IDs from every resource created by tests,
168                 // so they can be deleted after tests have been run.
169                 String newId = extractId(res);
170                 if (knownResourceId == null){
171                         setKnownResource( newId, null ); //baseRefName );
172                 }
173                 allResourceIdsCreated.add(newId);
174         } finally {
175             res.releaseConnection();
176         }        
177
178         // Create all the person refs and entities
179         createPersonRefs();
180
181         // Create all the organization sub-body refs and entities
182         createSubBodyOrgRefs();
183
184         // Initialize values for a new Organization item, to be created within
185         // the newly-created Organization Authority resource.
186         //
187         // One or more fields in the Organization item record will
188         // contain references to Persons, via their refNames, as
189         // per the initialization(s) below.
190         Map<String, String> testOrgMap = new HashMap<String,String>();
191         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
192         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
193
194         Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
195         List<String> testOrgContactNames = new ArrayList<String>();
196         testOrgContactNames.add(organizationContactPersonRefName1);
197         testOrgContactNames.add(organizationContactPersonRefName2);
198         testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
199         List<String> testOrgSubBodies = new ArrayList<String>();
200         testOrgSubBodies.add(subBodyRefName);
201         testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
202
203         MainBodyGroupList mainBodyList = new MainBodyGroupList();
204         List<MainBodyGroup> mainBodyGroups = mainBodyList.getMainBodyGroup();
205         MainBodyGroup mainBodyGroup = new MainBodyGroup();
206         mainBodyGroup.setShortName("Test Organization-" + shortId);
207         mainBodyGroup.setLongName("Test Organization Name");
208         mainBodyGroups.add(mainBodyGroup);
209
210         // Finishing creating the new Organization item, then
211         // submit the request to the service and store the response.
212         knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
213                         knownResourceId, knownResourceRefName, testOrgMap,
214                         testOrgRepeatablesMap, mainBodyList, orgAuthClient);
215
216         // Store the IDs from every item created by tests,
217         // so they can be deleted after tests have been run.
218         allResourceItemIdsCreated.put(knownItemResourceId, knownResourceId);
219     }
220     
221     /**
222      * Creates the person refs.
223      */
224     protected void createPersonRefs() {
225         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
226         // Create a temporary PersonAuthority resource, and its corresponding
227         // refName by which it can be identified.
228         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
229             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
230         
231         ClientResponse<Response> res = personAuthClient.create(multipart);
232         try {
233             int statusCode = res.getStatus();
234             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
235                 invalidStatusCodeMessage(testRequestType, statusCode));
236             Assert.assertEquals(statusCode, STATUS_CREATED);
237             personAuthCSID = extractId(res);
238         } finally {
239             res.releaseConnection();
240         }
241
242         //String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
243         
244         // Create temporary Person resources, and their corresponding refNames
245         // by which they can be identified.
246         String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", null ); // authRefName);
247         personIdsCreated.add(csid);
248         organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
249
250         // Create temporary Person resources, and their corresponding refNames
251         // by which they can be identified.
252         csid = createPerson("Chelsie", "Contact", "chelsieContact", null ); // authRefName);
253         personIdsCreated.add(csid);
254         organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
255     }
256     
257     /**
258      * Creates the person.
259      *
260      * @param firstName the first name
261      * @param surName the sur name
262      * @param shortId
263      * @param authRefName
264      * @return the string
265      */
266     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
267         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
268         Map<String, String> personInfo = new HashMap<String,String>();
269         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
270         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
271         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
272         PoxPayloadOut multipart = 
273             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
274                         authRefName, personInfo, null, personAuthClient.getItemCommonPartName());
275         
276         String result = null;
277         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
278         try {
279                 int statusCode = res.getStatus();
280         
281                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
282                         invalidStatusCodeMessage(testRequestType, statusCode));
283                 Assert.assertEquals(statusCode, STATUS_CREATED);
284                 result = extractId(res);
285         } finally {
286                 res.releaseConnection();
287         }
288         
289         return result;
290     }
291
292     private void createSubBodyOrgRefs() {
293         // Create a temporary sub-body Organization resource, and its corresponding refName
294         // by which it can be identified.
295         //
296         // This sub-body Organization resource will be created in the same
297         // Organization authority as its parent Organization resource.
298
299         String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
300         allResourceItemIdsCreated.put(subBodyResourceId, knownResourceId);
301         subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
302     }
303
304     protected String createSubBodyOrganization(String subBodyName) {
305         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
306         Map<String, String> subBodyOrgMap = new HashMap<String,String>();
307         String shortId = createIdentifier();
308         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
309         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
310             subBodyName + "-" + shortId);
311         subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
312         subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
313         PoxPayloadOut multipart =
314             OrgAuthorityClientUtils.createOrganizationInstance(
315                 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
316
317         String result = null;
318         ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
319         try {
320             int statusCode = res.getStatus();
321             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
322                     invalidStatusCodeMessage(testRequestType, statusCode));
323             Assert.assertEquals(statusCode, STATUS_CREATED);
324             result = extractId(res);
325         } finally {
326             res.releaseConnection();
327         }
328
329         return result;
330     }
331
332     // Success outcomes
333     /**
334      * Read and check auth refs.
335      *
336      * @param testName the test name
337      * @throws Exception the exception
338      */
339     @Test(dataProvider="testName",
340         dependsOnMethods = {"createWithAuthRefs"})
341     public void readAndCheckAuthRefs(String testName) throws Exception {
342         // Perform setup.
343         testSetup(STATUS_OK, ServiceRequestType.READ);
344
345         // Submit the request to the service and store the response.
346         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
347         ClientResponse<String> res = orgAuthClient.readItem(knownResourceId, knownItemResourceId);
348         OrganizationsCommon organization = null;
349         try {
350                 assertStatusCode(res, testName);
351                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
352                 organization = (OrganizationsCommon) extractPart(input,
353                     orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
354                 Assert.assertNotNull(organization);
355                 if (logger.isDebugEnabled()){
356                     logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
357                 }
358         } finally {
359                 if (res != null) {
360                 res.releaseConnection();
361             }
362         }
363         // Check one or more of the authority fields in the Organization item
364         Assert.assertEquals(organization.getContactNames().getContactName().get(0),
365                 organizationContactPersonRefName1);
366         Assert.assertEquals(organization.getContactNames().getContactName().get(1),
367                 organizationContactPersonRefName2);
368         Assert.assertEquals(organization.getSubBodies().getSubBody().get(0),
369                 subBodyRefName);
370
371         // Get the auth refs and check them
372         // FIXME - need to create this method in the client
373         // and get the ID for the organization item
374         ClientResponse<AuthorityRefList> res2 =
375            orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
376         AuthorityRefList list = null;
377         try {
378                 assertStatusCode(res2, testName);
379                 list = res2.getEntity();
380         } finally {
381                 if (res2 != null) {
382                         res2.releaseConnection();
383             }
384         }
385         
386         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
387         int numAuthRefsFound = items.size();
388         if(logger.isDebugEnabled()){
389             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
390                 " authority references, found " + numAuthRefsFound);
391         }
392         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
393             "Did not find all expected authority references! " +
394             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
395
396         // Optionally output additional data about list members for debugging.
397         boolean iterateThroughList = true;
398         if(iterateThroughList && logger.isDebugEnabled()){
399             int i = 0;
400             for(AuthorityRefList.AuthorityRefItem item : items){
401                 logger.debug(testName + ": list-item[" + i + "] Field:" +
402                     item.getSourceField() + "=" +
403                     item.getItemDisplayName());
404                 logger.debug(testName + ": list-item[" + i + "] refName=" +
405                     item.getRefName());
406                 logger.debug(testName + ": list-item[" + i + "] URI=" +
407                     item.getUri());
408                 i++;
409             }
410         }
411     }
412
413     // ---------------------------------------------------------------
414     // Cleanup of resources created during testing
415     // ---------------------------------------------------------------
416
417     /**
418      * Deletes all resources created by tests, after all tests have been run.
419      *
420      * This cleanup method will always be run, even if one or more tests fail.
421      * For this reason, it attempts to remove all resources created
422      * at any point during testing, even if some of those resources
423      * may be expected to be deleted by certain tests.
424      */
425     @AfterClass(alwaysRun=true)
426     public void cleanUp() {
427         String noTest = System.getProperty("noTestCleanup");
428         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
429             if (logger.isDebugEnabled()) {
430                 logger.debug("Skipping Cleanup phase ...");
431             }
432             return;
433         }
434         if (logger.isDebugEnabled()) {
435             logger.debug("Cleaning up temporary resources created for testing ...");
436         }
437         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
438         // Delete Person resource(s) (before PersonAuthority resources).
439         for (String resourceId : personIdsCreated) {
440             // Note: Any non-success responses are ignored and not reported.
441             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
442         }
443         // Delete PersonAuthority resource(s).
444         // Note: Any non-success response is ignored and not reported.
445         if(personAuthCSID!=null) {
446                 personAuthClient.delete(personAuthCSID).releaseConnection();
447         }
448         
449         String parentResourceId;
450         String itemResourceId;
451         OrgAuthorityClient client = new OrgAuthorityClient();
452         // Clean up item resources.
453         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
454             itemResourceId = entry.getKey();
455             parentResourceId = entry.getValue();
456             // Note: Any non-success responses from the delete operation
457             // below are ignored and not reported.
458             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
459         }
460         
461         // Clean up parent resources.
462         for (String resourceId : allResourceIdsCreated) {
463             // Note: Any non-success responses from the delete operation
464             // below are ignored and not reported.
465             client.delete(resourceId).releaseConnection();
466         }
467     }
468 }