]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9837fe0a1f677375cdcad359dba1a883b0cc13fb
[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(
99                         ClientResponse<AbstractCommonList> 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         ClientResponse<Response> response = loaninClient.create(multipart);
131         int statusCode = response.getStatus();
132         try {
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(response);
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                 loaninIdsCreated.add(extractId(response));
158         } finally {
159                 response.releaseConnection();
160         }
161     }
162     
163     protected void createPersonRefs(){
164
165         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
166         // Create a temporary PersonAuthority resource, and its corresponding
167         // refName by which it can be identified.
168         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
169             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
170         ClientResponse<Response> res = personAuthClient.create(multipart);
171         int statusCode = res.getStatus();
172
173         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
174             invalidStatusCodeMessage(testRequestType, statusCode));
175         Assert.assertEquals(statusCode, STATUS_CREATED);
176         personAuthCSID = extractId(res);
177
178         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
179         
180         // Create temporary Person resources, and their corresponding refNames
181         // by which they can be identified.
182         String csid = createPerson("Linus", "Lender", "linusLender", authRefName);
183         personIdsCreated.add(csid);
184         lenderRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
185
186         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
187         personIdsCreated.add(csid);
188         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
189
190         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
191         personIdsCreated.add(csid);
192         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
193         
194         csid = createPerson("Carrie", "Borrowerscontact", "carrieBorrowerscontact", authRefName);
195         personIdsCreated.add(csid);
196         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
197
198         csid = createPerson("Bonnie", "Borrowersauthorizer", "bonnieBorrowersauthorizer", authRefName);
199         personIdsCreated.add(csid);
200         borrowersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
201
202         // FIXME: Add instance(s) of 'lenders' field when we can work with
203         // repeatable / multivalued authority reference fields.  Be sure to
204     }
205     
206     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
207         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
208         Map<String, String> personInfo = new HashMap<String,String>();
209         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
210         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
211         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
212         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
213         PersonTermGroup term = new PersonTermGroup();
214         String termName = firstName + " " + surName;
215         term.setTermDisplayName(termName);
216         term.setTermName(termName);
217         personTerms.add(term);
218         PoxPayloadOut multipart =
219                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
220                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
221         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
222         int statusCode = res.getStatus();
223
224         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
225                 invalidStatusCodeMessage(testRequestType, statusCode));
226         Assert.assertEquals(statusCode, STATUS_CREATED);
227         return extractId(res);
228     }
229
230     // Success outcomes
231     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
232         dependsOnMethods = {"createWithAuthRefs"})
233     public void readAndCheckAuthRefs(String testName) throws Exception {
234         // Perform setup.
235         testSetup(STATUS_OK, ServiceRequestType.READ);
236
237         // Submit the request to the service and store the response.
238         LoaninClient loaninClient = new LoaninClient();
239         ClientResponse<String> res = loaninClient.read(knownResourceId);
240         LoansinCommon loaninCommon = null;
241         try {
242                 assertStatusCode(res, testName);
243                 // Extract the common part from the response.
244                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
245                 loaninCommon = (LoansinCommon) extractPart(input,
246                     loaninClient.getCommonPartName(), LoansinCommon.class);
247                 Assert.assertNotNull(loaninCommon);
248                 if(logger.isDebugEnabled()){
249                     logger.debug(objectAsXmlString(loaninCommon, LoansinCommon.class));
250                 }
251         } finally {
252                 if (res != null) {
253                 res.releaseConnection();
254             }
255         }
256         //
257         // Check a couple of fields
258         // Assert.assertEquals(loaninCommon.getLender(), lenderRefName);
259         // Assert.assertEquals(loaninCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
260         // Assert.assertEquals(loaninCommon.getLendersContact(), lendersContactRefName);
261         //
262         Assert.assertEquals(loaninCommon.getBorrowersContact(), borrowersContactRefName);
263         Assert.assertEquals(loaninCommon.getBorrowersAuthorizer(), borrowersAuthorizerRefName);
264         
265         // Get the auth refs and check them
266         ClientResponse<AuthorityRefList> res2 = loaninClient.getAuthorityRefs(knownResourceId);
267         AuthorityRefList list = null;
268         try {
269                 assertStatusCode(res2, testName);
270                 list = res2.getEntity();
271                 Assert.assertNotNull(list);
272         } finally {
273                 if (res2 != null) {
274                         res2.releaseConnection();
275             }
276         }
277         
278         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
279         int numAuthRefsFound = items.size();
280         if(logger.isDebugEnabled()){
281             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
282                 " authority references, found " + numAuthRefsFound);
283         }
284
285         // Optionally output additional data about list members for debugging.
286         boolean iterateThroughList = true;
287         if(iterateThroughList && logger.isDebugEnabled()){
288             int i = 0;
289             for(AuthorityRefList.AuthorityRefItem item : items){
290                 logger.debug(testName + ": list-item[" + i + "] Field:" +
291                                 item.getSourceField() + "= " +
292                         item.getAuthDisplayName() +
293                         item.getItemDisplayName());
294                 logger.debug(testName + ": list-item[" + i + "] refName=" +
295                         item.getRefName());
296                 logger.debug(testName + ": list-item[" + i + "] URI=" +
297                         item.getUri());
298                 i++;
299             }
300         }
301
302         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
303             "Did not find all expected authority references! " +
304             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
305
306     }
307
308
309     // ---------------------------------------------------------------
310     // Cleanup of resources created during testing
311     // ---------------------------------------------------------------
312
313     /**
314      * Deletes all resources created by tests, after all tests have been run.
315      *
316      * This cleanup method will always be run, even if one or more tests fail.
317      * For this reason, it attempts to remove all resources created
318      * at any point during testing, even if some of those resources
319      * may be expected to be deleted by certain tests.
320      */
321     @AfterClass(alwaysRun=true)
322     public void cleanUp() {
323         String noTest = System.getProperty("noTestCleanup");
324         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
325             if (logger.isDebugEnabled()) {
326                 logger.debug("Skipping Cleanup phase ...");
327             }
328             return;
329         }
330         if (logger.isDebugEnabled()) {
331             logger.debug("Cleaning up temporary resources created for testing ...");
332         }
333         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
334         // Delete Person resource(s) (before PersonAuthority resources).
335         
336         for (String resourceId : personIdsCreated) {
337             // Note: Any non-success responses are ignored and not reported.
338                 ClientResponse<Response> response = 
339                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
340                 response.releaseConnection();
341         }
342         
343         // Delete PersonAuthority resource(s).
344         // Note: Any non-success response is ignored and not reported.
345         if (personAuthCSID != null) {
346                 personAuthClient.delete(personAuthCSID);
347                 // Delete Loans In resource(s).
348                 LoaninClient loaninClient = new LoaninClient();
349                 ClientResponse<Response> response = null;
350                 for (String resourceId : loaninIdsCreated) {
351                     // Note: Any non-success responses are ignored and not reported.
352                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
353                     response.releaseConnection();
354                 }
355         }
356     }
357
358     // ---------------------------------------------------------------
359     // Utility methods used by tests above
360     // ---------------------------------------------------------------
361     public String getServiceName() {
362         return SERVICE_NAME;
363     }
364
365     @Override
366     public String getServicePathComponent() {
367         return SERVICE_PATH_COMPONENT;
368     }
369
370     private PoxPayloadOut createLoaninInstance(String loaninNumber,
371                 String returnDate,
372                 String lender,
373                 String lendersAuthorizer,
374                 String lendersContact,
375                 String borrowersContact,
376                 String borrowersAuthorizer) {
377         LoansinCommon loaninCommon = new LoansinCommon();
378         loaninCommon.setLoanInNumber(loaninNumber);
379         loaninCommon.setLoanInNumber(returnDate);
380         LenderGroupList lenderGroupList =  new LenderGroupList();
381         LenderGroup lenderGroup = new LenderGroup();
382         lenderGroup.setLender(lender);
383         lenderGroup.setLendersAuthorizer(lendersAuthorizer);
384         lenderGroup.setLendersContact(lendersContact);
385         lenderGroupList.getLenderGroup().add(lenderGroup);
386         loaninCommon.setLenderGroupList(lenderGroupList);
387         loaninCommon.setBorrowersContact(borrowersContact);
388         loaninCommon.setBorrowersAuthorizer(borrowersAuthorizer);
389
390         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
391         PayloadOutputPart commonPart =
392                         multipart.addPart(new LoaninClient().getCommonPartName(), loaninCommon);
393
394         if(logger.isDebugEnabled()){
395                 logger.debug("to be created, loanin common");
396                 logger.debug(objectAsXmlString(loaninCommon, LoansinCommon.class));
397         }
398
399         return multipart;
400     }
401
402     @Override
403     protected Class<AbstractCommonList> getCommonListType() {
404         return AbstractCommonList.class;
405     }
406 }