]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b0be8b37a4a55d216995b3c017cad2eb90b988d5
[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
46 import org.testng.Assert;
47 import org.testng.annotations.AfterClass;
48 import org.testng.annotations.Test;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * LoanoutAuthRefsTest, carries out Authority References tests against a
54  * deployed and running Loanout (aka Loans Out) Service.
55  *
56  * $LastChangedRevision$
57  * $LastChangedDate$
58  */
59 public class LoanoutAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
60
61     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
62     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
63
64     // Instance variables specific to this test.
65     final String SERVICE_NAME = "loansout";
66     final String SERVICE_PATH_COMPONENT = "loansout";
67     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
68     private String knownResourceId = null;
69     private List<String> loanoutIdsCreated = new ArrayList<String>();
70     private List<String> personIdsCreated = new ArrayList<String>();
71     private String personAuthCSID = null;
72     private String borrowerRefName = null;
73     private String borrowersContactRefName = null;
74     private String lendersAuthorizerRefName = null;
75     private String lendersContactRefName = null;
76
77     // FIXME: Can add 'borrower' - likely to be an organization
78     // authority - as an authRef to tests below, and increase the
79     // number of expected authRefs to 4.
80     private final int NUM_AUTH_REFS_EXPECTED = 4;
81     
82     private final static String CURRENT_DATE_UTC =
83             GregorianCalendarDateTimeUtils.currentDateUTC();
84
85     /* (non-Javadoc)
86      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
87      */
88     @Override
89     protected CollectionSpaceClient getClientInstance() {
90         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
91     }
92
93     @Override
94         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
95         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
96         }
97     
98     /* (non-Javadoc)
99      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
100      */
101     @Override
102         protected AbstractCommonList getCommonList(Response response) {
103         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
104     }
105
106     // ---------------------------------------------------------------
107     // CRUD tests : CREATE tests
108     // ---------------------------------------------------------------
109     // Success outcomes
110     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
111     public void createWithAuthRefs(String testName) throws Exception {
112         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
113
114         // Submit the request to the service and store the response.
115         String identifier = createIdentifier();
116
117         // Create all the person refs and entities
118         createPersonRefs();
119
120         // Create a new Loans In resource.
121         //
122         // One or more fields in this resource will be PersonAuthority
123         // references, and will refer to Person resources by their refNames.
124         LoanoutClient loanoutClient = new LoanoutClient();
125         PoxPayloadOut multipart = createLoanoutInstance(
126                 "loanOutNumber-" + identifier,
127                 CURRENT_DATE_UTC,
128                 borrowerRefName,
129                 borrowersContactRefName,
130                 lendersAuthorizerRefName,
131                 lendersContactRefName);
132         String newId = null;
133         Response res = loanoutClient.create(multipart);
134         try {
135                 int statusCode = res.getStatus();
136         
137                 // Check the status code of the response: does it match
138                 // the expected response(s)?
139                 //
140                 // Specifically:
141                 // Does it fall within the set of valid status codes?
142                 // Does it exactly match the expected status code?
143                 if(logger.isDebugEnabled()){
144                     logger.debug(testName + ": status = " + statusCode);
145                 }
146                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
147                         invalidStatusCodeMessage(testRequestType, statusCode));
148                 Assert.assertEquals(statusCode, testExpectedStatusCode);
149                 newId = extractId(res);
150                 Assert.assertNotNull(newId, "Could not create a new LoanOut record.");
151         } finally {
152                 res.close();
153         }
154
155         // Store the ID returned from the first resource created
156         // for additional tests below.
157         if (knownResourceId == null){
158             knownResourceId = newId;
159             if (logger.isDebugEnabled()) {
160                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
161             }
162         }
163         
164         // Store the IDs from every resource created by tests,
165         // so they can be deleted after tests have been run.
166         loanoutIdsCreated.add(newId);
167     }
168
169     protected void createPersonRefs(){
170
171         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
172         // Create a temporary PersonAuthority resource, and its corresponding
173         // refName by which it can be identified.
174         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
175             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
176         Response res = personAuthClient.create(multipart);
177         try {
178                 int statusCode = res.getStatus();
179                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
180                     invalidStatusCodeMessage(testRequestType, statusCode));
181                 Assert.assertEquals(statusCode, STATUS_CREATED);
182                 personAuthCSID = extractId(res);
183         } finally {
184                 res.close();
185         }
186         
187         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
188
189         // Create temporary Person resources, and their corresponding refNames
190         // by which they can be identified.
191
192         String csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
193         personIdsCreated.add(csid);
194         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
195
196         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
197         personIdsCreated.add(csid);
198         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
199
200         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
201         personIdsCreated.add(csid);
202         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
203
204         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
205         personIdsCreated.add(csid);
206         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
207     }
208     
209     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
210         String result = null;
211         
212         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
213         Map<String, String> personInfo = new HashMap<String,String>();
214         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
215         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
216         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
217         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
218         PersonTermGroup term = new PersonTermGroup();
219         String termName = firstName + " " + surName;
220         term.setTermDisplayName(termName);
221         term.setTermName(termName);
222         personTerms.add(term);
223         PoxPayloadOut multipart =
224                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
225                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
226         Response res = personAuthClient.createItem(personAuthCSID, multipart);
227         try {
228                 int statusCode = res.getStatus();
229         
230                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
231                         invalidStatusCodeMessage(testRequestType, statusCode));
232                 Assert.assertEquals(statusCode, STATUS_CREATED);
233                 result = extractId(res);
234         } finally {
235                 res.close();
236         }
237         
238         return result; 
239     }
240
241     // Success outcomes
242     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
243         dependsOnMethods = {"createWithAuthRefs"})
244     public void readAndCheckAuthRefs(String testName) throws Exception {
245         // Perform setup.
246         testSetup(STATUS_OK, ServiceRequestType.READ);
247
248         // Submit the request to the service and store the response.
249         LoanoutClient loanoutClient = new LoanoutClient();
250         Response res = loanoutClient.read(knownResourceId);
251         LoansoutCommon loanoutCommon = null;
252         try {
253                 assertStatusCode(res, testName);
254                 // Extract the common part from the response.
255                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
256                 loanoutCommon = (LoansoutCommon) extractPart(input,
257                     loanoutClient.getCommonPartName(), LoansoutCommon.class);
258                 Assert.assertNotNull(loanoutCommon);
259                 if(logger.isDebugEnabled()){
260                     logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
261                 }
262         } finally {
263                 if (res != null) {
264                 res.close();
265             }
266         }
267         
268         // Check a couple of fields
269         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
270         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
271         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
272         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
273         
274         // Get the auth refs and check them
275         Response res2 = loanoutClient.getAuthorityRefs(knownResourceId);
276         AuthorityRefList list = null;
277         try {
278                 assertStatusCode(res2, testName);
279                 list = res2.readEntity(AuthorityRefList.class);
280         } finally {
281                 if (res2 != null) {
282                         res2.close();
283             }
284         }
285
286         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
287         int numAuthRefsFound = items.size();
288         if(logger.isDebugEnabled()){
289             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
290                 " authority references, found " + numAuthRefsFound);
291         }
292         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
293             "Did not find all expected authority references! " +
294             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
295             
296         // Optionally output additional data about list members for debugging.
297         boolean iterateThroughList = true;
298         if(iterateThroughList && logger.isDebugEnabled()){
299             int i = 0;
300             for(AuthorityRefList.AuthorityRefItem item : items){
301                 logger.debug(testName + ": list-item[" + i + "] Field:" +
302                                 item.getSourceField() + "= " +
303                         item.getAuthDisplayName() +
304                         item.getItemDisplayName());
305                 logger.debug(testName + ": list-item[" + i + "] refName=" +
306                         item.getRefName());
307                 logger.debug(testName + ": list-item[" + i + "] URI=" +
308                         item.getUri());
309                 i++;
310             }
311         }
312     }
313
314
315     // ---------------------------------------------------------------
316     // Cleanup of resources created during testing
317     // ---------------------------------------------------------------
318
319     /**
320      * Deletes all resources created by tests, after all tests have been run.
321      *
322      * This cleanup method will always be run, even if one or more tests fail.
323      * For this reason, it attempts to remove all resources created
324      * at any point during testing, even if some of those resources
325      * may be expected to be deleted by certain tests.
326      */
327     @AfterClass(alwaysRun=true)
328     public void cleanUp() {
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) {
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 }