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