]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a881a3921e2aae406dc79112074b77af2cb41dc0
[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.LoanoutClient;
35 import org.collectionspace.services.client.PayloadOutputPart;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
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.loanout.LoansoutCommon;
44 import org.collectionspace.services.person.PersonTermGroup;
45
46 import org.jboss.resteasy.client.ClientResponse;
47
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * LoanoutAuthRefsTest, carries out Authority References tests against a
57  * deployed and running Loanout (aka Loans Out) Service.
58  *
59  * $LastChangedRevision$
60  * $LastChangedDate$
61  */
62 public class LoanoutAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
63
64     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
65     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
66
67     // Instance variables specific to this test.
68     final String SERVICE_NAME = "loansout";
69     final String SERVICE_PATH_COMPONENT = "loansout";
70     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
71     private String knownResourceId = null;
72     private List<String> loanoutIdsCreated = new ArrayList<String>();
73     private List<String> personIdsCreated = new ArrayList<String>();
74     private String personAuthCSID = null;
75     private String borrowerRefName = null;
76     private String borrowersContactRefName = null;
77     private String lendersAuthorizerRefName = null;
78     private String lendersContactRefName = null;
79
80     // FIXME: Can add 'borrower' - likely to be an organization
81     // authority - as an authRef to tests below, and increase the
82     // number of expected authRefs to 4.
83     private final int NUM_AUTH_REFS_EXPECTED = 4;
84     
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 getCommonList(
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         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
112
113         // Submit the request to the service and store the response.
114         String identifier = createIdentifier();
115
116         // Create all the person refs and entities
117         createPersonRefs();
118
119         // Create a new Loans In resource.
120         //
121         // One or more fields in this resource will be PersonAuthority
122         // references, and will refer to Person resources by their refNames.
123         LoanoutClient loanoutClient = new LoanoutClient();
124         PoxPayloadOut multipart = createLoanoutInstance(
125                 "loanOutNumber-" + identifier,
126                 CURRENT_DATE_UTC,
127                 borrowerRefName,
128                 borrowersContactRefName,
129                 lendersAuthorizerRefName,
130                 lendersContactRefName);
131         String newId = null;
132         Response res = loanoutClient.create(multipart);
133         try {
134                 int statusCode = res.getStatus();
135         
136                 // Check the status code of the response: does it match
137                 // the expected response(s)?
138                 //
139                 // Specifically:
140                 // Does it fall within the set of valid status codes?
141                 // Does it exactly match the expected status code?
142                 if(logger.isDebugEnabled()){
143                     logger.debug(testName + ": status = " + statusCode);
144                 }
145                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
146                         invalidStatusCodeMessage(testRequestType, statusCode));
147                 Assert.assertEquals(statusCode, testExpectedStatusCode);
148                 newId = extractId(res);
149         } finally {
150                 res.close();
151         }
152
153         // Store the ID returned from the first resource created
154         // for additional tests below.
155         if (knownResourceId == null){
156             knownResourceId = newId;
157             if (logger.isDebugEnabled()) {
158                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
159             }
160         }
161         
162         // Store the IDs from every resource created by tests,
163         // so they can be deleted after tests have been run.
164         loanoutIdsCreated.add(newId);
165     }
166
167     protected void createPersonRefs(){
168
169         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
170         // Create a temporary PersonAuthority resource, and its corresponding
171         // refName by which it can be identified.
172         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
173             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
174         Response res = personAuthClient.create(multipart);
175         try {
176                 int statusCode = res.getStatus();
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
190         String csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
191         personIdsCreated.add(csid);
192         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
193
194         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
195         personIdsCreated.add(csid);
196         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
197
198         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
199         personIdsCreated.add(csid);
200         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
201
202         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
203         personIdsCreated.add(csid);
204         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
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         LoanoutClient loanoutClient = new LoanoutClient();
240         ClientResponse<String> res = loanoutClient.read(knownResourceId);
241         LoansoutCommon loanoutCommon = null;
242         try {
243                 assertStatusCode(res, testName);
244                 // Extract the common part from the response.
245                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
246                 loanoutCommon = (LoansoutCommon) extractPart(input,
247                     loanoutClient.getCommonPartName(), LoansoutCommon.class);
248                 Assert.assertNotNull(loanoutCommon);
249                 if(logger.isDebugEnabled()){
250                     logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
251                 }
252         } finally {
253                 if (res != null) {
254                 res.releaseConnection();
255             }
256         }
257         
258         // Check a couple of fields
259         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
260         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
261         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
262         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
263         
264         // Get the auth refs and check them
265         ClientResponse<AuthorityRefList> res2 = loanoutClient.getAuthorityRefs(knownResourceId);
266         AuthorityRefList list = null;
267         try {
268                 assertStatusCode(res2, testName);
269                 list = res2.getEntity();
270         } finally {
271                 if (res2 != null) {
272                         res2.releaseConnection();
273             }
274         }
275
276         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
277         int numAuthRefsFound = items.size();
278         if(logger.isDebugEnabled()){
279             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
280                 " authority references, found " + numAuthRefsFound);
281         }
282         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
283             "Did not find all expected authority references! " +
284             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
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
304
305     // ---------------------------------------------------------------
306     // Cleanup of resources created during testing
307     // ---------------------------------------------------------------
308
309     /**
310      * Deletes all resources created by tests, after all tests have been run.
311      *
312      * This cleanup method will always be run, even if one or more tests fail.
313      * For this reason, it attempts to remove all resources created
314      * at any point during testing, even if some of those resources
315      * may be expected to be deleted by certain tests.
316      */
317     @AfterClass(alwaysRun=true)
318     public void cleanUp() {
319         String noTest = System.getProperty("noTestCleanup");
320         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
321             if (logger.isDebugEnabled()) {
322                 logger.debug("Skipping Cleanup phase ...");
323             }
324             return;
325         }
326         if (logger.isDebugEnabled()) {
327             logger.debug("Cleaning up temporary resources created for testing ...");
328         }
329         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
330         // Delete Person resource(s) (before PersonAuthority resources).
331         for (String resourceId : personIdsCreated) {
332             // Note: Any non-success responses are ignored and not reported.
333             personAuthClient.deleteItem(personAuthCSID, resourceId);
334         }
335         // Delete PersonAuthority resource(s).
336         // Note: Any non-success response is ignored and not reported.
337         if (personAuthCSID != null) {
338                 personAuthClient.delete(personAuthCSID);
339                 // Delete Loans In resource(s).
340                 LoanoutClient loanoutClient = new LoanoutClient();
341                 for (String resourceId : loanoutIdsCreated) {
342                     // Note: Any non-success responses are ignored and not reported.
343                     loanoutClient.delete(resourceId);
344                 }
345         }
346     }
347
348     // ---------------------------------------------------------------
349     // Utility methods used by tests above
350     // ---------------------------------------------------------------
351     public String getServiceName() {
352         return SERVICE_NAME;
353     }
354
355     @Override
356     public String getServicePathComponent() {
357         return SERVICE_PATH_COMPONENT;
358     }
359
360     private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
361                 String returnDate,
362                 String borrower,
363                 String borrowersContact,
364                 String lendersAuthorizer,
365                 String lendersContact) {
366         LoansoutCommon loanoutCommon = new LoansoutCommon();
367         loanoutCommon.setLoanOutNumber(loanoutNumber);
368         loanoutCommon.setLoanReturnDate(returnDate);
369         loanoutCommon.setBorrower(borrower);
370         loanoutCommon.setBorrowersContact(borrowersContact);
371         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
372         loanoutCommon.setLendersContact(lendersContact);
373
374         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
375         PayloadOutputPart commonPart =
376                         multipart.addPart(new LoanoutClient().getCommonPartName(), loanoutCommon);
377
378         if(logger.isDebugEnabled()){
379                 logger.debug("to be created, loanout common");
380                 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
381         }
382
383         return multipart;
384     }
385
386     @Override
387     protected Class<AbstractCommonList> getCommonListType() {
388         // TODO Auto-generated method stub
389         return null;
390     }
391 }