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