]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
6845b0537ec91f3b69e43680558181ec3e72a219
[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.CollectionSpaceClient;
35 import org.collectionspace.services.client.LoaninClient;
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.common.authorityref.AuthorityRefList.AuthorityRefItem;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.collectionspace.services.loanin.LoansinCommon;
42 //import org.collectionspace.services.loanin.LoansinCommonList;
43
44 import org.jboss.resteasy.client.ClientResponse;
45
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
48 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * LoaninAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Loanin (aka Loans In) Service.
59  *
60  * $LastChangedRevision$
61  * $LastChangedDate$
62  */
63 public class LoaninAuthRefsTest extends BaseServiceTest {
64
65     private final String CLASS_NAME = LoaninAuthRefsTest.class.getName();
66     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67     
68     // Instance variables specific to this test.
69     final String SERVICE_PATH_COMPONENT = "loansin";
70     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
71     private String knownResourceId = null;
72     private List<String> loaninIdsCreated = new ArrayList<String>();
73     private List<String> personIdsCreated = new ArrayList<String>();
74     private String personAuthCSID = null;
75     private String lendersAuthorizerRefName = null;
76     private String lendersContactRefName = null;
77     private String loanInContactRefName = null;
78     // FIXME: May change when repeatable / multivalue 'lenders' field is added
79     // to tenant-bindings.xml
80     private final int NUM_AUTH_REFS_EXPECTED = 3;
81
82     /* (non-Javadoc)
83      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
84      */
85     @Override
86     protected CollectionSpaceClient getClientInstance() {
87         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
88     }
89     
90     /* (non-Javadoc)
91      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
92      */
93     @Override
94         protected AbstractCommonList getAbstractCommonList(
95                         ClientResponse<AbstractCommonList> response) {
96         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
97     }
98
99     // ---------------------------------------------------------------
100     // CRUD tests : CREATE tests
101     // ---------------------------------------------------------------
102     // Success outcomes
103     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
104     public void createWithAuthRefs(String testName) throws Exception {
105
106         if (logger.isDebugEnabled()) {
107             logger.debug(testBanner(testName, CLASS_NAME));
108         }
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         // Create a new Loans In resource.
118         //
119         // One or more fields in this resource will be PersonAuthority
120         // references, and will refer to Person resources by their refNames.
121         LoaninClient loaninClient = new LoaninClient();
122         MultipartOutput multipart = createLoaninInstance(
123                 "loanInNumber-" + identifier,
124                 "returnDate-" + identifier,
125                 lendersAuthorizerRefName,
126                 lendersContactRefName,
127                 loanInContactRefName);
128         ClientResponse<Response> response = loaninClient.create(multipart);
129         int statusCode = response.getStatus();
130         try {
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(response);
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                 loaninIdsCreated.add(extractId(response));
156         } finally {
157                 response.releaseConnection();
158         }
159     }
160     
161     protected void createPersonRefs(){
162
163         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
164         // Create a temporary PersonAuthority resource, and its corresponding
165         // refName by which it can be identified.
166         String authRefName = 
167                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
168         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
169             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
170         ClientResponse<Response> res = personAuthClient.create(multipart);
171         int statusCode = res.getStatus();
172
173         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
174             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
175         Assert.assertEquals(statusCode, STATUS_CREATED);
176         personAuthCSID = extractId(res);
177
178         // Create temporary Person resources, and their corresponding refNames
179         // by which they can be identified.
180         lendersAuthorizerRefName =
181             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
182         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
183
184         lendersContactRefName =
185             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
186         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
187         
188         loanInContactRefName =
189             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Carrie Loanincontact", true);
190         personIdsCreated.add(createPerson("Carrie", "Loanincontact", loanInContactRefName));
191
192         // FIXME: Add instance(s) of 'lenders' field when we can work with
193         // repeatable / multivalued authority reference fields.  Be sure to
194         // change the NUM_AUTH_REFS_EXPECTED constant accordingly, or otherwise
195         // revise check for numbers of authority fields expected in readAndCheckAuthRefs.
196     }
197     
198     protected String createPerson(String firstName, String surName, String refName ) {
199         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
200         Map<String, String> personInfo = new HashMap<String,String>();
201         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
202         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
203         MultipartOutput multipart = 
204                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
205                                 refName, personInfo, personAuthClient.getItemCommonPartName());
206         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
207         int statusCode = res.getStatus();
208
209         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
210                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
211         Assert.assertEquals(statusCode, STATUS_CREATED);
212         return extractId(res);
213     }
214
215     // Success outcomes
216     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
217         dependsOnMethods = {"createWithAuthRefs"})
218     public void readAndCheckAuthRefs(String testName) throws Exception {
219
220         if (logger.isDebugEnabled()) {
221             logger.debug(testBanner(testName, CLASS_NAME));
222         }
223         // Perform setup.
224         testSetup(STATUS_OK, ServiceRequestType.READ);
225
226         // Submit the request to the service and store the response.
227         LoaninClient loaninClient = new LoaninClient();
228         ClientResponse<MultipartInput> res = loaninClient.read(knownResourceId);
229         int statusCode = res.getStatus();
230
231         // Check the status code of the response: does it match
232         // the expected response(s)?
233         if(logger.isDebugEnabled()){
234             logger.debug(testName + ".read: status = " + statusCode);
235         }
236         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
237             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
238         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
239
240         MultipartInput input = (MultipartInput) res.getEntity();
241         LoansinCommon loanin = (LoansinCommon) extractPart(input,
242             loaninClient.getCommonPartName(), LoansinCommon.class);
243         Assert.assertNotNull(loanin);
244         if(logger.isDebugEnabled()){
245             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
246         }
247         // Check a couple of fields
248         // FIXME
249         Assert.assertEquals(loanin.getLendersAuthorizer(), lendersAuthorizerRefName);
250         Assert.assertEquals(loanin.getLendersContact(), lendersContactRefName);
251         Assert.assertEquals(loanin.getLoanInContact(), loanInContactRefName);
252         
253         // Get the auth refs and check them
254         ClientResponse<AuthorityRefList> res2 =
255            loaninClient.getAuthorityRefs(knownResourceId);
256         statusCode = res2.getStatus();
257
258         if(logger.isDebugEnabled()){
259             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
260         }
261         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
262                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
263         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
264         AuthorityRefList list = res2.getEntity();
265         
266         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
267         int numAuthRefsFound = items.size();
268         if(logger.isDebugEnabled()){
269             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
270                 " authority references, found " + numAuthRefsFound);
271         }
272         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
273             "Did not find all expected authority references! " +
274             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
275
276         // Optionally output additional data about list members for debugging.
277         boolean iterateThroughList = true;
278         if(iterateThroughList && logger.isDebugEnabled()){
279             int i = 0;
280             for(AuthorityRefList.AuthorityRefItem item : items){
281                 logger.debug(testName + ": list-item[" + i + "] Field:" +
282                                 item.getSourceField() + "= " +
283                         item.getAuthDisplayName() +
284                         item.getItemDisplayName());
285                 logger.debug(testName + ": list-item[" + i + "] refName=" +
286                         item.getRefName());
287                 logger.debug(testName + ": list-item[" + i + "] URI=" +
288                         item.getUri());
289                 i++;
290             }
291         }
292     }
293
294
295     // ---------------------------------------------------------------
296     // Cleanup of resources created during testing
297     // ---------------------------------------------------------------
298
299     /**
300      * Deletes all resources created by tests, after all tests have been run.
301      *
302      * This cleanup method will always be run, even if one or more tests fail.
303      * For this reason, it attempts to remove all resources created
304      * at any point during testing, even if some of those resources
305      * may be expected to be deleted by certain tests.
306      */
307     @AfterClass(alwaysRun=true)
308     public void cleanUp() {
309         String noTest = System.getProperty("noTestCleanup");
310         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
311             if (logger.isDebugEnabled()) {
312                 logger.debug("Skipping Cleanup phase ...");
313             }
314             return;
315         }
316         if (logger.isDebugEnabled()) {
317             logger.debug("Cleaning up temporary resources created for testing ...");
318         }
319         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
320         // Delete Person resource(s) (before PersonAuthority resources).
321         
322         for (String resourceId : personIdsCreated) {
323             // Note: Any non-success responses are ignored and not reported.
324                 ClientResponse<Response> response = 
325                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
326                 response.releaseConnection();
327         }
328         
329         // Delete PersonAuthority resource(s).
330         // Note: Any non-success response is ignored and not reported.
331         if (personAuthCSID != null) {
332                 personAuthClient.delete(personAuthCSID);
333                 // Delete Loans In resource(s).
334                 LoaninClient loaninClient = new LoaninClient();
335                 ClientResponse<Response> response = null;
336                 for (String resourceId : loaninIdsCreated) {
337                     // Note: Any non-success responses are ignored and not reported.
338                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
339                     response.releaseConnection();
340                 }
341         }
342     }
343
344     // ---------------------------------------------------------------
345     // Utility methods used by tests above
346     // ---------------------------------------------------------------
347     @Override
348     public String getServicePathComponent() {
349         return SERVICE_PATH_COMPONENT;
350     }
351
352    private MultipartOutput createLoaninInstance(String loaninNumber,
353                 String returnDate,
354                 String lendersAuthorizer,
355                 String lendersContact,
356                 String loaninContact) {
357         LoansinCommon loanin = new LoansinCommon();
358         loanin.setLoanInNumber(loaninNumber);
359         loanin.setLoanInNumber(returnDate);
360         loanin.setLendersAuthorizer(lendersAuthorizer);
361         loanin.setLendersContact(lendersContact);
362         loanin.setLoanInContact(loaninContact);
363         MultipartOutput multipart = new MultipartOutput();
364         OutputPart commonPart =
365             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
366         commonPart.getHeaders().add("label", new LoaninClient().getCommonPartName());
367
368         if(logger.isDebugEnabled()){
369             logger.debug("to be created, loanin common");
370             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
371         }
372
373         return multipart;
374     }
375 }