]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e51422ae03fb4ab754ea21aea12b3533faaf4c8d
[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 lenderRefName = null;
76     private String lendersAuthorizerRefName = null;
77     private String lendersContactRefName = null;
78     private String loanInContactRefName = null;
79     // FIXME: May change when repeatable / multivalue 'lenders' field is added
80     // to tenant-bindings.xml
81     private final int NUM_AUTH_REFS_EXPECTED = 4;
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         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
111
112         // Submit the request to the service and store the response.
113         String identifier = createIdentifier();
114         
115         // Create all the person refs and entities
116         createPersonRefs();
117
118         // Create a new Loans In resource.
119         //
120         // One or more fields in this resource will be PersonAuthority
121         // references, and will refer to Person resources by their refNames.
122         LoaninClient loaninClient = new LoaninClient();
123         MultipartOutput multipart = createLoaninInstance(
124                 "loanInNumber-" + identifier,
125                 "returnDate-" + identifier,
126                 lenderRefName,
127                 lendersAuthorizerRefName,
128                 lendersContactRefName,
129                 loanInContactRefName);
130         ClientResponse<Response> response = loaninClient.create(multipart);
131         int statusCode = response.getStatus();
132         try {
133                 // Check the status code of the response: does it match
134                 // the expected response(s)?
135                 //
136                 // Specifically:
137                 // Does it fall within the set of valid status codes?
138                 // Does it exactly match the expected status code?
139                 if(logger.isDebugEnabled()){
140                     logger.debug(testName + ": status = " + statusCode);
141                 }
142                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
143                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
144                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
145         
146                 // Store the ID returned from the first resource created
147                 // for additional tests below.
148                 if (knownResourceId == null){
149                     knownResourceId = extractId(response);
150                     if (logger.isDebugEnabled()) {
151                         logger.debug(testName + ": knownResourceId=" + knownResourceId);
152                     }
153                 }
154                 
155                 // Store the IDs from every resource created by tests,
156                 // so they can be deleted after tests have been run.
157                 loaninIdsCreated.add(extractId(response));
158         } finally {
159                 response.releaseConnection();
160         }
161     }
162     
163     protected void createPersonRefs(){
164
165         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
166         // Create a temporary PersonAuthority resource, and its corresponding
167         // refName by which it can be identified.
168         String authRefName = 
169                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
170         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
171             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
172         ClientResponse<Response> res = personAuthClient.create(multipart);
173         int statusCode = res.getStatus();
174
175         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
176             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
177         Assert.assertEquals(statusCode, STATUS_CREATED);
178         personAuthCSID = extractId(res);
179
180         // Create temporary Person resources, and their corresponding refNames
181         // by which they can be identified.
182         lenderRefName =
183             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Linus Lender", true);
184         personIdsCreated.add(createPerson("Linus", "Lender", lenderRefName));
185
186         lendersAuthorizerRefName =
187             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
188         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
189
190         lendersContactRefName =
191             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
192         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
193         
194         loanInContactRefName =
195             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Carrie Loanincontact", true);
196         personIdsCreated.add(createPerson("Carrie", "Loanincontact", loanInContactRefName));
197
198         // FIXME: Add instance(s) of 'lenders' field when we can work with
199         // repeatable / multivalued authority reference fields.  Be sure to
200         // change the NUM_AUTH_REFS_EXPECTED constant accordingly, or otherwise
201         // revise check for numbers of authority fields expected in readAndCheckAuthRefs.
202     }
203     
204     protected String createPerson(String firstName, String surName, String refName ) {
205         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
206         Map<String, String> personInfo = new HashMap<String,String>();
207         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
208         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
209         MultipartOutput multipart = 
210                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
211                                 refName, personInfo, personAuthClient.getItemCommonPartName());
212         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
213         int statusCode = res.getStatus();
214
215         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
216                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
217         Assert.assertEquals(statusCode, STATUS_CREATED);
218         return extractId(res);
219     }
220
221     // Success outcomes
222     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
223         dependsOnMethods = {"createWithAuthRefs"})
224     public void readAndCheckAuthRefs(String testName) throws Exception {
225
226         if (logger.isDebugEnabled()) {
227             logger.debug(testBanner(testName, CLASS_NAME));
228         }
229         // Perform setup.
230         testSetup(STATUS_OK, ServiceRequestType.READ);
231
232         // Submit the request to the service and store the response.
233         LoaninClient loaninClient = new LoaninClient();
234         ClientResponse<MultipartInput> res = loaninClient.read(knownResourceId);
235         int statusCode = res.getStatus();
236
237         // Check the status code of the response: does it match
238         // the expected response(s)?
239         if(logger.isDebugEnabled()){
240             logger.debug(testName + ".read: status = " + statusCode);
241         }
242         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
243             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
244         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
245
246         MultipartInput input = (MultipartInput) res.getEntity();
247         LoansinCommon loanin = (LoansinCommon) extractPart(input,
248             loaninClient.getCommonPartName(), LoansinCommon.class);
249         Assert.assertNotNull(loanin);
250         if(logger.isDebugEnabled()){
251             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
252         }
253         // Check a couple of fields
254         Assert.assertEquals(loanin.getLender(), lenderRefName);
255         Assert.assertEquals(loanin.getLendersAuthorizer(), lendersAuthorizerRefName);
256         Assert.assertEquals(loanin.getLendersContact(), lendersContactRefName);
257         Assert.assertEquals(loanin.getLoanInContact(), loanInContactRefName);
258         
259         // Get the auth refs and check them
260         ClientResponse<AuthorityRefList> res2 =
261            loaninClient.getAuthorityRefs(knownResourceId);
262         statusCode = res2.getStatus();
263
264         if(logger.isDebugEnabled()){
265             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
266         }
267         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
268                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
269         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
270         AuthorityRefList list = res2.getEntity();
271         
272         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
273         int numAuthRefsFound = items.size();
274         if(logger.isDebugEnabled()){
275             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
276                 " authority references, found " + numAuthRefsFound);
277         }
278
279         // Optionally output additional data about list members for debugging.
280         boolean iterateThroughList = true;
281         if(iterateThroughList && logger.isDebugEnabled()){
282             int i = 0;
283             for(AuthorityRefList.AuthorityRefItem item : items){
284                 logger.debug(testName + ": list-item[" + i + "] Field:" +
285                                 item.getSourceField() + "= " +
286                         item.getAuthDisplayName() +
287                         item.getItemDisplayName());
288                 logger.debug(testName + ": list-item[" + i + "] refName=" +
289                         item.getRefName());
290                 logger.debug(testName + ": list-item[" + i + "] URI=" +
291                         item.getUri());
292                 i++;
293             }
294         }
295
296         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
297             "Did not find all expected authority references! " +
298             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
299
300     }
301
302
303     // ---------------------------------------------------------------
304     // Cleanup of resources created during testing
305     // ---------------------------------------------------------------
306
307     /**
308      * Deletes all resources created by tests, after all tests have been run.
309      *
310      * This cleanup method will always be run, even if one or more tests fail.
311      * For this reason, it attempts to remove all resources created
312      * at any point during testing, even if some of those resources
313      * may be expected to be deleted by certain tests.
314      */
315     @AfterClass(alwaysRun=true)
316     public void cleanUp() {
317         String noTest = System.getProperty("noTestCleanup");
318         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
319             if (logger.isDebugEnabled()) {
320                 logger.debug("Skipping Cleanup phase ...");
321             }
322             return;
323         }
324         if (logger.isDebugEnabled()) {
325             logger.debug("Cleaning up temporary resources created for testing ...");
326         }
327         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
328         // Delete Person resource(s) (before PersonAuthority resources).
329         
330         for (String resourceId : personIdsCreated) {
331             // Note: Any non-success responses are ignored and not reported.
332                 ClientResponse<Response> response = 
333                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
334                 response.releaseConnection();
335         }
336         
337         // Delete PersonAuthority resource(s).
338         // Note: Any non-success response is ignored and not reported.
339         if (personAuthCSID != null) {
340                 personAuthClient.delete(personAuthCSID);
341                 // Delete Loans In resource(s).
342                 LoaninClient loaninClient = new LoaninClient();
343                 ClientResponse<Response> response = null;
344                 for (String resourceId : loaninIdsCreated) {
345                     // Note: Any non-success responses are ignored and not reported.
346                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
347                     response.releaseConnection();
348                 }
349         }
350     }
351
352     // ---------------------------------------------------------------
353     // Utility methods used by tests above
354     // ---------------------------------------------------------------
355     @Override
356     public String getServicePathComponent() {
357         return SERVICE_PATH_COMPONENT;
358     }
359
360    private MultipartOutput createLoaninInstance(String loaninNumber,
361                 String returnDate,
362                 String lender,
363                 String lendersAuthorizer,
364                 String lendersContact,
365                 String loaninContact) {
366         LoansinCommon loanin = new LoansinCommon();
367         loanin.setLoanInNumber(loaninNumber);
368         loanin.setLoanInNumber(returnDate);
369         loanin.setLender(lender);
370         loanin.setLendersAuthorizer(lendersAuthorizer);
371         loanin.setLendersContact(lendersContact);
372         loanin.setLoanInContact(loaninContact);
373         MultipartOutput multipart = new MultipartOutput();
374         OutputPart commonPart =
375             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
376         commonPart.getHeaders().add("label", new LoaninClient().getCommonPartName());
377
378         if(logger.isDebugEnabled()){
379             logger.debug("to be created, loanin common");
380             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
381         }
382
383         return multipart;
384     }
385 }