]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
543f355d90ab1105d80992beb35e8f0a711b6afa
[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.LoanoutClient;
36 import org.collectionspace.services.client.PayloadOutputPart;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
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.authorityref.AuthorityRefList.AuthorityRefItem;
43 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
44 import org.collectionspace.services.jaxb.AbstractCommonList;
45 import org.collectionspace.services.loanout.LoansoutCommon;
46 //import org.collectionspace.services.loanout.LoansoutCommonList;
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  * LoanoutAuthRefsTest, carries out Authority References tests against a
59  * deployed and running Loanout (aka Loans Out) Service.
60  *
61  * $LastChangedRevision$
62  * $LastChangedDate$
63  */
64 public class LoanoutAuthRefsTest extends BaseServiceTest {
65
66     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
67     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
68
69     // Instance variables specific to this test.
70     final String SERVICE_NAME = "loansout";
71     final String SERVICE_PATH_COMPONENT = "loansout";
72     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
73     private String knownResourceId = null;
74     private List<String> loanoutIdsCreated = new ArrayList<String>();
75     private List<String> personIdsCreated = new ArrayList<String>();
76     private String personAuthCSID = null;
77     private String borrowerRefName = null;
78     private String borrowersContactRefName = null;
79     private String lendersAuthorizerRefName = null;
80     private String lendersContactRefName = null;
81
82     // FIXME: Can add 'borrower' - likely to be an organization
83     // authority - as an authRef to tests below, and increase the
84     // number of expected authRefs to 4.
85     private final int NUM_AUTH_REFS_EXPECTED = 4;
86     
87     private final static String CURRENT_DATE_UTC =
88             GregorianCalendarDateTimeUtils.currentDateUTC();
89
90     /* (non-Javadoc)
91      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
92      */
93     @Override
94     protected CollectionSpaceClient getClientInstance() {
95         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
96     }
97     
98     /* (non-Javadoc)
99      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
100      */
101     @Override
102         protected AbstractCommonList getAbstractCommonList(
103                         ClientResponse<AbstractCommonList> response) {
104         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
105     }
106
107     // ---------------------------------------------------------------
108     // CRUD tests : CREATE tests
109     // ---------------------------------------------------------------
110     // Success outcomes
111     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
112     public void createWithAuthRefs(String testName) throws Exception {
113
114         if (logger.isDebugEnabled()) {
115             logger.debug(testBanner(testName, CLASS_NAME));
116         }
117         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
118
119         // Submit the request to the service and store the response.
120         String identifier = createIdentifier();
121
122         // Create all the person refs and entities
123         createPersonRefs();
124
125         // Create a new Loans In resource.
126         //
127         // One or more fields in this resource will be PersonAuthority
128         // references, and will refer to Person resources by their refNames.
129         LoanoutClient loanoutClient = new LoanoutClient();
130         PoxPayloadOut multipart = createLoanoutInstance(
131                 "loanOutNumber-" + identifier,
132                 CURRENT_DATE_UTC,
133                 borrowerRefName,
134                 borrowersContactRefName,
135                 lendersAuthorizerRefName,
136                 lendersContactRefName);
137         ClientResponse<Response> res = loanoutClient.create(multipart);
138         int statusCode = res.getStatus();
139
140         // Check the status code of the response: does it match
141         // the expected response(s)?
142         //
143         // Specifically:
144         // Does it fall within the set of valid status codes?
145         // Does it exactly match the expected status code?
146         if(logger.isDebugEnabled()){
147             logger.debug(testName + ": status = " + statusCode);
148         }
149         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
150                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
151         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
152
153         // Store the ID returned from the first resource created
154         // for additional tests below.
155         if (knownResourceId == null){
156             knownResourceId = extractId(res);
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(extractId(res));
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         ClientResponse<Response> res = personAuthClient.create(multipart);
175         int statusCode = res.getStatus();
176
177         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
178             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
179         Assert.assertEquals(statusCode, STATUS_CREATED);
180         personAuthCSID = extractId(res);
181         
182         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
183
184         // Create temporary Person resources, and their corresponding refNames
185         // by which they can be identified.
186
187         String csid = "";
188
189         csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
190         personIdsCreated.add(csid);
191         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
192
193         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
194         personIdsCreated.add(csid);
195         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
196
197         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
198         personIdsCreated.add(csid);
199         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
200
201         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
202         personIdsCreated.add(csid);
203         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
204     
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         PoxPayloadOut multipart =
214                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
215                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
216         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
217         int statusCode = res.getStatus();
218
219         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
220                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
221         Assert.assertEquals(statusCode, STATUS_CREATED);
222         return extractId(res);
223     }
224
225     // Success outcomes
226     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
227         dependsOnMethods = {"createWithAuthRefs"})
228     public void readAndCheckAuthRefs(String testName) throws Exception {
229
230         if (logger.isDebugEnabled()) {
231             logger.debug(testBanner(testName, CLASS_NAME));
232         }
233         // Perform setup.
234         testSetup(STATUS_OK, ServiceRequestType.READ);
235
236         // Submit the request to the service and store the response.
237         LoanoutClient loanoutClient = new LoanoutClient();
238         ClientResponse<String> res = loanoutClient.read(knownResourceId);
239         int statusCode = res.getStatus();
240
241         // Check the status code of the response: does it match
242         // the expected response(s)?
243         if(logger.isDebugEnabled()){
244             logger.debug(testName + ".read: status = " + statusCode);
245         }
246         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
247             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
248         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
249
250         // Extract the common part from the response.
251         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
252         LoansoutCommon loanoutCommon = (LoansoutCommon) extractPart(input,
253             loanoutClient.getCommonPartName(), LoansoutCommon.class);
254         Assert.assertNotNull(loanoutCommon);
255         if(logger.isDebugEnabled()){
256             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
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 =
266            loanoutClient.getAuthorityRefs(knownResourceId);
267         statusCode = res2.getStatus();
268
269         if(logger.isDebugEnabled()){
270             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
271         }
272         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
273                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
274         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
275         AuthorityRefList list = res2.getEntity();
276
277         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
278         int numAuthRefsFound = items.size();
279         if(logger.isDebugEnabled()){
280             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
281                 " authority references, found " + numAuthRefsFound);
282         }
283         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
284             "Did not find all expected authority references! " +
285             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
286             
287         // Optionally output additional data about list members for debugging.
288         boolean iterateThroughList = true;
289         if(iterateThroughList && logger.isDebugEnabled()){
290             int i = 0;
291             for(AuthorityRefList.AuthorityRefItem item : items){
292                 logger.debug(testName + ": list-item[" + i + "] Field:" +
293                                 item.getSourceField() + "= " +
294                         item.getAuthDisplayName() +
295                         item.getItemDisplayName());
296                 logger.debug(testName + ": list-item[" + i + "] refName=" +
297                         item.getRefName());
298                 logger.debug(testName + ": list-item[" + i + "] URI=" +
299                         item.getUri());
300                 i++;
301             }
302         }
303     }
304
305
306     // ---------------------------------------------------------------
307     // Cleanup of resources created during testing
308     // ---------------------------------------------------------------
309
310     /**
311      * Deletes all resources created by tests, after all tests have been run.
312      *
313      * This cleanup method will always be run, even if one or more tests fail.
314      * For this reason, it attempts to remove all resources created
315      * at any point during testing, even if some of those resources
316      * may be expected to be deleted by certain tests.
317      */
318     @AfterClass(alwaysRun=true)
319     public void cleanUp() {
320         String noTest = System.getProperty("noTestCleanup");
321         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
322             if (logger.isDebugEnabled()) {
323                 logger.debug("Skipping Cleanup phase ...");
324             }
325             return;
326         }
327         if (logger.isDebugEnabled()) {
328             logger.debug("Cleaning up temporary resources created for testing ...");
329         }
330         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
331         // Delete Person resource(s) (before PersonAuthority resources).
332         for (String resourceId : personIdsCreated) {
333             // Note: Any non-success responses are ignored and not reported.
334             personAuthClient.deleteItem(personAuthCSID, resourceId);
335         }
336         // Delete PersonAuthority resource(s).
337         // Note: Any non-success response is ignored and not reported.
338         if (personAuthCSID != null) {
339                 personAuthClient.delete(personAuthCSID);
340                 // Delete Loans In resource(s).
341                 LoanoutClient loanoutClient = new LoanoutClient();
342                 for (String resourceId : loanoutIdsCreated) {
343                     // Note: Any non-success responses are ignored and not reported.
344                     loanoutClient.delete(resourceId);
345                 }
346         }
347     }
348
349     // ---------------------------------------------------------------
350     // Utility methods used by tests above
351     // ---------------------------------------------------------------
352     public String getServiceName() {
353         return SERVICE_NAME;
354     }
355
356     @Override
357     public String getServicePathComponent() {
358         return SERVICE_PATH_COMPONENT;
359     }
360
361    private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
362                 String returnDate,
363                 String borrower,
364                 String borrowersContact,
365                 String lendersAuthorizer,
366                 String lendersContact) {
367         LoansoutCommon loanoutCommon = new LoansoutCommon();
368         loanoutCommon.setLoanOutNumber(loanoutNumber);
369         loanoutCommon.setLoanReturnDate(returnDate);
370         loanoutCommon.setBorrower(borrower);
371         loanoutCommon.setBorrowersContact(borrowersContact);
372         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
373         loanoutCommon.setLendersContact(lendersContact);
374
375         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
376         PayloadOutputPart commonPart =
377             multipart.addPart(loanoutCommon, MediaType.APPLICATION_XML_TYPE);
378         commonPart.setLabel(new LoanoutClient().getCommonPartName());
379
380         if(logger.isDebugEnabled()){
381             logger.debug("to be created, loanout common");
382             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
383         }
384
385         return multipart;
386     }
387 }