]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d58348b69c5ee2e368c8d1ff2a6bdafa00ba7153
[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 Logger logger =
65        LoggerFactory.getLogger(AcquisitionAuthRefsTest.class);
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();
72     private List<String> personIdsCreated = new ArrayList();
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         testSetup(CREATED_STATUS, ServiceRequestType.CREATE,testName);
108
109         // Submit the request to the service and store the response.
110         String identifier = createIdentifier();
111         
112         // Create all the person refs and entities
113         createPersonRefs();
114         
115         MultipartOutput multipart = createAcquisitionInstance(
116                                                 "April 1, 2010",
117                                                                 acquisitionAuthorizerRefName,
118                                                                 acquisitionFundingSourceRefName,
119                                                                 fieldCollectorRefName );
120
121         AcquisitionClient acquisitionClient = new AcquisitionClient();
122         ClientResponse<Response> res = acquisitionClient.create(multipart);
123
124         int statusCode = res.getStatus();
125
126         // Check the status code of the response: does it match
127         // the expected response(s)?
128         //
129         // Specifically:
130         // Does it fall within the set of valid status codes?
131         // Does it exactly match the expected status code?
132         if(logger.isDebugEnabled()){
133             logger.debug(testName + ": status = " + statusCode);
134         }
135         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
136                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
137         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
138
139         // Store the ID returned from the first resource created
140         // for additional tests below.
141         if (knownResourceId == null){
142             knownResourceId = extractId(res);
143             if (logger.isDebugEnabled()) {
144                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
145             }
146         }
147         
148         // Store the IDs from every resource created by tests,
149         // so they can be deleted after tests have been run.
150         acquisitionIdsCreated.add(extractId(res));
151     }
152     
153     protected void createPersonRefs(){
154         String authRefName = 
155                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
156         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
157         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
158                         PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
159         ClientResponse<Response> res = personAuthClient.create(multipart);
160         int statusCode = res.getStatus();
161
162         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
163                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
164         Assert.assertEquals(statusCode, CREATED_STATUS);
165         personAuthCSID = extractId(res);
166         
167         acquisitionAuthorizerRefName = PersonAuthorityClientUtils.createPersonRefName(
168                                                                 authRefName, "Annie Authorizer", true);
169         personIdsCreated.add(createPerson("Annie", "Authorizer", acquisitionAuthorizerRefName));
170         
171         acquisitionFundingSourceRefName = PersonAuthorityClientUtils.createPersonRefName(
172                                                                         authRefName, "Sammy Source", true);
173         personIdsCreated.add(createPerson("Sammy", "Source", acquisitionFundingSourceRefName));
174         
175         
176         fieldCollectorRefName = PersonAuthorityClientUtils.createPersonRefName(
177                                                                         authRefName, "Connie Collector", true);
178         personIdsCreated.add(createPerson("Connie", "Collector", fieldCollectorRefName));
179     }
180     
181     protected String createPerson(String firstName, String surName, String refName ) {
182         Map<String, String> personInfo = new HashMap<String,String>();
183         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
184         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
185         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
186         MultipartOutput multipart = 
187                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
188                                 refName, personInfo, personAuthClient.getItemCommonPartName());
189         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
190         int statusCode = res.getStatus();
191
192         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
193                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
194         Assert.assertEquals(statusCode, CREATED_STATUS);
195         return extractId(res);
196     }
197
198     // Success outcomes
199     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
200         dependsOnMethods = {"createWithAuthRefs"})
201     public void readAndCheckAuthRefs(String testName) throws Exception {
202
203         // Perform setup.
204         testSetup(OK_STATUS, ServiceRequestType.READ,testName);
205
206         // Submit the request to the service and store the response.
207         AcquisitionClient acquisitionClient = new AcquisitionClient();
208         ClientResponse<MultipartInput> res = acquisitionClient.read(knownResourceId);
209         int statusCode = res.getStatus();
210
211         // Check the status code of the response: does it match
212         // the expected response(s)?
213         if(logger.isDebugEnabled()){
214             logger.debug(testName + ".read: status = " + statusCode);
215         }
216         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
217                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
218         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
219
220         MultipartInput input = (MultipartInput) res.getEntity();
221         AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input,
222                         acquisitionClient.getCommonPartName(), AcquisitionsCommon.class);
223         Assert.assertNotNull(acquisition);
224         // Check a couple of fields
225         Assert.assertEquals(acquisition.getAcquisitionAuthorizer(), acquisitionAuthorizerRefName);
226         Assert.assertEquals(acquisition.getFieldCollector(), fieldCollectorRefName);
227         
228         // Get the auth refs and check them
229         ClientResponse<AuthorityRefList> res2 =
230             acquisitionClient.getAuthorityRefs(knownResourceId);
231         statusCode = res2.getStatus();
232
233         if(logger.isDebugEnabled()){
234             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
235         }
236         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
237                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
238         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
239         AuthorityRefList list = res2.getEntity();
240
241         // Optionally output additional data about list members for debugging.
242         boolean iterateThroughList = true;
243         if(iterateThroughList && logger.isDebugEnabled()){
244             List<AuthorityRefList.AuthorityRefItem> items =
245                     list.getAuthorityRefItem();
246             int i = 0;
247             for(AuthorityRefList.AuthorityRefItem item : items){
248                 logger.debug(testName + ": list-item[" + i + "] Field:" +
249                                 item.getSourceField() + "= " +
250                         item.getAuthDisplayName() +
251                         item.getItemDisplayName());
252                 logger.debug(testName + ": list-item[" + i + "] refName=" +
253                         item.getRefName());
254                 logger.debug(testName + ": list-item[" + i + "] URI=" +
255                         item.getUri());
256                 i++;
257             }
258             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
259         }
260     }
261
262
263     // ---------------------------------------------------------------
264     // Cleanup of resources created during testing
265     // ---------------------------------------------------------------
266
267     /**
268      * Deletes all resources created by tests, after all tests have been run.
269      *
270      * This cleanup method will always be run, even if one or more tests fail.
271      * For this reason, it attempts to remove all resources created
272      * at any point during testing, even if some of those resources
273      * may be expected to be deleted by certain tests.
274      */
275     @AfterClass(alwaysRun=true)
276     public void cleanUp() {
277         String noTest = System.getProperty("noTestCleanup");
278         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
279             if (logger.isDebugEnabled()) {
280                 logger.debug("Skipping Cleanup phase ...");
281             }
282             return;
283         }
284         if (logger.isDebugEnabled()) {
285             logger.debug("Cleaning up temporary resources created for testing ...");
286         }
287         AcquisitionClient acquisitionClient = new AcquisitionClient();
288         for (String resourceId : acquisitionIdsCreated) {
289            // Note: Any non-success responses are ignored and not reported.
290            ClientResponse<Response> res = acquisitionClient.delete(resourceId);
291         }
292         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
293         // Delete persons before PersonAuth
294         for (String resourceId : personIdsCreated) {
295             // Note: Any non-success responses are ignored and not reported.
296             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
297         }
298         // Note: Any non-success response is ignored and not reported.
299         ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
300     }
301
302     // ---------------------------------------------------------------
303     // Utility methods used by tests above
304     // ---------------------------------------------------------------
305     @Override
306     public String getServicePathComponent() {
307         return SERVICE_PATH_COMPONENT;
308     }
309
310    private MultipartOutput createAcquisitionInstance(
311                         String accessionDate,
312                                 String acquisitionAuthorizer,
313                                 String acquisitionFundingSource,
314                                 String fieldCollector ) {
315         AcquisitionsCommon acquisition = new AcquisitionsCommon();
316         acquisition.setAccessionDate(accessionDate);
317         acquisition.setAcquisitionAuthorizer(acquisitionAuthorizer);
318         acquisition.setAcquisitionFundingSource(acquisitionFundingSource);
319         acquisition.setFieldCollector(fieldCollector);
320         MultipartOutput multipart = new MultipartOutput();
321         OutputPart commonPart =
322             multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
323         AcquisitionClient acquisitionClient = new AcquisitionClient();
324         commonPart.getHeaders().add("label", acquisitionClient.getCommonPartName());
325
326         if(logger.isDebugEnabled()){
327             logger.debug("to be created, acquisition common");
328             logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class));
329         }
330
331         return multipart;
332     }
333 }