]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
69eca30e41c6f4917e8fdd60b3a41e426afa5769
[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 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 final int NUM_AUTH_REFS_EXPECTED = 2;
79
80     /* (non-Javadoc)
81      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
82      */
83     @Override
84     protected CollectionSpaceClient getClientInstance() {
85         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
86     }
87     
88     /* (non-Javadoc)
89      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
90      */
91     @Override
92         protected AbstractCommonList getAbstractCommonList(
93                         ClientResponse<AbstractCommonList> response) {
94         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
95     }
96
97     // ---------------------------------------------------------------
98     // CRUD tests : CREATE tests
99     // ---------------------------------------------------------------
100     // Success outcomes
101     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
102     public void createWithAuthRefs(String testName) throws Exception {
103
104         if (logger.isDebugEnabled()) {
105             logger.debug(testBanner(testName, CLASS_NAME));
106         };
107         
108         // Perform setup.
109         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
110
111         // Submit the request to the service and store the response.
112         String identifier = createIdentifier();
113         
114         // Create all the person refs and entities
115         createPersonRefs();
116         
117         MultipartOutput multipart = createAcquisitionInstance(
118             "April 1, 2010",
119             acquisitionAuthorizerRefName,
120             acquisitionFundingSourceRefName);
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("Sammy", "Source", "sammySource", authRefName);
173         acquisitionFundingSourceRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
174         personIdsCreated.add(csid);
175     }
176     
177     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
178         Map<String, String> personInfo = new HashMap<String,String>();
179         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
180         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
181         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
182         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
183         MultipartOutput multipart = 
184                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
185                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
186         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
187         int statusCode = res.getStatus();
188
189         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
190             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
191         Assert.assertEquals(statusCode, STATUS_CREATED);
192         return extractId(res);
193     }
194
195     // Success outcomes
196     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
197         dependsOnMethods = {"createWithAuthRefs"})
198     public void readAndCheckAuthRefs(String testName) throws Exception {
199
200         if (logger.isDebugEnabled()) {
201             logger.debug(testBanner(testName, CLASS_NAME));
202         };
203         
204         // Perform setup.
205         testSetup(STATUS_OK, ServiceRequestType.READ);
206         
207         // Submit the request to the service and store the response.
208         AcquisitionClient acquisitionClient = new AcquisitionClient();
209         ClientResponse<MultipartInput> res = acquisitionClient.read(knownResourceId);
210         int statusCode = res.getStatus();
211
212         // Check the status code of the response: does it match
213         // the expected response(s)?
214         if(logger.isDebugEnabled()){
215             logger.debug(testName + ".read: status = " + statusCode);
216         }
217         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
218             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
219         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
220
221         MultipartInput input = (MultipartInput) res.getEntity();
222         AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input,
223                         acquisitionClient.getCommonPartName(), AcquisitionsCommon.class);
224         Assert.assertNotNull(acquisition);
225         // Check a couple of fields
226         Assert.assertEquals(acquisition.getAcquisitionAuthorizer(), acquisitionAuthorizerRefName);
227         Assert.assertEquals(acquisition.getAcquisitionFundingSource(), acquisitionFundingSourceRefName);
228         
229         // Get the auth refs and check them
230         ClientResponse<AuthorityRefList> res2 =
231             acquisitionClient.getAuthorityRefs(knownResourceId);
232         statusCode = res2.getStatus();
233
234         if(logger.isDebugEnabled()){
235             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
236         }
237         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
238                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
239         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
240         AuthorityRefList list = res2.getEntity();
241
242         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
243         int numAuthRefsFound = items.size();
244         if(logger.isDebugEnabled()){
245             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
246                 " authority references, found " + numAuthRefsFound);
247         }
248         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
249             "Did not find all expected authority references! " +
250             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
251
252         // Optionally output additional data about list members for debugging.
253         boolean iterateThroughList = true;
254         if(iterateThroughList && logger.isDebugEnabled()){
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         }
268     }
269
270
271     // ---------------------------------------------------------------
272     // Cleanup of resources created during testing
273     // ---------------------------------------------------------------
274
275     /**
276      * Deletes all resources created by tests, after all tests have been run.
277      *
278      * This cleanup method will always be run, even if one or more tests fail.
279      * For this reason, it attempts to remove all resources created
280      * at any point during testing, even if some of those resources
281      * may be expected to be deleted by certain tests.
282      */
283     @AfterClass(alwaysRun=true)
284     public void cleanUp() {
285         String noTest = System.getProperty("noTestCleanup");
286         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
287             if (logger.isDebugEnabled()) {
288                 logger.debug("Skipping Cleanup phase ...");
289             }
290             return;
291         }
292         if (logger.isDebugEnabled()) {
293             logger.debug("Cleaning up temporary resources created for testing ...");
294         }
295         AcquisitionClient acquisitionClient = new AcquisitionClient();
296         for (String resourceId : acquisitionIdsCreated) {
297            // Note: Any non-success responses are ignored and not reported.
298            ClientResponse<Response> res = acquisitionClient.delete(resourceId);
299            res.releaseConnection();
300         }
301         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
302         // Delete persons before PersonAuth
303         for (String resourceId : personIdsCreated) {
304             // Note: Any non-success responses are ignored and not reported.
305             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
306             res.releaseConnection();
307         }
308         // Note: Any non-success response is ignored and not reported.
309         ClientResponse<Response> res = personAuthClient.delete(personAuthCSID);
310         res.releaseConnection();
311     }
312
313     // ---------------------------------------------------------------
314     // Utility methods used by tests above
315     // ---------------------------------------------------------------
316     @Override
317     public String getServicePathComponent() {
318         return SERVICE_PATH_COMPONENT;
319     }
320
321    private MultipartOutput createAcquisitionInstance(
322         String accessionDate,
323         String acquisitionAuthorizer,
324         String acquisitionFundingSource) {
325        
326         AcquisitionsCommon acquisition = new AcquisitionsCommon();
327         acquisition.setAccessionDate(accessionDate);
328         acquisition.setAcquisitionAuthorizer(acquisitionAuthorizer);
329         acquisition.setAcquisitionFundingSource(acquisitionFundingSource);
330         MultipartOutput multipart = new MultipartOutput();
331         OutputPart commonPart =
332             multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE);
333         AcquisitionClient acquisitionClient = new AcquisitionClient();
334         commonPart.getHeaders().add("label", acquisitionClient.getCommonPartName());
335
336         if(logger.isDebugEnabled()){
337             logger.debug("to be created, acquisition common");
338             logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class));
339         }
340
341         return multipart;
342     }
343 }