]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
eac316a5ecda8e5a81d7054b0911b9c816939c48
[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.Response;
31
32 import org.collectionspace.services.PersonJAXBSchema;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.LoanoutClient;
35 import org.collectionspace.services.client.PayloadOutputPart;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.jaxb.AbstractCommonList;
43 import org.collectionspace.services.loanout.LoansoutCommon;
44 import org.collectionspace.services.person.PersonTermGroup;
45 import org.testng.Assert;
46 import org.testng.annotations.AfterClass;
47 import org.testng.annotations.Test;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * LoanoutAuthRefsTest, carries out Authority References tests against a
53  * deployed and running Loanout (aka Loans Out) Service.
54  *
55  * $LastChangedRevision$
56  * $LastChangedDate$
57  */
58 public class LoanoutAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
59
60     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
61     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
62
63     // Instance variables specific to this test.
64     final String SERVICE_NAME = "loansout";
65     final String SERVICE_PATH_COMPONENT = "loansout";
66     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
67     private String knownResourceId = null;
68     private List<String> loanoutIdsCreated = new ArrayList<String>();
69     private List<String> personIdsCreated = new ArrayList<String>();
70     private String personAuthCSID = null;
71     private String borrowerRefName = null;
72     private String borrowersContactRefName = null;
73     private String lendersAuthorizerRefName = null;
74     private String lendersContactRefName = null;
75
76     // FIXME: Can add 'borrower' - likely to be an organization
77     // authority - as an authRef to tests below, and increase the
78     // number of expected authRefs to 4.
79     private final int NUM_AUTH_REFS_EXPECTED = 4;
80     
81     private final static String CURRENT_DATE_UTC =
82             GregorianCalendarDateTimeUtils.currentDateUTC();
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     @Override
93         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
94         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
95         }
96     
97     /* (non-Javadoc)
98      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
99      */
100     @Override
101         protected AbstractCommonList getCommonList(Response response) {
102         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
103     }
104
105     // ---------------------------------------------------------------
106     // CRUD tests : CREATE tests
107     // ---------------------------------------------------------------
108     // Success outcomes
109     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
110     public void createWithAuthRefs(String testName) throws Exception {
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         LoanoutClient loanoutClient = new LoanoutClient();
124         PoxPayloadOut multipart = createLoanoutInstance(
125                 "loanOutNumber-" + identifier,
126                 CURRENT_DATE_UTC,
127                 borrowerRefName,
128                 borrowersContactRefName,
129                 lendersAuthorizerRefName,
130                 lendersContactRefName);
131         String newId = null;
132         Response res = loanoutClient.create(multipart);
133         try {
134                 int statusCode = res.getStatus();
135         
136                 // Check the status code of the response: does it match
137                 // the expected response(s)?
138                 //
139                 // Specifically:
140                 // Does it fall within the set of valid status codes?
141                 // Does it exactly match the expected status code?
142                 if(logger.isDebugEnabled()){
143                     logger.debug(testName + ": status = " + statusCode);
144                 }
145                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
146                         invalidStatusCodeMessage(testRequestType, statusCode));
147                 Assert.assertEquals(statusCode, testExpectedStatusCode);
148                 newId = extractId(res);
149                 Assert.assertNotNull(newId, "Could not create a new LoanOut record.");
150         } finally {
151                 res.close();
152         }
153
154         // Store the ID returned from the first resource created
155         // for additional tests below.
156         if (knownResourceId == null){
157             knownResourceId = newId;
158             if (logger.isDebugEnabled()) {
159                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
160             }
161         }
162         
163         // Store the IDs from every resource created by tests,
164         // so they can be deleted after tests have been run.
165         loanoutIdsCreated.add(newId);
166     }
167
168     protected void createPersonRefs() throws Exception{
169
170         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
171         // Create a temporary PersonAuthority resource, and its corresponding
172         // refName by which it can be identified.
173         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
174             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
175         Response res = personAuthClient.create(multipart);
176         try {
177                 int statusCode = res.getStatus();
178                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
179                     invalidStatusCodeMessage(testRequestType, statusCode));
180                 Assert.assertEquals(statusCode, STATUS_CREATED);
181                 personAuthCSID = extractId(res);
182         } finally {
183                 res.close();
184         }
185         
186         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
187
188         // Create temporary Person resources, and their corresponding refNames
189         // by which they can be identified.
190
191         String csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
192         personIdsCreated.add(csid);
193         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
194
195         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
196         personIdsCreated.add(csid);
197         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
198
199         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
200         personIdsCreated.add(csid);
201         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
202
203         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
204         personIdsCreated.add(csid);
205         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
206     }
207     
208     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
209         String result = null;
210         
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 + random.nextInt(1000)); // avoid short ID conflicts with pass test session records that never got cleaned up
216         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
217         PersonTermGroup term = new PersonTermGroup();
218         String termName = firstName + " " + surName;
219         term.setTermDisplayName(termName);
220         term.setTermName(termName);
221         personTerms.add(term);
222         PoxPayloadOut multipart =
223                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
224                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
225         Response res = personAuthClient.createItem(personAuthCSID, multipart);
226         try {
227                 int statusCode = res.getStatus();
228         
229                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
230                         invalidStatusCodeMessage(testRequestType, statusCode));
231                 Assert.assertEquals(statusCode, STATUS_CREATED);
232                 result = extractId(res);
233         } finally {
234                 res.close();
235         }
236         
237         return result; 
238     }
239
240     // Success outcomes
241     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
242         dependsOnMethods = {"createWithAuthRefs"})
243     public void readAndCheckAuthRefs(String testName) throws Exception {
244         // Perform setup.
245         testSetup(STATUS_OK, ServiceRequestType.READ);
246
247         // Submit the request to the service and store the response.
248         LoanoutClient loanoutClient = new LoanoutClient();
249         Response res = loanoutClient.read(knownResourceId);
250         LoansoutCommon loanoutCommon = null;
251         try {
252                 assertStatusCode(res, testName);
253                 // Extract the common part from the response.
254                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
255                 loanoutCommon = (LoansoutCommon) extractPart(input,
256                     loanoutClient.getCommonPartName(), LoansoutCommon.class);
257                 Assert.assertNotNull(loanoutCommon);
258                 if(logger.isDebugEnabled()){
259                     logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
260                 }
261         } finally {
262                 if (res != null) {
263                 res.close();
264             }
265         }
266         
267         // Check a couple of fields
268         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
269         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
270         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
271         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
272         
273         // Get the auth refs and check them
274         Response res2 = loanoutClient.getAuthorityRefs(knownResourceId);
275         AuthorityRefList list = null;
276         try {
277                 assertStatusCode(res2, testName);
278                 list = res2.readEntity(AuthorityRefList.class);
279         } finally {
280                 if (res2 != null) {
281                         res2.close();
282             }
283         }
284
285         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
286         int numAuthRefsFound = items.size();
287         if(logger.isDebugEnabled()){
288             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
289                 " authority references, found " + numAuthRefsFound);
290         }
291         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
292             "Did not find all expected authority references! " +
293             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
294             
295         // Optionally output additional data about list members for debugging.
296         boolean iterateThroughList = true;
297         if(iterateThroughList && logger.isDebugEnabled()){
298             int i = 0;
299             for(AuthorityRefList.AuthorityRefItem item : items){
300                 logger.debug(testName + ": list-item[" + i + "] Field:" +
301                                 item.getSourceField() + "= " +
302                         item.getAuthDisplayName() +
303                         item.getItemDisplayName());
304                 logger.debug(testName + ": list-item[" + i + "] refName=" +
305                         item.getRefName());
306                 logger.debug(testName + ": list-item[" + i + "] URI=" +
307                         item.getUri());
308                 i++;
309             }
310         }
311     }
312
313
314     // ---------------------------------------------------------------
315     // Cleanup of resources created during testing
316     // ---------------------------------------------------------------
317
318     /**
319      * Deletes all resources created by tests, after all tests have been run.
320      *
321      * This cleanup method will always be run, even if one or more tests fail.
322      * For this reason, it attempts to remove all resources created
323      * at any point during testing, even if some of those resources
324      * may be expected to be deleted by certain tests.
325      * @throws Exception 
326      */
327     @AfterClass(alwaysRun=true)
328     public void cleanUp() throws Exception {
329         String noTest = System.getProperty("noTestCleanup");
330         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
331             if (logger.isDebugEnabled()) {
332                 logger.debug("Skipping Cleanup phase ...");
333             }
334             return;
335         }
336         if (logger.isDebugEnabled()) {
337             logger.debug("Cleaning up temporary resources created for testing ...");
338         }
339         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
340         // Delete Person resource(s) (before PersonAuthority resources).
341         for (String resourceId : personIdsCreated) {
342             // Note: Any non-success responses are ignored and not reported.
343             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
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).close();
349                 // Delete Loans In resource(s).
350                 LoanoutClient loanoutClient = new LoanoutClient();
351                 for (String resourceId : loanoutIdsCreated) {
352                     // Note: Any non-success responses are ignored and not reported.
353                     loanoutClient.delete(resourceId).close();
354                 }
355         }
356     }
357
358     // ---------------------------------------------------------------
359     // Utility methods used by tests above
360     // ---------------------------------------------------------------
361     public String getServiceName() {
362         return SERVICE_NAME;
363     }
364
365     @Override
366     public String getServicePathComponent() {
367         return SERVICE_PATH_COMPONENT;
368     }
369
370     private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
371                 String returnDate,
372                 String borrower,
373                 String borrowersContact,
374                 String lendersAuthorizer,
375                 String lendersContact) throws Exception {
376         LoansoutCommon loanoutCommon = new LoansoutCommon();
377         loanoutCommon.setLoanOutNumber(loanoutNumber);
378         loanoutCommon.setLoanReturnDate(returnDate);
379         loanoutCommon.setBorrower(borrower);
380         loanoutCommon.setBorrowersContact(borrowersContact);
381         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
382         loanoutCommon.setLendersContact(lendersContact);
383
384         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
385         PayloadOutputPart commonPart =
386                         multipart.addPart(new LoanoutClient().getCommonPartName(), loanoutCommon);
387
388         if(logger.isDebugEnabled()){
389                 logger.debug("to be created, loanout common");
390                 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
391         }
392
393         return multipart;
394     }
395
396     @Override
397     protected Class<AbstractCommonList> getCommonListType() {
398         // TODO Auto-generated method stub
399         return null;
400     }
401 }