]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b8103304bfc09cb0c46fc3aa7870b026e9f41eb8
[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.AcquisitionsCommonList;
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 int CREATED_STATUS = Response.Status.CREATED.getStatusCode();
74     private int OK_STATUS = Response.Status.OK.getStatusCode();
75     private String personAuthCSID = null; 
76     private String acquisitionAuthorizerRefName = null;
77     private String acquisitionFundingSourceRefName = null;
78     // Not ready for multiples, yet
79     //private String acquisitionSourcesRefName = null;
80     private String fieldCollectorRefName = null;
81     private final int NUM_AUTH_REFS_EXPECTED = 3;
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                                                                 acquisitionFundingSourceRefName,
124                                                                 fieldCollectorRefName );
125
126         AcquisitionClient acquisitionClient = new AcquisitionClient();
127         ClientResponse<Response> res = acquisitionClient.create(multipart);
128
129         int statusCode = res.getStatus();
130
131         // Check the status code of the response: does it match
132         // the expected response(s)?
133         //
134         // Specifically:
135         // Does it fall within the set of valid status codes?
136         // Does it exactly match the expected status code?
137         if(logger.isDebugEnabled()){
138             logger.debug(testName + ": status = " + statusCode);
139         }
140         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
141                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
142         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
143
144         // Store the ID returned from the first resource created
145         // for additional tests below.
146         if (knownResourceId == null){
147             knownResourceId = extractId(res);
148             if (logger.isDebugEnabled()) {
149                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
150             }
151         }
152         
153         // Store the IDs from every resource created by tests,
154         // so they can be deleted after tests have been run.
155         acquisitionIdsCreated.add(extractId(res));
156     }
157     
158     protected void createPersonRefs(){
159         String authRefName = 
160                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
161         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
162         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
163                         PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
164         ClientResponse<Response> res = personAuthClient.create(multipart);
165         int statusCode = res.getStatus();
166
167         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
168                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
169         Assert.assertEquals(statusCode, CREATED_STATUS);
170         personAuthCSID = extractId(res);
171         
172         acquisitionAuthorizerRefName = PersonAuthorityClientUtils.createPersonRefName(
173                                                                 authRefName, "Annie Authorizer", true);
174         personIdsCreated.add(createPerson("Annie", "Authorizer", acquisitionAuthorizerRefName));
175         
176         acquisitionFundingSourceRefName = PersonAuthorityClientUtils.createPersonRefName(
177                                                                         authRefName, "Sammy Source", true);
178         personIdsCreated.add(createPerson("Sammy", "Source", acquisitionFundingSourceRefName));
179         
180         
181         fieldCollectorRefName = PersonAuthorityClientUtils.createPersonRefName(
182                                                                         authRefName, "Connie Collector", true);
183         personIdsCreated.add(createPerson("Connie", "Collector", fieldCollectorRefName));
184     }
185     
186     protected String createPerson(String firstName, String surName, String refName ) {
187         Map<String, String> personInfo = new HashMap<String,String>();
188         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
189         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
190         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
191         MultipartOutput multipart = 
192                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
193                                 refName, 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, CREATED_STATUS);
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.getFieldCollector(), fieldCollectorRefName);
236         
237         // Get the auth refs and check them
238         ClientResponse<AuthorityRefList> res2 =
239             acquisitionClient.getAuthorityRefs(knownResourceId);
240         statusCode = res2.getStatus();
241
242         if(logger.isDebugEnabled()){
243             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
244         }
245         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
246                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
247         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
248         AuthorityRefList list = res2.getEntity();
249
250         // Optionally output additional data about list members for debugging.
251         boolean iterateThroughList = true;
252         if(iterateThroughList && logger.isDebugEnabled()){
253             List<AuthorityRefList.AuthorityRefItem> items =
254                     list.getAuthorityRefItem();
255             int i = 0;
256             for(AuthorityRefList.AuthorityRefItem item : items){
257                 logger.debug(testName + ": list-item[" + i + "] Field:" +
258                                 item.getSourceField() + "= " +
259                         item.getAuthDisplayName() +
260                         item.getItemDisplayName());
261                 logger.debug(testName + ": list-item[" + i + "] refName=" +
262                         item.getRefName());
263                 logger.debug(testName + ": list-item[" + i + "] URI=" +
264                         item.getUri());
265                 i++;
266             }
267             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
268         }
269     }
270
271
272     // ---------------------------------------------------------------
273     // Cleanup of resources created during testing
274     // ---------------------------------------------------------------
275
276     /**
277      * Deletes all resources created by tests, after all tests have been run.
278      *
279      * This cleanup method will always be run, even if one or more tests fail.
280      * For this reason, it attempts to remove all resources created
281      * at any point during testing, even if some of those resources
282      * may be expected to be deleted by certain tests.
283      */
284     @AfterClass(alwaysRun=true)
285     public void cleanUp() {
286         String noTest = System.getProperty("noTestCleanup");
287         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
288             if (logger.isDebugEnabled()) {
289                 logger.debug("Skipping Cleanup phase ...");
290             }
291             return;
292         }
293         if (logger.isDebugEnabled()) {
294             logger.debug("Cleaning up temporary resources created for testing ...");
295         }
296         AcquisitionClient acquisitionClient = new AcquisitionClient();
297         for (String resourceId : acquisitionIdsCreated) {
298            // Note: Any non-success responses are ignored and not reported.
299            ClientResponse<Response> res = acquisitionClient.delete(resourceId);
300            res.releaseConnection();
301         }
302         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
303         // Delete persons before PersonAuth
304         for (String resourceId : personIdsCreated) {
305             // Note: Any non-success responses are ignored and not reported.
306             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
307             res.releaseConnection();
308         }
309         // Note: Any non-success response is ignored and not reported.
310         ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
311         res.releaseConnection();
312     }
313
314     // ---------------------------------------------------------------
315     // Utility methods used by tests above
316     // ---------------------------------------------------------------
317     @Override
318     public String getServicePathComponent() {
319         return SERVICE_PATH_COMPONENT;
320     }
321
322    private MultipartOutput createAcquisitionInstance(
323                         String accessionDate,
324                                 String acquisitionAuthorizer,
325                                 String acquisitionFundingSource,
326                                 String fieldCollector ) {
327         AcquisitionsCommon acquisition = new AcquisitionsCommon();
328         acquisition.setAccessionDate(accessionDate);
329         acquisition.setAcquisitionAuthorizer(acquisitionAuthorizer);
330         acquisition.setAcquisitionFundingSource(acquisitionFundingSource);
331         acquisition.setFieldCollector(fieldCollector);
332         MultipartOutput multipart = new MultipartOutput();
333         OutputPart commonPart =
334             multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
335         AcquisitionClient acquisitionClient = new AcquisitionClient();
336         commonPart.getHeaders().add("label", acquisitionClient.getCommonPartName());
337
338         if(logger.isDebugEnabled()){
339             logger.debug("to be created, acquisition common");
340             logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class));
341         }
342
343         return multipart;
344     }
345 }