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