]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3c80b24783c9ef87d59600d39c375805b0f0dcd0
[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         // Optionally output additional data about list members for debugging.
267         boolean iterateThroughList = true;
268         if(iterateThroughList && logger.isDebugEnabled()){
269             List<AuthorityRefList.AuthorityRefItem> items =
270                     list.getAuthorityRefItem();
271             int i = 0;
272             for(AuthorityRefList.AuthorityRefItem item : items){
273                 logger.debug(testName + ": list-item[" + i + "] Field:" +
274                                 item.getSourceField() + "= " +
275                         item.getAuthDisplayName() +
276                         item.getItemDisplayName());
277                 logger.debug(testName + ": list-item[" + i + "] refName=" +
278                         item.getRefName());
279                 logger.debug(testName + ": list-item[" + i + "] URI=" +
280                         item.getUri());
281                 i++;
282             }
283             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
284         }
285     }
286
287
288     // ---------------------------------------------------------------
289     // Cleanup of resources created during testing
290     // ---------------------------------------------------------------
291
292     /**
293      * Deletes all resources created by tests, after all tests have been run.
294      *
295      * This cleanup method will always be run, even if one or more tests fail.
296      * For this reason, it attempts to remove all resources created
297      * at any point during testing, even if some of those resources
298      * may be expected to be deleted by certain tests.
299      */
300     @AfterClass(alwaysRun=true)
301     public void cleanUp() {
302         String noTest = System.getProperty("noTestCleanup");
303         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
304             if (logger.isDebugEnabled()) {
305                 logger.debug("Skipping Cleanup phase ...");
306             }
307             return;
308         }
309         if (logger.isDebugEnabled()) {
310             logger.debug("Cleaning up temporary resources created for testing ...");
311         }
312         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
313         // Delete Person resource(s) (before PersonAuthority resources).
314         
315         for (String resourceId : personIdsCreated) {
316             // Note: Any non-success responses are ignored and not reported.
317                 ClientResponse<Response> response = 
318                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
319                 response.releaseConnection();
320         }
321         
322         // Delete PersonAuthority resource(s).
323         // Note: Any non-success response is ignored and not reported.
324         if (personAuthCSID != null) {
325                 personAuthClient.delete(personAuthCSID);
326                 // Delete Loans In resource(s).
327                 LoaninClient loaninClient = new LoaninClient();
328                 ClientResponse<Response> response = null;
329                 for (String resourceId : loaninIdsCreated) {
330                     // Note: Any non-success responses are ignored and not reported.
331                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
332                     response.releaseConnection();
333                 }
334         }
335     }
336
337     // ---------------------------------------------------------------
338     // Utility methods used by tests above
339     // ---------------------------------------------------------------
340     @Override
341     public String getServicePathComponent() {
342         return SERVICE_PATH_COMPONENT;
343     }
344
345    private MultipartOutput createLoaninInstance(String loaninNumber,
346                 String returnDate,
347                 String lendersAuthorizer,
348                 String lendersContact,
349                 String loaninContact) {
350         LoansinCommon loanin = new LoansinCommon();
351         loanin.setLoanInNumber(loaninNumber);
352         loanin.setLoanInNumber(returnDate);
353         loanin.setLendersAuthorizer(lendersAuthorizer);
354         loanin.setLendersContact(lendersContact);
355         loanin.setLoanInContact(loaninContact);
356         MultipartOutput multipart = new MultipartOutput();
357         OutputPart commonPart =
358             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
359         commonPart.getHeaders().add("label", new LoaninClient().getCommonPartName());
360
361         if(logger.isDebugEnabled()){
362             logger.debug("to be created, loanin common");
363             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
364         }
365
366         return multipart;
367     }
368 }