]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
862551da32a63532b72258e84253938c4aba11e9
[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         assertStatusCode(res, testName);
240
241         // Extract the common part from the response.
242         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
243         LoansoutCommon loanoutCommon = (LoansoutCommon) extractPart(input,
244             loanoutClient.getCommonPartName(), LoansoutCommon.class);
245         Assert.assertNotNull(loanoutCommon);
246         if(logger.isDebugEnabled()){
247             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
248         }
249         // Check a couple of fields
250         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
251         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
252         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
253         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
254         
255         // Get the auth refs and check them
256         ClientResponse<AuthorityRefList> res2 =
257            loanoutClient.getAuthorityRefs(knownResourceId);
258         assertStatusCode(res2, testName);
259
260         AuthorityRefList list = res2.getEntity();
261
262         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
263         int numAuthRefsFound = items.size();
264         if(logger.isDebugEnabled()){
265             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
266                 " authority references, found " + numAuthRefsFound);
267         }
268         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
269             "Did not find all expected authority references! " +
270             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
271             
272         // Optionally output additional data about list members for debugging.
273         boolean iterateThroughList = true;
274         if(iterateThroughList && logger.isDebugEnabled()){
275             int i = 0;
276             for(AuthorityRefList.AuthorityRefItem item : items){
277                 logger.debug(testName + ": list-item[" + i + "] Field:" +
278                                 item.getSourceField() + "= " +
279                         item.getAuthDisplayName() +
280                         item.getItemDisplayName());
281                 logger.debug(testName + ": list-item[" + i + "] refName=" +
282                         item.getRefName());
283                 logger.debug(testName + ": list-item[" + i + "] URI=" +
284                         item.getUri());
285                 i++;
286             }
287         }
288     }
289
290
291     // ---------------------------------------------------------------
292     // Cleanup of resources created during testing
293     // ---------------------------------------------------------------
294
295     /**
296      * Deletes all resources created by tests, after all tests have been run.
297      *
298      * This cleanup method will always be run, even if one or more tests fail.
299      * For this reason, it attempts to remove all resources created
300      * at any point during testing, even if some of those resources
301      * may be expected to be deleted by certain tests.
302      */
303     @AfterClass(alwaysRun=true)
304     public void cleanUp() {
305         String noTest = System.getProperty("noTestCleanup");
306         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
307             if (logger.isDebugEnabled()) {
308                 logger.debug("Skipping Cleanup phase ...");
309             }
310             return;
311         }
312         if (logger.isDebugEnabled()) {
313             logger.debug("Cleaning up temporary resources created for testing ...");
314         }
315         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
316         // Delete Person resource(s) (before PersonAuthority resources).
317         for (String resourceId : personIdsCreated) {
318             // Note: Any non-success responses are ignored and not reported.
319             personAuthClient.deleteItem(personAuthCSID, resourceId);
320         }
321         // Delete PersonAuthority resource(s).
322         // Note: Any non-success response is ignored and not reported.
323         if (personAuthCSID != null) {
324                 personAuthClient.delete(personAuthCSID);
325                 // Delete Loans In resource(s).
326                 LoanoutClient loanoutClient = new LoanoutClient();
327                 for (String resourceId : loanoutIdsCreated) {
328                     // Note: Any non-success responses are ignored and not reported.
329                     loanoutClient.delete(resourceId);
330                 }
331         }
332     }
333
334     // ---------------------------------------------------------------
335     // Utility methods used by tests above
336     // ---------------------------------------------------------------
337     public String getServiceName() {
338         return SERVICE_NAME;
339     }
340
341     @Override
342     public String getServicePathComponent() {
343         return SERVICE_PATH_COMPONENT;
344     }
345
346    private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
347                 String returnDate,
348                 String borrower,
349                 String borrowersContact,
350                 String lendersAuthorizer,
351                 String lendersContact) {
352         LoansoutCommon loanoutCommon = new LoansoutCommon();
353         loanoutCommon.setLoanOutNumber(loanoutNumber);
354         loanoutCommon.setLoanReturnDate(returnDate);
355         loanoutCommon.setBorrower(borrower);
356         loanoutCommon.setBorrowersContact(borrowersContact);
357         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
358         loanoutCommon.setLendersContact(lendersContact);
359
360         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
361         PayloadOutputPart commonPart =
362             multipart.addPart(loanoutCommon, MediaType.APPLICATION_XML_TYPE);
363         commonPart.setLabel(new LoanoutClient().getCommonPartName());
364
365         if(logger.isDebugEnabled()){
366             logger.debug("to be created, loanout common");
367             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
368         }
369
370         return multipart;
371     }
372 }