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