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