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