]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
df8e25ba607407001ea091f8df8a30f7c77f07db
[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 import org.testng.Assert;
48 import org.testng.annotations.AfterClass;
49 import org.testng.annotations.Test;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * LoaninAuthRefsTest, carries out Authority References tests against a
55  * deployed and running Loanin (aka Loans In) Service.
56  *
57  * $LastChangedRevision$
58  * $LastChangedDate$
59  */
60 public class LoaninAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
61
62     private final String CLASS_NAME = LoaninAuthRefsTest.class.getName();
63     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
64     
65     // Instance variables specific to this test.
66     final String SERVICE_NAME = "loansin";
67     final String SERVICE_PATH_COMPONENT = "loansin";
68     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
69     private String knownResourceId = null;
70     private List<String> loaninIdsCreated = new ArrayList<String>();
71     private List<String> personIdsCreated = new ArrayList<String>();
72     private String personAuthCSID = null;
73     private String lenderRefName = null;
74     private String lendersAuthorizerRefName = null;
75     private String lendersContactRefName = null;
76     private String borrowersContactRefName = null;
77     private String borrowersAuthorizerRefName = null;
78     private final int NUM_AUTH_REFS_EXPECTED = 5;
79     private final static String CURRENT_DATE_UTC =
80             GregorianCalendarDateTimeUtils.currentDateUTC();
81
82     /* (non-Javadoc)
83      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
84      */
85     @Override
86     protected CollectionSpaceClient getClientInstance() {
87         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
88     }
89
90         @Override
91         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
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(Response response) {
100         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
101     }
102
103     // ---------------------------------------------------------------
104     // CRUD tests : CREATE tests
105     // ---------------------------------------------------------------
106     // Success outcomes
107     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
108     public void createWithAuthRefs(String testName) throws Exception {
109         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
110
111         // Submit the request to the service and store the response.
112         String identifier = createIdentifier();
113         
114         // Create all the person refs and entities
115         createPersonRefs();
116
117         // Create a new Loans In resource.
118         //
119         // One or more fields in this resource will be PersonAuthority
120         // references, and will refer to Person resources by their refNames.
121         LoaninClient loaninClient = new LoaninClient();
122         PoxPayloadOut multipart = createLoaninInstance(
123                 "loanInNumber-" + identifier,
124                 CURRENT_DATE_UTC,
125                 lenderRefName,
126                 lendersAuthorizerRefName,
127                 lendersContactRefName,
128                 borrowersContactRefName,
129                 borrowersAuthorizerRefName);
130         String newId = null;
131         Response response = loaninClient.create(multipart);
132         try {
133             int statusCode = response.getStatus();
134                 // Check the status code of the response: does it match
135                 // the expected response(s)?
136                 //
137                 // Specifically:
138                 // Does it fall within the set of valid status codes?
139                 // Does it exactly match the expected status code?
140                 if(logger.isDebugEnabled()){
141                     logger.debug(testName + ": status = " + statusCode);
142                 }
143                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
144                         invalidStatusCodeMessage(testRequestType, statusCode));
145                 Assert.assertEquals(statusCode, testExpectedStatusCode);
146                 newId = extractId(response);
147         } finally {
148                 response.close();
149         }
150         
151         // Store the ID returned from the first resource created
152         // for additional tests below.
153         if (knownResourceId == null){
154             knownResourceId = newId;
155             if (logger.isDebugEnabled()) {
156                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
157             }
158         }
159         
160         // Store the IDs from every resource created by tests,
161         // so they can be deleted after tests have been run.
162         loaninIdsCreated.add(newId);
163     }
164     
165     protected void createPersonRefs() throws Exception{
166
167         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
168         // Create a temporary PersonAuthority resource, and its corresponding
169         // refName by which it can be identified.
170         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
171             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
172         Response res = personAuthClient.create(multipart);
173         try {
174                 int statusCode = res.getStatus();
175         
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         String csid = createPerson("Linus", "Lender", "linusLender", authRefName);
189         personIdsCreated.add(csid);
190         lenderRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
191
192         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
193         personIdsCreated.add(csid);
194         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
195
196         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
197         personIdsCreated.add(csid);
198         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
199         
200         csid = createPerson("Carrie", "Borrowerscontact", "carrieBorrowerscontact", authRefName);
201         personIdsCreated.add(csid);
202         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
203
204         csid = createPerson("Bonnie", "Borrowersauthorizer", "bonnieBorrowersauthorizer", authRefName);
205         personIdsCreated.add(csid);
206         borrowersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
207
208         // FIXME: Add instance(s) of 'lenders' field when we can work with
209         // repeatable / multivalued authority reference fields.  Be sure to
210     }
211     
212     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
213         String result = null;
214         
215         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
216         Map<String, String> personInfo = new HashMap<String,String>();
217         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
218         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
219         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
220         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
221         PersonTermGroup term = new PersonTermGroup();
222         String termName = firstName + " " + surName;
223         term.setTermDisplayName(termName);
224         term.setTermName(termName);
225         personTerms.add(term);
226         PoxPayloadOut multipart =
227                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
228                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
229         Response res = personAuthClient.createItem(personAuthCSID, multipart);
230         try {
231                 int statusCode = res.getStatus();
232         
233                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
234                         invalidStatusCodeMessage(testRequestType, statusCode));
235                 Assert.assertEquals(statusCode, STATUS_CREATED);
236                 result = extractId(res);
237         } finally {
238                 res.close();
239         }
240         
241         return result; 
242     }
243
244     // Success outcomes
245     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
246         dependsOnMethods = {"createWithAuthRefs"})
247     public void readAndCheckAuthRefs(String testName) throws Exception {
248         // Perform setup.
249         testSetup(STATUS_OK, ServiceRequestType.READ);
250
251         // Submit the request to the service and store the response.
252         LoaninClient loaninClient = new LoaninClient();
253         Response res = loaninClient.read(knownResourceId);
254         LoansinCommon loaninCommon = null;
255         try {
256                 assertStatusCode(res, testName);
257                 // Extract the common part from the response.
258                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
259                 loaninCommon = (LoansinCommon) extractPart(input,
260                     loaninClient.getCommonPartName(), LoansinCommon.class);
261                 Assert.assertNotNull(loaninCommon);
262                 if(logger.isDebugEnabled()){
263                     logger.debug(objectAsXmlString(loaninCommon, LoansinCommon.class));
264                 }
265         } finally {
266                 if (res != null) {
267                 res.close();
268             }
269         }
270         //
271         // Check a couple of fields
272         // Assert.assertEquals(loaninCommon.getLender(), lenderRefName);
273         // Assert.assertEquals(loaninCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
274         // Assert.assertEquals(loaninCommon.getLendersContact(), lendersContactRefName);
275         //
276         Assert.assertEquals(loaninCommon.getBorrowersContact(), borrowersContactRefName);
277         Assert.assertEquals(loaninCommon.getBorrowersAuthorizer(), borrowersAuthorizerRefName);
278         
279         // Get the auth refs and check them
280         Response res2 = loaninClient.getAuthorityRefs(knownResourceId);
281         AuthorityRefList list = null;
282         try {
283                 assertStatusCode(res2, testName);
284                 list = res2.readEntity(AuthorityRefList.class);
285                 Assert.assertNotNull(list);
286         } finally {
287                 if (res2 != null) {
288                         res2.close();
289             }
290         }
291         
292         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
293         int numAuthRefsFound = items.size();
294         if(logger.isDebugEnabled()){
295             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
296                 " authority references, found " + numAuthRefsFound);
297         }
298
299         // Optionally output additional data about list members for debugging.
300         boolean iterateThroughList = true;
301         if(iterateThroughList && logger.isDebugEnabled()){
302             int i = 0;
303             for(AuthorityRefList.AuthorityRefItem item : items){
304                 logger.debug(testName + ": list-item[" + i + "] Field:" +
305                                 item.getSourceField() + "= " +
306                         item.getAuthDisplayName() +
307                         item.getItemDisplayName());
308                 logger.debug(testName + ": list-item[" + i + "] refName=" +
309                         item.getRefName());
310                 logger.debug(testName + ": list-item[" + i + "] URI=" +
311                         item.getUri());
312                 i++;
313             }
314         }
315
316         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
317             "Did not find all expected authority references! " +
318             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
319
320     }
321
322
323     // ---------------------------------------------------------------
324     // Cleanup of resources created during testing
325     // ---------------------------------------------------------------
326
327     /**
328      * Deletes all resources created by tests, after all tests have been run.
329      *
330      * This cleanup method will always be run, even if one or more tests fail.
331      * For this reason, it attempts to remove all resources created
332      * at any point during testing, even if some of those resources
333      * may be expected to be deleted by certain tests.
334      * @throws Exception 
335      */
336     @AfterClass(alwaysRun=true)
337     public void cleanUp() throws Exception {
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) throws Exception {
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 }