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