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