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