]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e22dbf32342f7596c883c29a30ab83dfd324d16d
[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.MediaType;
31 import javax.ws.rs.core.Response;
32
33 import org.collectionspace.services.PersonJAXBSchema;
34 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
35 import org.collectionspace.services.client.CollectionSpaceClient;
36 import org.collectionspace.services.client.LoaninClient;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
39 import org.collectionspace.services.client.PayloadInputPart;
40 import org.collectionspace.services.client.PayloadOutputPart;
41 import org.collectionspace.services.client.PoxPayloadIn;
42 import org.collectionspace.services.client.PoxPayloadOut;
43 import org.collectionspace.services.common.authorityref.AuthorityRefList;
44 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
45 import org.collectionspace.services.jaxb.AbstractCommonList;
46 import org.collectionspace.services.loanin.LenderGroup;
47 import org.collectionspace.services.loanin.LenderGroupList;
48 import org.collectionspace.services.loanin.LoansinCommon;
49
50 import org.jboss.resteasy.client.ClientResponse;
51
52 import org.testng.Assert;
53 import org.testng.annotations.AfterClass;
54 import org.testng.annotations.Test;
55
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * LoaninAuthRefsTest, carries out Authority References tests against a
61  * deployed and running Loanin (aka Loans In) Service.
62  *
63  * $LastChangedRevision$
64  * $LastChangedDate$
65  */
66 public class LoaninAuthRefsTest extends BaseServiceTest {
67
68     private final String CLASS_NAME = LoaninAuthRefsTest.class.getName();
69     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
70     
71     // Instance variables specific to this test.
72     final String SERVICE_NAME = "loansin";
73     final String SERVICE_PATH_COMPONENT = "loansin";
74     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
75     private String knownResourceId = null;
76     private List<String> loaninIdsCreated = new ArrayList<String>();
77     private List<String> personIdsCreated = new ArrayList<String>();
78     private String personAuthCSID = null;
79     private String lenderRefName = null;
80     private String lendersAuthorizerRefName = null;
81     private String lendersContactRefName = null;
82     private String loanInContactRefName = null;
83     private String borrowersAuthorizerRefName = null;
84     private final int NUM_AUTH_REFS_EXPECTED = 5;
85     private final static String CURRENT_DATE_UTC =
86             GregorianCalendarDateTimeUtils.currentDateUTC();
87
88     /* (non-Javadoc)
89      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
90      */
91     @Override
92     protected CollectionSpaceClient getClientInstance() {
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 getAbstractCommonList(
101                         ClientResponse<AbstractCommonList> response) {
102         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
103     }
104
105     // ---------------------------------------------------------------
106     // CRUD tests : CREATE tests
107     // ---------------------------------------------------------------
108     // Success outcomes
109     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
110     public void createWithAuthRefs(String testName) throws Exception {
111
112         if (logger.isDebugEnabled()) {
113             logger.debug(testBanner(testName, CLASS_NAME));
114         }
115         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
116
117         // Submit the request to the service and store the response.
118         String identifier = createIdentifier();
119         
120         // Create all the person refs and entities
121         createPersonRefs();
122
123         // Create a new Loans In resource.
124         //
125         // One or more fields in this resource will be PersonAuthority
126         // references, and will refer to Person resources by their refNames.
127         LoaninClient loaninClient = new LoaninClient();
128         PoxPayloadOut multipart = createLoaninInstance(
129                 "loanInNumber-" + identifier,
130                 CURRENT_DATE_UTC,
131                 lenderRefName,
132                 lendersAuthorizerRefName,
133                 lendersContactRefName,
134                 loanInContactRefName,
135                 borrowersAuthorizerRefName);
136         ClientResponse<Response> response = loaninClient.create(multipart);
137         int statusCode = response.getStatus();
138         try {
139                 // Check the status code of the response: does it match
140                 // the expected response(s)?
141                 //
142                 // Specifically:
143                 // Does it fall within the set of valid status codes?
144                 // Does it exactly match the expected status code?
145                 if(logger.isDebugEnabled()){
146                     logger.debug(testName + ": status = " + statusCode);
147                 }
148                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
149                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
150                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
151         
152                 // Store the ID returned from the first resource created
153                 // for additional tests below.
154                 if (knownResourceId == null){
155                     knownResourceId = extractId(response);
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(extractId(response));
164         } finally {
165                 response.releaseConnection();
166         }
167     }
168     
169     protected void createPersonRefs(){
170
171         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
172         // Create a temporary PersonAuthority resource, and its corresponding
173         // refName by which it can be identified.
174         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
175             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
176         ClientResponse<Response> res = personAuthClient.create(multipart);
177         int statusCode = res.getStatus();
178
179         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
180             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
181         Assert.assertEquals(statusCode, STATUS_CREATED);
182         personAuthCSID = extractId(res);
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", "Loanincontact", "carrieLoanincontact", authRefName);
201         personIdsCreated.add(csid);
202         loanInContactRefName = 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 ) {
213         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
214         Map<String, String> personInfo = new HashMap<String,String>();
215         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
216         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
217         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
218         PoxPayloadOut multipart =
219                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
220                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
221         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
222         int statusCode = res.getStatus();
223
224         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
225                 invalidStatusCodeMessage(REQUEST_TYPE, 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
235         if (logger.isDebugEnabled()) {
236             logger.debug(testBanner(testName, CLASS_NAME));
237         }
238         // Perform setup.
239         testSetup(STATUS_OK, ServiceRequestType.READ);
240
241         // Submit the request to the service and store the response.
242         LoaninClient loaninClient = new LoaninClient();
243         ClientResponse<String> res = loaninClient.read(knownResourceId);
244         int statusCode = res.getStatus();
245
246         // Check the status code of the response: does it match
247         // the expected response(s)?
248         if(logger.isDebugEnabled()){
249             logger.debug(testName + ".read: status = " + statusCode);
250         }
251         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
252             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
253         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
254
255         // Extract the common part from the response.
256         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
257         LoansinCommon loaninCommon = (LoansinCommon) extractPart(input,
258             loaninClient.getCommonPartName(), LoansinCommon.class);
259         Assert.assertNotNull(loaninCommon);
260         if(logger.isDebugEnabled()){
261             logger.debug(objectAsXmlString(loaninCommon, LoansinCommon.class));
262         }
263
264         // Check a couple of fields
265         // Assert.assertEquals(loaninCommon.getLender(), lenderRefName);
266         // Assert.assertEquals(loaninCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
267         // Assert.assertEquals(loaninCommon.getLendersContact(), lendersContactRefName);
268         Assert.assertEquals(loaninCommon.getLoanInContact(), loanInContactRefName);
269         Assert.assertEquals(loaninCommon.getBorrowersAuthorizer(), borrowersAuthorizerRefName);
270         
271         // Get the auth refs and check them
272         ClientResponse<AuthorityRefList> res2 =
273            loaninClient.getAuthorityRefs(knownResourceId);
274         statusCode = res2.getStatus();
275
276         if(logger.isDebugEnabled()){
277             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
278         }
279         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
280                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
281         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
282         AuthorityRefList list = res2.getEntity();
283         
284         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
285         int numAuthRefsFound = items.size();
286         if(logger.isDebugEnabled()){
287             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
288                 " authority references, found " + numAuthRefsFound);
289         }
290
291         // Optionally output additional data about list members for debugging.
292         boolean iterateThroughList = true;
293         if(iterateThroughList && logger.isDebugEnabled()){
294             int i = 0;
295             for(AuthorityRefList.AuthorityRefItem item : items){
296                 logger.debug(testName + ": list-item[" + i + "] Field:" +
297                                 item.getSourceField() + "= " +
298                         item.getAuthDisplayName() +
299                         item.getItemDisplayName());
300                 logger.debug(testName + ": list-item[" + i + "] refName=" +
301                         item.getRefName());
302                 logger.debug(testName + ": list-item[" + i + "] URI=" +
303                         item.getUri());
304                 i++;
305             }
306         }
307
308         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
309             "Did not find all expected authority references! " +
310             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
311
312     }
313
314
315     // ---------------------------------------------------------------
316     // Cleanup of resources created during testing
317     // ---------------------------------------------------------------
318
319     /**
320      * Deletes all resources created by tests, after all tests have been run.
321      *
322      * This cleanup method will always be run, even if one or more tests fail.
323      * For this reason, it attempts to remove all resources created
324      * at any point during testing, even if some of those resources
325      * may be expected to be deleted by certain tests.
326      */
327     @AfterClass(alwaysRun=true)
328     public void cleanUp() {
329         String noTest = System.getProperty("noTestCleanup");
330         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
331             if (logger.isDebugEnabled()) {
332                 logger.debug("Skipping Cleanup phase ...");
333             }
334             return;
335         }
336         if (logger.isDebugEnabled()) {
337             logger.debug("Cleaning up temporary resources created for testing ...");
338         }
339         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
340         // Delete Person resource(s) (before PersonAuthority resources).
341         
342         for (String resourceId : personIdsCreated) {
343             // Note: Any non-success responses are ignored and not reported.
344                 ClientResponse<Response> response = 
345                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
346                 response.releaseConnection();
347         }
348         
349         // Delete PersonAuthority resource(s).
350         // Note: Any non-success response is ignored and not reported.
351         if (personAuthCSID != null) {
352                 personAuthClient.delete(personAuthCSID);
353                 // Delete Loans In resource(s).
354                 LoaninClient loaninClient = new LoaninClient();
355                 ClientResponse<Response> response = null;
356                 for (String resourceId : loaninIdsCreated) {
357                     // Note: Any non-success responses are ignored and not reported.
358                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
359                     response.releaseConnection();
360                 }
361         }
362     }
363
364     // ---------------------------------------------------------------
365     // Utility methods used by tests above
366     // ---------------------------------------------------------------
367     public String getServiceName() {
368         return SERVICE_NAME;
369     }
370
371     @Override
372     public String getServicePathComponent() {
373         return SERVICE_PATH_COMPONENT;
374     }
375
376
377    private PoxPayloadOut createLoaninInstance(String loaninNumber,
378                 String returnDate,
379                 String lender,
380                 String lendersAuthorizer,
381                 String lendersContact,
382                 String loaninContact,
383                 String borrowersAuthorizer) {
384         LoansinCommon loaninCommon = new LoansinCommon();
385         loaninCommon.setLoanInNumber(loaninNumber);
386         loaninCommon.setLoanInNumber(returnDate);
387         LenderGroupList lenderGroupList =  new LenderGroupList();
388         LenderGroup lenderGroup = new LenderGroup();
389         lenderGroup.setLender(lender);
390         lenderGroup.setLendersAuthorizer(lendersAuthorizer);
391         lenderGroup.setLendersContact(lendersContact);
392         lenderGroupList.getLenderGroup().add(lenderGroup);
393         loaninCommon.setLenderGroupList(lenderGroupList);
394         loaninCommon.setLoanInContact(loaninContact);
395         loaninCommon.setBorrowersAuthorizer(borrowersAuthorizer);
396
397         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
398         PayloadOutputPart commonPart =
399             multipart.addPart(loaninCommon, MediaType.APPLICATION_XML_TYPE);
400         commonPart.setLabel(new LoaninClient().getCommonPartName());
401
402         if(logger.isDebugEnabled()){
403             logger.debug("to be created, loanin common");
404             logger.debug(objectAsXmlString(loaninCommon, LoansinCommon.class));
405         }
406
407         return multipart;
408     }
409 }