]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
59b5054de0b19fa45e7b7ce908cb0a2be1274b7d
[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         testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
199         testOrgMap.put(OrganizationJAXBSchema.SUB_BODY, subBodyRefName);
200
201         // Finishing creating the new Organization item, then
202         // submit the request to the service and store the response.
203         knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
204                         knownResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
205
206         // Store the IDs from every item created by tests,
207         // so they can be deleted after tests have been run.
208         allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
209     }
210     
211     /**
212      * Creates the person refs.
213      */
214     protected void createPersonRefs() {
215         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
216         // Create a temporary PersonAuthority resource, and its corresponding
217         // refName by which it can be identified.
218         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
219             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
220         
221         ClientResponse<Response> res = personAuthClient.create(multipart);
222         try {
223             int statusCode = res.getStatus();
224             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
225                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
226             Assert.assertEquals(statusCode, STATUS_CREATED);
227             personAuthCSID = extractId(res);
228         } finally {
229             res.releaseConnection();
230         }
231
232         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
233         
234         // Create temporary Person resources, and their corresponding refNames
235         // by which they can be identified.
236         String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", authRefName);
237         personIdsCreated.add(csid);
238         organizationContactPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
239     }
240     
241     /**
242      * Creates the person.
243      *
244      * @param firstName the first name
245      * @param surName the sur name
246      * @param shortId
247      * @param authRefName
248      * @return the string
249      */
250     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
251         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
252         Map<String, String> personInfo = new HashMap<String,String>();
253         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
254         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
255         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
256         MultipartOutput multipart = 
257             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
258                         authRefName, personInfo, personAuthClient.getItemCommonPartName());
259         
260         String result = null;
261         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
262         try {
263                 int statusCode = res.getStatus();
264         
265                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
266                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
267                 Assert.assertEquals(statusCode, STATUS_CREATED);
268                 result = extractId(res);
269         } finally {
270                 res.releaseConnection();
271         }
272         
273         return result;
274     }
275
276     private void createSubBodyOrgRefs() {
277         // Create a temporary sub-body Organization resource, and its corresponding refName
278         // by which it can be identified.
279         //
280         // This sub-body Organization resource will be created in the same
281         // Organization authority as its parent Organization resource.
282
283         String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
284         allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
285         subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
286     }
287
288     protected String createSubBodyOrganization(String subBodyName) {
289         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
290         Map<String, String> subBodyOrgMap = new HashMap<String,String>();
291         String shortId = createIdentifier();
292         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
293         subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
294             subBodyName + "-" + shortId);
295         subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
296         subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
297         MultipartOutput multipart =
298             OrgAuthorityClientUtils.createOrganizationInstance(knownResourceId,
299                 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
300
301         String result = null;
302         ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
303         try {
304             int statusCode = res.getStatus();
305             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
306                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
307             Assert.assertEquals(statusCode, STATUS_CREATED);
308             result = extractId(res);
309         } finally {
310             res.releaseConnection();
311         }
312
313         return result;
314     }
315
316     // Success outcomes
317     /**
318      * Read and check auth refs.
319      *
320      * @param testName the test name
321      * @throws Exception the exception
322      */
323     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
324         dependsOnMethods = {"createWithAuthRefs"})
325     public void readAndCheckAuthRefs(String testName) throws Exception {
326
327         if (logger.isDebugEnabled()) {
328             logger.debug(testBanner(testName, CLASS_NAME));
329         }
330         // Perform setup.
331         testSetup(STATUS_OK, ServiceRequestType.READ);
332
333         // Submit the request to the service and store the response.
334         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
335         ClientResponse<MultipartInput> res =
336             orgAuthClient.readItem(knownResourceId, knownItemResourceId);
337         int statusCode = res.getStatus();
338
339         // Check the status code of the response: does it match
340         // the expected response(s)?
341         if(logger.isDebugEnabled()){
342             logger.debug(testName + ".read: status = " + statusCode);
343         }
344         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
345             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
346         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
347
348         MultipartInput input = (MultipartInput) res.getEntity();
349         OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
350             orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
351         Assert.assertNotNull(organization);
352         if(logger.isDebugEnabled()){
353             logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
354         }
355         // Check one or more of the authority fields in the Organization item
356         Assert.assertEquals(organization.getContactName(), organizationContactPersonRefName);
357         Assert.assertEquals(organization.getSubBody(), subBodyRefName);
358
359         // Get the auth refs and check them
360         // FIXME - need to create this method in the client
361         // and get the ID for the organization item
362         ClientResponse<AuthorityRefList> res2 =
363            orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
364         statusCode = res2.getStatus();
365
366         if(logger.isDebugEnabled()){
367             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
368         }
369         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
370             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
371         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
372         AuthorityRefList list = res2.getEntity();
373         
374         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
375         int numAuthRefsFound = items.size();
376         if(logger.isDebugEnabled()){
377             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
378                 " authority references, found " + numAuthRefsFound);
379         }
380         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
381             "Did not find all expected authority references! " +
382             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
383
384         // Optionally output additional data about list members for debugging.
385         boolean iterateThroughList = true;
386         if(iterateThroughList && logger.isDebugEnabled()){
387             int i = 0;
388             for(AuthorityRefList.AuthorityRefItem item : items){
389                 logger.debug(testName + ": list-item[" + i + "] Field:" +
390                     item.getSourceField() + "=" +
391                     item.getItemDisplayName());
392                 logger.debug(testName + ": list-item[" + i + "] refName=" +
393                     item.getRefName());
394                 logger.debug(testName + ": list-item[" + i + "] URI=" +
395                     item.getUri());
396                 i++;
397             }
398         }
399     }
400
401     // ---------------------------------------------------------------
402     // Cleanup of resources created during testing
403     // ---------------------------------------------------------------
404
405     /**
406      * Deletes all resources created by tests, after all tests have been run.
407      *
408      * This cleanup method will always be run, even if one or more tests fail.
409      * For this reason, it attempts to remove all resources created
410      * at any point during testing, even if some of those resources
411      * may be expected to be deleted by certain tests.
412      */
413     @AfterClass(alwaysRun=true)
414     public void cleanUp() {
415         String noTest = System.getProperty("noTestCleanup");
416         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
417             if (logger.isDebugEnabled()) {
418                 logger.debug("Skipping Cleanup phase ...");
419             }
420             return;
421         }
422         if (logger.isDebugEnabled()) {
423             logger.debug("Cleaning up temporary resources created for testing ...");
424         }
425         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
426         // Delete Person resource(s) (before PersonAuthority resources).
427         for (String resourceId : personIdsCreated) {
428             // Note: Any non-success responses are ignored and not reported.
429             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
430         }
431         // Delete PersonAuthority resource(s).
432         // Note: Any non-success response is ignored and not reported.
433         if(personAuthCSID!=null) {
434                 personAuthClient.delete(personAuthCSID).releaseConnection();
435         }
436         
437         String parentResourceId;
438         String itemResourceId;
439         OrgAuthorityClient client = new OrgAuthorityClient();
440         // Clean up item resources.
441         for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
442             itemResourceId = entry.getKey();
443             parentResourceId = entry.getValue();
444             // Note: Any non-success responses from the delete operation
445             // below are ignored and not reported.
446             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
447         }
448         
449         // Clean up parent resources.
450         for (String resourceId : allResourceIdsCreated) {
451             // Note: Any non-success responses from the delete operation
452             // below are ignored and not reported.
453             client.delete(resourceId).releaseConnection();
454         }
455     }
456
457     // ---------------------------------------------------------------
458     // Utility methods used by tests above
459     // ---------------------------------------------------------------
460     /* (non-Javadoc)
461      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
462      */
463     @Override
464     public String getServicePathComponent() {
465         return SERVICE_PATH_COMPONENT;
466     }
467 }