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