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