]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
19b7dd9ffde977f3bf49fc4594762a226c9b0c36
[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.MediaType;
31 import javax.ws.rs.core.Response;
32
33 import org.collectionspace.services.OrganizationJAXBSchema;
34 import org.collectionspace.services.PersonJAXBSchema;
35 import org.collectionspace.services.client.CollectionObjectClient;
36 import org.collectionspace.services.client.CollectionSpaceClient;
37 import org.collectionspace.services.client.OrgAuthorityClient;
38 import org.collectionspace.services.client.OrgAuthorityClientUtils;
39 import org.collectionspace.services.client.PersonAuthorityClient;
40 import org.collectionspace.services.client.PersonAuthorityClientUtils;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.collectionobject.CollectionobjectsCommon;
43 import org.collectionspace.services.jaxb.AbstractCommonList;
44
45 import org.jboss.resteasy.client.ClientResponse;
46
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
48 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
49 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
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  * CollectionObjectAuthRefsTest, carries out tests against a
59  * deployed and running CollectionObject Service.
60  *
61  * $LastChangedRevision: 1327 $
62  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
63  */
64 public class CollectionObjectAuthRefsTest extends BaseServiceTest {
65
66    /** The logger. */
67     private final String CLASS_NAME = CollectionObjectAuthRefsTest.class.getName();
68     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
69
70     // Instance variables specific to this test.
71     /** The service path component. */
72     final String SERVICE_PATH_COMPONENT = "collectionobjects";
73     
74     /** The person authority name. */
75     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
76
77     /** The organization authority name. */
78     final String ORG_AUTHORITY_NAME = "TestOrgAuth";
79     
80     /** The known resource id. */
81     private String knownResourceId = null;
82     
83     /** The collection object ids created. */
84     private List<String> collectionObjectIdsCreated = new ArrayList<String>();
85     
86     /** The person ids created. */
87     private List<String> personIdsCreated = new ArrayList<String>();
88     
89     /** The person authority csid and refName. */
90     private String personAuthCSID = null; 
91     private String personAuthRefName = null;
92     
93     /** The organization ids created. */
94     private List<String> orgIdsCreated = new ArrayList<String>();
95
96     /** The org authority csid and refName. */
97     private String orgAuthCSID = null;
98     private String orgAuthRefName = null;
99     
100     /** The content organization ref name. */
101     private String contentOrganizationRefName = null;
102         
103     /** The content person ref name. */
104     private String contentPersonRefName = null;
105     
106     /** The inscriber ref names. */
107     private String contentInscriberRefName = null;
108     private String descriptionInscriberRefName = null;
109
110     /** The object history and association ref names. */
111     private String associatedEventOrganizationRefName = null;
112     private String associatedEventPersonRefName = null;
113     private String associatedOrganizationRefName = null;
114     private String associatedPersonRefName = null;
115     private String ownerRefName = null;
116
117     /** The number of authority references expected. */
118     private final int NUM_AUTH_REFS_EXPECTED = 9;
119
120     /* (non-Javadoc)
121      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
122      */
123     @Override
124     protected CollectionSpaceClient getClientInstance() {
125         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
126     }
127     
128     /* (non-Javadoc)
129      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
130      */
131     @Override
132         protected AbstractCommonList getAbstractCommonList(
133                         ClientResponse<AbstractCommonList> response) {
134         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
135     }
136
137     // ---------------------------------------------------------------
138     // CRUD tests : CREATE tests
139     // ---------------------------------------------------------------
140     // Success outcomes
141     /**
142      * Creates the with auth refs.
143      *
144      * @param testName the test name
145      * @throws Exception the exception
146      */
147     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
148     public void createWithAuthRefs(String testName) throws Exception {
149
150         if (logger.isDebugEnabled()) {
151             logger.debug(testBanner(testName, CLASS_NAME));
152         }
153         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
154         
155         // Create all the person refs and entities
156         createPersonRefs();
157
158         // Create all the organization refs and entities
159         createOrganizationRefs();
160
161         // Create an object record payload, containing
162         // authority reference values in a number of its fields
163         String identifier = createIdentifier();
164         MultipartOutput multipart =
165             createCollectionObjectInstance(
166                 "Obj Title",
167                 "ObjNum" + "-" + identifier,
168                 contentOrganizationRefName,
169                 contentPersonRefName,
170                 contentInscriberRefName,
171                 descriptionInscriberRefName,
172                 associatedEventOrganizationRefName,
173                 associatedEventPersonRefName,
174                 associatedOrganizationRefName,
175                 associatedPersonRefName,
176                 ownerRefName
177             );
178
179         // Submit the request to the service and store the response.
180         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
181         ClientResponse<Response> res = collectionObjectClient.create(multipart);
182
183         int statusCode = res.getStatus();
184
185         // Check the status code of the response: does it match
186         // the expected response(s)?
187         //
188         // Specifically:
189         // Does it fall within the set of valid status codes?
190         // Does it exactly match the expected status code?
191         if(logger.isDebugEnabled()){
192             logger.debug(testName + ": status = " + statusCode);
193         }
194         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
195                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
196         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
197
198         // Store the ID returned from the first resource created
199         // for additional tests below.
200         if (knownResourceId == null){
201             knownResourceId = extractId(res);
202             if (logger.isDebugEnabled()) {
203                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
204             }
205         }
206         
207         // Store the IDs from every resource created by tests,
208         // so they can be deleted after tests have been run.
209         collectionObjectIdsCreated.add(extractId(res));
210     }
211
212     /**
213      * Creates a Person Authority.
214      *
215      * @param displayName the display name of the authority
216      * @param shortIdentifier the short identifier for the authority
217      */
218     private void createPersonAuthority(String displayName, String shortIdentifier) {
219         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
220         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
221         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
222                         displayName, shortIdentifier, personAuthClient.getCommonPartName());
223         ClientResponse<Response> res = personAuthClient.create(multipart);
224         int statusCode = res.getStatus();
225
226         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
227                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
228         Assert.assertEquals(statusCode, STATUS_CREATED);
229         personAuthCSID = extractId(res);
230         personAuthRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
231     }
232
233     /**
234      * Creates a person item.
235      *
236      * @param firstName the person's first name
237      * @param surName the person's surname
238      * @param shortIdentifier the short identifier for the item
239      * @return the CSID of the newly-created person record
240      */
241     protected String createPerson(String firstName, String surName, String shortIdentifier ) {
242         Map<String, String> personInfo = new HashMap<String,String>();
243         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
244         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
245         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
246         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
247         MultipartOutput multipart =
248                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
249                                 personAuthRefName, personInfo, personAuthClient.getItemCommonPartName());
250         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
251         int statusCode = res.getStatus();
252
253         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
254                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
255         Assert.assertEquals(statusCode, STATUS_CREATED);
256         return extractId(res);
257     }
258
259     /**
260      * Creates multiple Person items within a Person Authority,
261      * and stores the refNames referring to each.
262      */
263     protected void createPersonRefs(){
264
265         createPersonAuthority(PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME);
266
267         String csid = "";
268         
269         csid = createPerson("Connie", "ContactPerson", "connieContactPerson");
270         contentPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
271         personIdsCreated.add(csid);
272         
273         csid = createPerson("Ingrid", "ContentInscriber", "ingridContentInscriber");
274         contentInscriberRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
275         personIdsCreated.add(csid);
276
277         csid = createPerson("Dessie", "DescriptionInscriber", "dessieDescriptionInscriber");
278         descriptionInscriberRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
279         personIdsCreated.add(csid);
280
281         csid = createPerson("Asok", "AssociatedEventPerson", "asokAssociatedEventPerson");
282         associatedEventPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
283         personIdsCreated.add(csid);
284         
285         csid = createPerson("Andrew", "AssociatedPerson", "andrewAssociatedPerson");
286         associatedPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
287         personIdsCreated.add(csid);
288
289         csid = createPerson("Owen", "Owner", "owenOwner");
290         ownerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
291         personIdsCreated.add(csid);
292     }
293     
294     /**
295      * Creates an organization authority.
296      *
297      * @param displayName the display name of the authority
298      * @param shortIdentifier the short identifier for the authority
299      */
300     private void createOrgAuthority(String displayName, String shortIdentifier) {
301         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
302         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
303         MultipartOutput multipart = OrgAuthorityClientUtils.createOrgAuthorityInstance(
304                         displayName, shortIdentifier, orgAuthClient.getCommonPartName());
305         ClientResponse<Response> res = orgAuthClient.create(multipart);
306         int statusCode = res.getStatus();
307
308         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
309                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
310         Assert.assertEquals(statusCode, STATUS_CREATED);
311         orgAuthCSID = extractId(res);
312         orgAuthRefName = OrgAuthorityClientUtils.getAuthorityRefName(orgAuthCSID, null);
313     }
314
315     /**
316      * Creates an organization item.
317      *
318      * @param shortName the organization's short name
319      * @param foundingPlace the organization's founding place
320      * @param shortIdentifier the short identifier for the item
321      * @return the CSID of the newly-created organization record
322      */
323     protected String createOrganization(String shortName, String foundingPlace, String shortIdentifier ) {
324         Map<String, String> orgInfo = new HashMap<String,String>();
325         orgInfo.put(OrganizationJAXBSchema.SHORT_NAME, shortName);
326         orgInfo.put(OrganizationJAXBSchema.FOUNDING_PLACE, foundingPlace);
327         orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
328         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
329         MultipartOutput multipart =
330                 OrgAuthorityClientUtils.createOrganizationInstance(orgAuthCSID,
331                                 orgAuthRefName, orgInfo, orgAuthClient.getItemCommonPartName());
332         ClientResponse<Response> res = orgAuthClient.createItem(orgAuthCSID, multipart);
333         int statusCode = res.getStatus();
334
335         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
336                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
337         Assert.assertEquals(statusCode, STATUS_CREATED);
338         return extractId(res);
339     }
340     
341    /**
342      * Creates multiple Organization items within an Organization Authority,
343      * and stores the refNames referring to each.
344      */
345     private void createOrganizationRefs() {
346
347         createOrgAuthority(ORG_AUTHORITY_NAME, ORG_AUTHORITY_NAME);
348
349         String csid = "";
350
351         csid = createOrganization("Content Org", "Content Org Town", "contentOrg");
352         contentOrganizationRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, csid, null);
353         orgIdsCreated.add(csid);
354
355         csid = createOrganization("Associated Event Org", "Associated Event Org City", "associatedEventOrg");
356         associatedEventOrganizationRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, csid, null);
357         orgIdsCreated.add(csid);
358
359         csid = createOrganization("Associated Org", "Associated Org City", "associatedOrg");
360         associatedOrganizationRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, csid, null);
361         orgIdsCreated.add(csid);
362     }
363
364
365     // Success outcomes
366     /**
367      * Read and check auth refs.
368      *
369      * @param testName the test name
370      * @throws Exception the exception
371      */
372     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
373         dependsOnMethods = {"createWithAuthRefs"})
374     public void readAndCheckAuthRefs(String testName) throws Exception {
375
376         if (logger.isDebugEnabled()) {
377             logger.debug(testBanner(testName, CLASS_NAME));
378         }
379         // Perform setup.
380         testSetup(STATUS_OK, ServiceRequestType.READ);
381
382         // Submit the request to the service and store the response.
383         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
384         ClientResponse<MultipartInput> res = collectionObjectClient.read(knownResourceId);
385         int statusCode = res.getStatus();
386
387         // Check the status code of the response: does it match
388         // the expected response(s)?
389         if(logger.isDebugEnabled()){
390             logger.debug(testName + ".read: status = " + statusCode);
391         }
392         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
393                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
394         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
395
396         MultipartInput input = (MultipartInput) res.getEntity();
397         CollectionobjectsCommon collectionObject = (CollectionobjectsCommon) extractPart(input,
398                         collectionObjectClient.getCommonPartName(), CollectionobjectsCommon.class);
399         Assert.assertNotNull(collectionObject);
400
401         // Check a sample of one or more person authority ref fields
402         Assert.assertEquals(collectionObject.getInscriptionContentInscriber(), contentInscriberRefName);
403         Assert.assertEquals(collectionObject.getAssociatedPerson(), associatedPersonRefName);
404         Assert.assertEquals(collectionObject.getOwner(), ownerRefName);
405
406         // Check a sample of one or more organization authority ref fields
407         Assert.assertEquals(collectionObject.getContentOrganization(), contentOrganizationRefName);
408         Assert.assertEquals(collectionObject.getAssociatedEventOrganization(), associatedEventOrganizationRefName);
409
410         // Get all of the auth refs and check that the expected number is returned
411         ClientResponse<AuthorityRefList> res2 = collectionObjectClient.getAuthorityRefs(knownResourceId);
412         statusCode = res2.getStatus();
413
414         if(logger.isDebugEnabled()){
415             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
416         }
417         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
418                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
419         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
420         AuthorityRefList list = res2.getEntity();
421         
422         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
423         int numAuthRefsFound = items.size();
424         if(logger.isDebugEnabled()){
425             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
426                 " authority references, found " + numAuthRefsFound);
427         }
428         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
429             "Did not find all expected authority references! " +
430             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
431
432         // Optionally output additional data about list members for debugging.
433         boolean iterateThroughList = true;
434         if(iterateThroughList && logger.isDebugEnabled()){;
435             int i = 0;
436             for(AuthorityRefList.AuthorityRefItem item : items){
437                 logger.debug(testName + ": list-item[" + i + "] Field:" +
438                                 item.getSourceField() + " =" +
439                         " item display name = " + item.getAuthDisplayName() +
440                         " auth display name = " + item.getItemDisplayName());
441                 logger.debug(testName + ": list-item[" + i + "] refName=" +
442                         item.getRefName());
443                 logger.debug(testName + ": list-item[" + i + "] URI=" +
444                         item.getUri());
445                 i++;
446             }
447         }
448     }
449
450
451     // ---------------------------------------------------------------
452     // Cleanup of resources created during testing
453     // ---------------------------------------------------------------
454
455     /**
456      * Deletes all resources created by tests, after all tests have been run.
457      *
458      * This cleanup method will always be run, even if one or more tests fail.
459      * For this reason, it attempts to remove all resources created
460      * at any point during testing, even if some of those resources
461      * may be expected to be deleted by certain tests.
462      */
463     @AfterClass(alwaysRun=true)
464     public void cleanUp() {
465         String noTest = System.getProperty("noTestCleanup");
466         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
467             if (logger.isDebugEnabled()) {
468                 logger.debug("Skipping Cleanup phase ...");
469             }
470             return;
471         }
472         if (logger.isDebugEnabled()) {
473             logger.debug("Cleaning up temporary resources created for testing ...");
474         }
475         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
476         for (String resourceId : collectionObjectIdsCreated) {
477             // Note: Any non-success responses are ignored and not reported.
478             collectionObjectClient.delete(resourceId).releaseConnection();
479         }
480         // Note: Any non-success response is ignored and not reported.
481         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
482         // Delete persons before PersonAuth
483         for (String resourceId : personIdsCreated) {
484             // Note: Any non-success responses are ignored and not reported.
485             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
486         }
487         personAuthClient.delete(personAuthCSID).releaseConnection();
488         // Note: Any non-success response is ignored and not reported.
489         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
490         // Delete organizations before OrgAuth
491         for (String resourceId : orgIdsCreated) {
492             // Note: Any non-success responses are ignored and not reported.
493             orgAuthClient.deleteItem(orgAuthCSID, resourceId).releaseConnection();
494         }
495         orgAuthClient.delete(orgAuthCSID).releaseConnection();
496     }
497
498     // ---------------------------------------------------------------
499     // Utility methods used by tests above
500     // ---------------------------------------------------------------
501     /* (non-Javadoc)
502      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
503      */
504     @Override
505     public String getServicePathComponent() {
506         return SERVICE_PATH_COMPONENT;
507     }
508
509    /**
510     * Creates the collection object instance.
511     *
512     * @param title the title
513     * @param objNum the obj num
514     * @param contentOrganization the content organization
515     * @param contentPeople the content people
516     * @param contentPerson the content person
517     * @param inscriber the inscriber
518     * @return the multipart output
519     */
520    private MultipartOutput createCollectionObjectInstance(
521                 String title,
522                 String objNum,
523                 String contentOrganization,
524                 String contentPerson,
525                 String contentInscriber,
526                 String descriptionInscriber,
527                 String associatedEventOrganization,
528                 String associatedEventPerson,
529                 String associatedOrganization,
530                 String associatedPerson,
531                 String owner ) {
532         CollectionobjectsCommon collectionObject = new CollectionobjectsCommon();
533         collectionObject.setTitle(title);
534         collectionObject.setObjectNumber(objNum);
535         collectionObject.setContentOrganization(contentOrganization);
536         collectionObject.setContentPerson(contentPerson);
537         collectionObject.setInscriptionContentInscriber(contentInscriber);
538         collectionObject.setInscriptionDescriptionInscriber(descriptionInscriber);
539         collectionObject.setAssociatedEventOrganization(associatedEventOrganization);
540         collectionObject.setAssociatedEventPerson(associatedEventPerson);
541         collectionObject.setAssociatedOrganization(associatedOrganization);
542         collectionObject.setAssociatedPerson(associatedPerson);
543         collectionObject.setOwner(owner);
544         MultipartOutput multipart = new MultipartOutput();
545         OutputPart commonPart =
546             multipart.addPart(collectionObject, MediaType.APPLICATION_XML_TYPE);
547         commonPart.getHeaders().add("label", new CollectionObjectClient().getCommonPartName());
548
549         if(logger.isDebugEnabled()){
550             logger.debug("to be created, collectionObject common");
551             logger.debug(objectAsXmlString(collectionObject, CollectionobjectsCommon.class));
552         }
553
554         return multipart;
555     }
556
557 }