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