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