]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f5b72ef5afedaea297da3d317edf1f07e5013d11
[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.PersonJAXBSchema;
34 import org.collectionspace.services.client.AcquisitionClient;
35 import org.collectionspace.services.client.CollectionSpaceClient;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList;
39 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.collectionspace.services.acquisition.AcquisitionsCommon;
41 import org.collectionspace.services.acquisition.AcquisitionFunding;
42 import org.collectionspace.services.acquisition.AcquisitionFundingList;
43 import org.collectionspace.services.acquisition.AcquisitionSourceList;
44 import org.collectionspace.services.acquisition.OwnerList;
45
46 import org.jboss.resteasy.client.ClientResponse;
47
48 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
49 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
50 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
51 import org.testng.Assert;
52 import org.testng.annotations.AfterClass;
53 import org.testng.annotations.Test;
54
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * AcquisitionAuthRefsTest, carries out tests against a
60  * deployed and running Acquisition Service.
61  *
62  * $LastChangedRevision: 1327 $
63  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
64  */
65 public class AcquisitionAuthRefsTest extends BaseServiceTest {
66
67     private final String CLASS_NAME = AcquisitionAuthRefsTest.class.getName();
68     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
69
70     // Instance variables specific to this test.
71     final String SERVICE_PATH_COMPONENT = "acquisitions";
72     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
73     private String knownResourceId = null;
74     private List<String> acquisitionIdsCreated = new ArrayList<String>();
75     private List<String> personIdsCreated = new ArrayList<String>();
76     private String personAuthCSID = null; 
77     private String acquisitionAuthorizerRefName = null;
78     private List<String> acquisitionFundingSourcesRefNames = new ArrayList<String>();
79     private List<String> ownersRefNames = new ArrayList<String>();
80     private List<String> acquisitionSourcesRefNames = new ArrayList<String>();
81     private final int NUM_AUTH_REFS_EXPECTED = 5;
82
83     /* (non-Javadoc)
84      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
85      */
86     @Override
87     protected CollectionSpaceClient getClientInstance() {
88         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
89     }
90     
91     /* (non-Javadoc)
92      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
93      */
94     @Override
95         protected AbstractCommonList getAbstractCommonList(
96                         ClientResponse<AbstractCommonList> response) {
97         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
98     }
99
100     // ---------------------------------------------------------------
101     // CRUD tests : CREATE tests
102     // ---------------------------------------------------------------
103     // Success outcomes
104     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
105     public void createWithAuthRefs(String testName) throws Exception {
106
107         if (logger.isDebugEnabled()) {
108             logger.debug(testBanner(testName, CLASS_NAME));
109         };
110         
111         // Perform setup.
112         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
113
114         // Submit the request to the service and store the response.
115         String identifier = createIdentifier();
116         
117         // Create all the person refs and entities
118         createPersonRefs();
119         
120         MultipartOutput multipart = createAcquisitionInstance(
121             "April 1, 2010",
122             acquisitionAuthorizerRefName,
123             acquisitionFundingSourcesRefNames,
124             ownersRefNames,
125             acquisitionSourcesRefNames);
126
127         AcquisitionClient acquisitionClient = new AcquisitionClient();
128         ClientResponse<Response> res = acquisitionClient.create(multipart);
129
130         int statusCode = res.getStatus();
131
132         // Check the status code of the response: does it match
133         // the expected response(s)?
134         //
135         // Specifically:
136         // Does it fall within the set of valid status codes?
137         // Does it exactly match the expected status code?
138         if(logger.isDebugEnabled()){
139             logger.debug(testName + ": status = " + statusCode);
140         }
141         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
142                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
143         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
144
145         // Store the ID returned from the first resource created
146         // for additional tests below.
147         if (knownResourceId == null){
148             knownResourceId = extractId(res);
149             if (logger.isDebugEnabled()) {
150                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
151             }
152         }
153         
154         // Store the IDs from every resource created by tests,
155         // so they can be deleted after tests have been run.
156         acquisitionIdsCreated.add(extractId(res));
157     }
158     
159     protected void createPersonRefs(){
160         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
161         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
162                         PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
163         ClientResponse<Response> res = personAuthClient.create(multipart);
164         int statusCode = res.getStatus();
165
166         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
167             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
168         Assert.assertEquals(statusCode, STATUS_CREATED);
169         personAuthCSID = extractId(res);
170         
171         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
172         
173         String csid = createPerson("Annie", "Authorizer", "annieAuth", authRefName);
174         acquisitionAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
175         personIdsCreated.add(csid);
176
177         /*
178         csid = createPerson("Fran", "Funding-SourceOne", "franFundingSourceOne", authRefName);
179         acquisitionFundingSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
180         personIdsCreated.add(csid);
181
182         csid = createPerson("Fahd", "Funding-SourceTwo", "fahdFundingSourceTwo", authRefName);
183         acquisitionFundingSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
184         personIdsCreated.add(csid);
185          */
186         
187         csid = createPerson("Owen", "OwnerOne", "owenOwnerOne", authRefName);
188         ownersRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
189         personIdsCreated.add(csid);
190
191         csid = createPerson("Orelia", "OwnerTwo", "oreliaOwnerTwo", authRefName);
192         ownersRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
193         personIdsCreated.add(csid);
194
195         csid = createPerson("Sammy", "SourceOne", "sammySourceOne", authRefName);
196         acquisitionSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
197         personIdsCreated.add(csid);
198
199         csid = createPerson("Serena", "SourceTwo", "serenaSourceTwo", authRefName);
200         acquisitionSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
201         personIdsCreated.add(csid);
202     }
203     
204     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
205         Map<String, String> personInfo = new HashMap<String,String>();
206         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
207         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
208         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
209         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
210         MultipartOutput multipart = 
211                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
212                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
213         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
214         int statusCode = res.getStatus();
215
216         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
217             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
218         Assert.assertEquals(statusCode, STATUS_CREATED);
219         return extractId(res);
220     }
221
222     // Success outcomes
223     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
224         dependsOnMethods = {"createWithAuthRefs"})
225     public void readAndCheckAuthRefs(String testName) throws Exception {
226
227         if (logger.isDebugEnabled()) {
228             logger.debug(testBanner(testName, CLASS_NAME));
229         };
230         
231         // Perform setup.
232         testSetup(STATUS_OK, ServiceRequestType.READ);
233         
234         // Submit the request to the service and store the response.
235         AcquisitionClient acquisitionClient = new AcquisitionClient();
236         ClientResponse<MultipartInput> res = acquisitionClient.read(knownResourceId);
237         int statusCode = res.getStatus();
238
239         // Check the status code of the response: does it match
240         // the expected response(s)?
241         if(logger.isDebugEnabled()){
242             logger.debug(testName + ".read: status = " + statusCode);
243         }
244         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
245             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
246         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
247
248         MultipartInput input = (MultipartInput) res.getEntity();
249         AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input,
250                         acquisitionClient.getCommonPartName(), AcquisitionsCommon.class);
251         Assert.assertNotNull(acquisition);
252
253         // Check a couple of fields
254         // Scalar fields
255         Assert.assertEquals(acquisition.getAcquisitionAuthorizer(), acquisitionAuthorizerRefName);
256         
257         // In repeatable groups of fields
258         /*
259         AcquisitionFundingList acqFundingList = acquisition.getAcquisitionFundingList();
260         List<AcquisitionFunding> acqFundings = acqFundingList.getAcquisitionFunding();
261         List<String> acqFundingSourceRefNamesFound = new ArrayList();
262         for (AcquisitionFunding acqFunding : acqFundings) {
263             String acqFundingSourceRefName = acqFunding.getAcquisitionFundingSource();
264             acqFundingSourceRefNamesFound.add(acqFundingSourceRefName);
265         }
266         Assert.assertTrue(acqFundingSourceRefNamesFound.containsAll(acquisitionFundingSourcesRefNames));
267         */
268
269         // In scalar repeatable fields
270         OwnerList ownersList = acquisition.getOwners();
271         List<String> owners = ownersList.getOwner();
272         for (String refName : owners) {
273           Assert.assertTrue(ownersRefNames.contains(refName));
274         }
275
276         AcquisitionSourceList acquisitionSources = acquisition.getAcquisitionSources();
277         List<String> sources = acquisitionSources.getAcquisitionSource();
278         for (String refName : sources) {
279           Assert.assertTrue(acquisitionSourcesRefNames.contains(refName));
280         }
281         
282         // Get the auth refs and check them
283         ClientResponse<AuthorityRefList> res2 =
284             acquisitionClient.getAuthorityRefs(knownResourceId);
285         statusCode = res2.getStatus();
286
287         if(logger.isDebugEnabled()){
288             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
289         }
290         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
291                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
292         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
293         AuthorityRefList list = res2.getEntity();
294
295         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
296         int numAuthRefsFound = items.size();
297         if(logger.isDebugEnabled()){
298             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
299                 " authority references, found " + numAuthRefsFound);
300         }
301         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
302             "Did not find all expected authority references! " +
303             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
304
305         // Optionally output additional data about list members for debugging.
306         boolean iterateThroughList = true;
307         if(iterateThroughList && logger.isDebugEnabled()){
308             int i = 0;
309             for(AuthorityRefList.AuthorityRefItem item : items){
310                 logger.debug(testName + ": list-item[" + i + "] Field:" +
311                                 item.getSourceField() + "= " +
312                         item.getAuthDisplayName() +
313                         item.getItemDisplayName());
314                 logger.debug(testName + ": list-item[" + i + "] refName=" +
315                         item.getRefName());
316                 logger.debug(testName + ": list-item[" + i + "] URI=" +
317                         item.getUri());
318                 i++;
319             }
320         }
321     }
322
323
324     // ---------------------------------------------------------------
325     // Cleanup of resources created during testing
326     // ---------------------------------------------------------------
327
328     /**
329      * Deletes all resources created by tests, after all tests have been run.
330      *
331      * This cleanup method will always be run, even if one or more tests fail.
332      * For this reason, it attempts to remove all resources created
333      * at any point during testing, even if some of those resources
334      * may be expected to be deleted by certain tests.
335      */
336     @AfterClass(alwaysRun=true)
337     public void cleanUp() {
338         String noTest = System.getProperty("noTestCleanup");
339         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
340             if (logger.isDebugEnabled()) {
341                 logger.debug("Skipping Cleanup phase ...");
342             }
343             return;
344         }
345         if (logger.isDebugEnabled()) {
346             logger.debug("Cleaning up temporary resources created for testing ...");
347         }
348         AcquisitionClient acquisitionClient = new AcquisitionClient();
349         for (String resourceId : acquisitionIdsCreated) {
350            // Note: Any non-success responses are ignored and not reported.
351            ClientResponse<Response> res = acquisitionClient.delete(resourceId);
352            res.releaseConnection();
353         }
354         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
355         // Delete persons before PersonAuth
356         for (String resourceId : personIdsCreated) {
357             // Note: Any non-success responses are ignored and not reported.
358             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
359             res.releaseConnection();
360         }
361         // Note: Any non-success response is ignored and not reported.
362         ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
363         res.releaseConnection();
364     }
365
366     // ---------------------------------------------------------------
367     // Utility methods used by tests above
368     // ---------------------------------------------------------------
369     @Override
370     public String getServicePathComponent() {
371         return SERVICE_PATH_COMPONENT;
372     }
373
374    private MultipartOutput createAcquisitionInstance(
375         String accessionDate,
376         String acquisitionAuthorizer,
377         List<String> acquisitionFundingSources,
378         List<String> acqOwners,
379         List<String> acquisitionSources) {
380        
381         AcquisitionsCommon acquisition = new AcquisitionsCommon();
382         acquisition.setAccessionDate(accessionDate);
383         acquisition.setAcquisitionAuthorizer(acquisitionAuthorizer);
384
385         // AcquisitionFunding-related authrefs fields are *not* currently
386         // enabled, as described in issue CSPACE-2818
387
388         /*
389         AcquisitionFundingList acqFundingsList = new AcquisitionFundingList();
390         List<AcquisitionFunding> acqFundings = acqFundingsList.getAcquisitionFunding();
391         int i = 0;
392         for (String acqFundingSource: acquisitionFundingSources) {
393             i++;
394             AcquisitionFunding acqFunding = new AcquisitionFunding();
395             acqFunding.setAcquisitionFundingSource(acqFundingSource);
396             acqFunding.setAcquisitionFundingSourceProvisos("funding source provisos-" + i);
397             acqFundings.add(acqFunding);
398         }
399         AcquisitionFunding addtlAcqFunding = new AcquisitionFunding();
400         addtlAcqFunding.setAcquisitionFundingCurrency("USD");
401         acqFundings.add(addtlAcqFunding);
402         acquisition.setAcquisitionFundingList(acqFundingsList);
403         */
404
405         OwnerList ownersList = new OwnerList();
406         List<String> owners = ownersList.getOwner();
407         for (String owner: acqOwners) {
408           owners.add(owner);
409         }
410         acquisition.setOwners(ownersList);
411
412         AcquisitionSourceList acqSourcesList = new AcquisitionSourceList();
413         List<String> acqSources = acqSourcesList.getAcquisitionSource();
414         for (String acqSource: acquisitionSources) {
415           acqSources.add(acqSource);
416         }
417         acquisition.setAcquisitionSources(acqSourcesList);
418
419         MultipartOutput multipart = new MultipartOutput();
420         OutputPart commonPart =
421             multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
422         AcquisitionClient acquisitionClient = new AcquisitionClient();
423         commonPart.getHeaders().add("label", acquisitionClient.getCommonPartName());
424
425         if(logger.isDebugEnabled()){
426             logger.debug("to be created, acquisition common");
427             logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class));
428         }
429
430         return multipart;
431     }
432 }