]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7eebf7d0726b6da48d73fe6131437456c0f5dff3
[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 = 5;
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         csid = createPerson("Fran", "Funding-SourceOne", "franFundingSourceOne", authRefName);
175         acquisitionFundingSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
176         personIdsCreated.add(csid);
177
178         csid = createPerson("Fahd", "Funding-SourceTwo", "fahdFundingSourceTwo", authRefName);
179         acquisitionFundingSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
180         personIdsCreated.add(csid);
181
182         csid = createPerson("Sammy", "SourceOne", "sammySourceOne", authRefName);
183         acquisitionSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
184         personIdsCreated.add(csid);
185
186         csid = createPerson("Serena", "SourceTwo", "serenaSourceTwo", authRefName);
187         acquisitionSourcesRefNames.add(PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null));
188         personIdsCreated.add(csid);
189     }
190     
191     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
192         Map<String, String> personInfo = new HashMap<String,String>();
193         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
194         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
195         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
196         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
197         MultipartOutput multipart = 
198                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
199                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
200         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
201         int statusCode = res.getStatus();
202
203         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
204             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
205         Assert.assertEquals(statusCode, STATUS_CREATED);
206         return extractId(res);
207     }
208
209     // Success outcomes
210     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
211         dependsOnMethods = {"createWithAuthRefs"})
212     public void readAndCheckAuthRefs(String testName) throws Exception {
213
214         if (logger.isDebugEnabled()) {
215             logger.debug(testBanner(testName, CLASS_NAME));
216         };
217         
218         // Perform setup.
219         testSetup(STATUS_OK, ServiceRequestType.READ);
220         
221         // Submit the request to the service and store the response.
222         AcquisitionClient acquisitionClient = new AcquisitionClient();
223         ClientResponse<MultipartInput> res = acquisitionClient.read(knownResourceId);
224         int statusCode = res.getStatus();
225
226         // Check the status code of the response: does it match
227         // the expected response(s)?
228         if(logger.isDebugEnabled()){
229             logger.debug(testName + ".read: status = " + statusCode);
230         }
231         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
232             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
233         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
234
235         MultipartInput input = (MultipartInput) res.getEntity();
236         AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input,
237                         acquisitionClient.getCommonPartName(), AcquisitionsCommon.class);
238         Assert.assertNotNull(acquisition);
239
240         // Check a couple of fields
241         // Scalar fields
242         Assert.assertEquals(acquisition.getAcquisitionAuthorizer(), acquisitionAuthorizerRefName);
243         
244         // In repeatable groups of fields
245         AcquisitionFundingList acqFundingList = acquisition.getAcquisitionFundingList();
246         List<AcquisitionFunding> acqFundings = acqFundingList.getAcquisitionFunding();
247         List<String> acqFundingSourceRefNamesFound = new ArrayList();
248         for (AcquisitionFunding acqFunding : acqFundings) {
249             String acqFundingSourceRefName = acqFunding.getAcquisitionFundingSource();
250             acqFundingSourceRefNamesFound.add(acqFundingSourceRefName);
251         }
252         Assert.assertTrue(acqFundingSourceRefNamesFound.containsAll(acquisitionFundingSourcesRefNames));
253
254         // In scalar repeatable fields
255         AcquisitionSourceList acquisitionSources = acquisition.getAcquisitionSources();
256         List<String> sources = acquisitionSources.getAcquisitionSource();
257         for (String refName : sources) {
258           Assert.assertTrue(acquisitionSourcesRefNames.contains(refName));
259         }
260         
261         // Get the auth refs and check them
262         ClientResponse<AuthorityRefList> res2 =
263             acquisitionClient.getAuthorityRefs(knownResourceId);
264         statusCode = res2.getStatus();
265
266         if(logger.isDebugEnabled()){
267             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
268         }
269         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
270                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
271         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
272         AuthorityRefList list = res2.getEntity();
273
274         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
275         int numAuthRefsFound = items.size();
276         if(logger.isDebugEnabled()){
277             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
278                 " authority references, found " + numAuthRefsFound);
279         }
280         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
281             "Did not find all expected authority references! " +
282             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
283
284         // Optionally output additional data about list members for debugging.
285         boolean iterateThroughList = true;
286         if(iterateThroughList && logger.isDebugEnabled()){
287             int i = 0;
288             for(AuthorityRefList.AuthorityRefItem item : items){
289                 logger.debug(testName + ": list-item[" + i + "] Field:" +
290                                 item.getSourceField() + "= " +
291                         item.getAuthDisplayName() +
292                         item.getItemDisplayName());
293                 logger.debug(testName + ": list-item[" + i + "] refName=" +
294                         item.getRefName());
295                 logger.debug(testName + ": list-item[" + i + "] URI=" +
296                         item.getUri());
297                 i++;
298             }
299         }
300     }
301
302
303     // ---------------------------------------------------------------
304     // Cleanup of resources created during testing
305     // ---------------------------------------------------------------
306
307     /**
308      * Deletes all resources created by tests, after all tests have been run.
309      *
310      * This cleanup method will always be run, even if one or more tests fail.
311      * For this reason, it attempts to remove all resources created
312      * at any point during testing, even if some of those resources
313      * may be expected to be deleted by certain tests.
314      */
315     @AfterClass(alwaysRun=true)
316     public void cleanUp() {
317         String noTest = System.getProperty("noTestCleanup");
318         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
319             if (logger.isDebugEnabled()) {
320                 logger.debug("Skipping Cleanup phase ...");
321             }
322             return;
323         }
324         if (logger.isDebugEnabled()) {
325             logger.debug("Cleaning up temporary resources created for testing ...");
326         }
327         AcquisitionClient acquisitionClient = new AcquisitionClient();
328         for (String resourceId : acquisitionIdsCreated) {
329            // Note: Any non-success responses are ignored and not reported.
330            ClientResponse<Response> res = acquisitionClient.delete(resourceId);
331            res.releaseConnection();
332         }
333         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
334         // Delete persons before PersonAuth
335         for (String resourceId : personIdsCreated) {
336             // Note: Any non-success responses are ignored and not reported.
337             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
338             res.releaseConnection();
339         }
340         // Note: Any non-success response is ignored and not reported.
341         ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
342         res.releaseConnection();
343     }
344
345     // ---------------------------------------------------------------
346     // Utility methods used by tests above
347     // ---------------------------------------------------------------
348     @Override
349     public String getServicePathComponent() {
350         return SERVICE_PATH_COMPONENT;
351     }
352
353    private MultipartOutput createAcquisitionInstance(
354         String accessionDate,
355         String acquisitionAuthorizer,
356         List<String> acquisitionFundingSources,
357         List<String> acquisitionSources) {
358        
359         AcquisitionsCommon acquisition = new AcquisitionsCommon();
360         acquisition.setAccessionDate(accessionDate);
361         acquisition.setAcquisitionAuthorizer(acquisitionAuthorizer);
362         
363         AcquisitionFundingList acqFundingsList = new AcquisitionFundingList();
364         List<AcquisitionFunding> acqFundings = acqFundingsList.getAcquisitionFunding();
365         int i = 0;
366         for (String acqFundingSource: acquisitionFundingSources) {
367             i++;
368             AcquisitionFunding acqFunding = new AcquisitionFunding();
369             acqFunding.setAcquisitionFundingSource(acqFundingSource);
370             acqFunding.setAcquisitionFundingSourceProvisos("funding source provisos-" + i);
371             acqFundings.add(acqFunding);
372         }
373         AcquisitionFunding addtlAcqFunding = new AcquisitionFunding();
374         addtlAcqFunding.setAcquisitionFundingCurrency("USD");
375         acqFundings.add(addtlAcqFunding);
376         acquisition.setAcquisitionFundingList(acqFundingsList);
377
378         AcquisitionSourceList acqSourcesList = new AcquisitionSourceList();
379         List<String> acqSources = acqSourcesList.getAcquisitionSource();
380         for (String acqSource: acquisitionSources) {
381           acqSources.add(acqSource);
382         }
383         acquisition.setAcquisitionSources(acqSourcesList);
384
385         MultipartOutput multipart = new MultipartOutput();
386         OutputPart commonPart =
387             multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
388         AcquisitionClient acquisitionClient = new AcquisitionClient();
389         commonPart.getHeaders().add("label", acquisitionClient.getCommonPartName());
390
391         if(logger.isDebugEnabled()){
392             logger.debug("to be created, acquisition common");
393             logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class));
394         }
395
396         return multipart;
397     }
398 }