]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
03e44064974c5d79a1875f86ec7c66b908d6ded4
[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(Response response) {
101         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
102     }
103
104     // ---------------------------------------------------------------
105     // CRUD tests : CREATE tests
106     // ---------------------------------------------------------------
107     // Success outcomes
108     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
109     public void createWithAuthRefs(String testName) throws Exception {
110         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
111
112         // Submit the request to the service and store the response.
113         String identifier = createIdentifier();
114
115         // Create all the person refs and entities
116         createPersonRefs();
117
118         // Create a new Loans In resource.
119         //
120         // One or more fields in this resource will be PersonAuthority
121         // references, and will refer to Person resources by their refNames.
122         LoanoutClient loanoutClient = new LoanoutClient();
123         PoxPayloadOut multipart = createLoanoutInstance(
124                 "loanOutNumber-" + identifier,
125                 CURRENT_DATE_UTC,
126                 borrowerRefName,
127                 borrowersContactRefName,
128                 lendersAuthorizerRefName,
129                 lendersContactRefName);
130         String newId = null;
131         Response res = loanoutClient.create(multipart);
132         try {
133                 int statusCode = res.getStatus();
134         
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(testRequestType.isValidStatusCode(statusCode),
145                         invalidStatusCodeMessage(testRequestType, statusCode));
146                 Assert.assertEquals(statusCode, testExpectedStatusCode);
147                 newId = extractId(res);
148         } finally {
149                 res.close();
150         }
151
152         // Store the ID returned from the first resource created
153         // for additional tests below.
154         if (knownResourceId == null){
155             knownResourceId = newId;
156             if (logger.isDebugEnabled()) {
157                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
158             }
159         }
160         
161         // Store the IDs from every resource created by tests,
162         // so they can be deleted after tests have been run.
163         loanoutIdsCreated.add(newId);
164     }
165
166     protected void createPersonRefs(){
167
168         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
169         // Create a temporary PersonAuthority resource, and its corresponding
170         // refName by which it can be identified.
171         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
172             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
173         Response res = personAuthClient.create(multipart);
174         try {
175                 int statusCode = res.getStatus();
176                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
177                     invalidStatusCodeMessage(testRequestType, statusCode));
178                 Assert.assertEquals(statusCode, STATUS_CREATED);
179                 personAuthCSID = extractId(res);
180         } finally {
181                 res.close();
182         }
183         
184         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
185
186         // Create temporary Person resources, and their corresponding refNames
187         // by which they can be identified.
188
189         String csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
190         personIdsCreated.add(csid);
191         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
192
193         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
194         personIdsCreated.add(csid);
195         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
196
197         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
198         personIdsCreated.add(csid);
199         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
200
201         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
202         personIdsCreated.add(csid);
203         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
204     }
205     
206     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
207         String result = null;
208         
209         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
210         Map<String, String> personInfo = new HashMap<String,String>();
211         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
212         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
213         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
214         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
215         PersonTermGroup term = new PersonTermGroup();
216         String termName = firstName + " " + surName;
217         term.setTermDisplayName(termName);
218         term.setTermName(termName);
219         personTerms.add(term);
220         PoxPayloadOut multipart =
221                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
222                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
223         Response res = personAuthClient.createItem(personAuthCSID, multipart);
224         try {
225                 int statusCode = res.getStatus();
226         
227                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
228                         invalidStatusCodeMessage(testRequestType, statusCode));
229                 Assert.assertEquals(statusCode, STATUS_CREATED);
230                 result = extractId(res);
231         } finally {
232                 res.close();
233         }
234         
235         return result; 
236     }
237
238     // Success outcomes
239     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
240         dependsOnMethods = {"createWithAuthRefs"})
241     public void readAndCheckAuthRefs(String testName) throws Exception {
242         // Perform setup.
243         testSetup(STATUS_OK, ServiceRequestType.READ);
244
245         // Submit the request to the service and store the response.
246         LoanoutClient loanoutClient = new LoanoutClient();
247         Response res = loanoutClient.read(knownResourceId);
248         LoansoutCommon loanoutCommon = null;
249         try {
250                 assertStatusCode(res, testName);
251                 // Extract the common part from the response.
252                 PoxPayloadIn input = new PoxPayloadIn((String)res.getEntity());
253                 loanoutCommon = (LoansoutCommon) extractPart(input,
254                     loanoutClient.getCommonPartName(), LoansoutCommon.class);
255                 Assert.assertNotNull(loanoutCommon);
256                 if(logger.isDebugEnabled()){
257                     logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
258                 }
259         } finally {
260                 if (res != null) {
261                 res.close();
262             }
263         }
264         
265         // Check a couple of fields
266         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
267         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
268         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
269         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
270         
271         // Get the auth refs and check them
272         Response res2 = loanoutClient.getAuthorityRefs(knownResourceId);
273         AuthorityRefList list = null;
274         try {
275                 assertStatusCode(res2, testName);
276                 list = (AuthorityRefList)res2.getEntity();
277         } finally {
278                 if (res2 != null) {
279                         res2.close();
280             }
281         }
282
283         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
284         int numAuthRefsFound = items.size();
285         if(logger.isDebugEnabled()){
286             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
287                 " authority references, found " + numAuthRefsFound);
288         }
289         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
290             "Did not find all expected authority references! " +
291             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
292             
293         // Optionally output additional data about list members for debugging.
294         boolean iterateThroughList = true;
295         if(iterateThroughList && logger.isDebugEnabled()){
296             int i = 0;
297             for(AuthorityRefList.AuthorityRefItem item : items){
298                 logger.debug(testName + ": list-item[" + i + "] Field:" +
299                                 item.getSourceField() + "= " +
300                         item.getAuthDisplayName() +
301                         item.getItemDisplayName());
302                 logger.debug(testName + ": list-item[" + i + "] refName=" +
303                         item.getRefName());
304                 logger.debug(testName + ": list-item[" + i + "] URI=" +
305                         item.getUri());
306                 i++;
307             }
308         }
309     }
310
311
312     // ---------------------------------------------------------------
313     // Cleanup of resources created during testing
314     // ---------------------------------------------------------------
315
316     /**
317      * Deletes all resources created by tests, after all tests have been run.
318      *
319      * This cleanup method will always be run, even if one or more tests fail.
320      * For this reason, it attempts to remove all resources created
321      * at any point during testing, even if some of those resources
322      * may be expected to be deleted by certain tests.
323      */
324     @AfterClass(alwaysRun=true)
325     public void cleanUp() {
326         String noTest = System.getProperty("noTestCleanup");
327         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
328             if (logger.isDebugEnabled()) {
329                 logger.debug("Skipping Cleanup phase ...");
330             }
331             return;
332         }
333         if (logger.isDebugEnabled()) {
334             logger.debug("Cleaning up temporary resources created for testing ...");
335         }
336         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
337         // Delete Person resource(s) (before PersonAuthority resources).
338         for (String resourceId : personIdsCreated) {
339             // Note: Any non-success responses are ignored and not reported.
340             personAuthClient.deleteItem(personAuthCSID, resourceId);
341         }
342         // Delete PersonAuthority resource(s).
343         // Note: Any non-success response is ignored and not reported.
344         if (personAuthCSID != null) {
345                 personAuthClient.delete(personAuthCSID);
346                 // Delete Loans In resource(s).
347                 LoanoutClient loanoutClient = new LoanoutClient();
348                 for (String resourceId : loanoutIdsCreated) {
349                     // Note: Any non-success responses are ignored and not reported.
350                     loanoutClient.delete(resourceId);
351                 }
352         }
353     }
354
355     // ---------------------------------------------------------------
356     // Utility methods used by tests above
357     // ---------------------------------------------------------------
358     public String getServiceName() {
359         return SERVICE_NAME;
360     }
361
362     @Override
363     public String getServicePathComponent() {
364         return SERVICE_PATH_COMPONENT;
365     }
366
367     private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
368                 String returnDate,
369                 String borrower,
370                 String borrowersContact,
371                 String lendersAuthorizer,
372                 String lendersContact) {
373         LoansoutCommon loanoutCommon = new LoansoutCommon();
374         loanoutCommon.setLoanOutNumber(loanoutNumber);
375         loanoutCommon.setLoanReturnDate(returnDate);
376         loanoutCommon.setBorrower(borrower);
377         loanoutCommon.setBorrowersContact(borrowersContact);
378         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
379         loanoutCommon.setLendersContact(lendersContact);
380
381         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
382         PayloadOutputPart commonPart =
383                         multipart.addPart(new LoanoutClient().getCommonPartName(), loanoutCommon);
384
385         if(logger.isDebugEnabled()){
386                 logger.debug("to be created, loanout common");
387                 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
388         }
389
390         return multipart;
391     }
392
393     @Override
394     protected Class<AbstractCommonList> getCommonListType() {
395         // TODO Auto-generated method stub
396         return null;
397     }
398 }