]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ed87a83ed6482375ddd57576de455b2ab3911697
[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.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList;
39 //import org.collectionspace.services.common.authorityref.AuthorityRefList.AuthorityRefItem;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.collectionspace.services.loanout.LoansoutCommon;
42 //import org.collectionspace.services.loanout.LoansoutCommonList;
43
44 import org.jboss.resteasy.client.ClientResponse;
45
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
48 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * LoanoutAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Loanout (aka Loans Out) Service.
59  *
60  * $LastChangedRevision$
61  * $LastChangedDate$
62  */
63 public class LoanoutAuthRefsTest extends BaseServiceTest {
64
65     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
66     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67
68     // Instance variables specific to this test.
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     /* (non-Javadoc)
86      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
87      */
88     @Override
89     protected CollectionSpaceClient getClientInstance() {
90         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
91     }
92     
93     /* (non-Javadoc)
94      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
95      */
96     @Override
97         protected AbstractCommonList getAbstractCommonList(
98                         ClientResponse<AbstractCommonList> response) {
99         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
100     }
101
102     // ---------------------------------------------------------------
103     // CRUD tests : CREATE tests
104     // ---------------------------------------------------------------
105     // Success outcomes
106     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
107     public void createWithAuthRefs(String testName) throws Exception {
108
109         if (logger.isDebugEnabled()) {
110             logger.debug(testBanner(testName, CLASS_NAME));
111         }
112         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
113
114         // Submit the request to the service and store the response.
115         String identifier = createIdentifier();
116
117         // Create all the person refs and entities
118         createPersonRefs();
119
120         // Create a new Loans In resource.
121         //
122         // One or more fields in this resource will be PersonAuthority
123         // references, and will refer to Person resources by their refNames.
124         LoanoutClient loanoutClient = new LoanoutClient();
125         MultipartOutput multipart = createLoanoutInstance(
126                 "loanOutNumber-" + identifier,
127                 "returnDate-" + identifier,
128                 borrowerRefName,
129                 borrowersContactRefName,
130                 lendersAuthorizerRefName,
131                 lendersContactRefName);
132         ClientResponse<Response> res = loanoutClient.create(multipart);
133         int statusCode = res.getStatus();
134
135         // Check the status code of the response: does it match
136         // the expected response(s)?
137         //
138         // Specifically:
139         // Does it fall within the set of valid status codes?
140         // Does it exactly match the expected status code?
141         if(logger.isDebugEnabled()){
142             logger.debug(testName + ": status = " + statusCode);
143         }
144         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
145                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
146         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
147
148         // Store the ID returned from the first resource created
149         // for additional tests below.
150         if (knownResourceId == null){
151             knownResourceId = extractId(res);
152             if (logger.isDebugEnabled()) {
153                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
154             }
155         }
156         
157         // Store the IDs from every resource created by tests,
158         // so they can be deleted after tests have been run.
159         loanoutIdsCreated.add(extractId(res));
160     }
161
162     protected void createPersonRefs(){
163
164         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
165         // Create a temporary PersonAuthority resource, and its corresponding
166         // refName by which it can be identified.
167         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
168             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
169         ClientResponse<Response> res = personAuthClient.create(multipart);
170         int statusCode = res.getStatus();
171
172         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
173             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
174         Assert.assertEquals(statusCode, STATUS_CREATED);
175         personAuthCSID = extractId(res);
176         
177         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
178
179         // Create temporary Person resources, and their corresponding refNames
180         // by which they can be identified.
181
182         String csid = "";
183
184         csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
185         personIdsCreated.add(csid);
186         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
187
188         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
189         personIdsCreated.add(csid);
190         borrowersContactRefName = 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     }
201     
202     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
203         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
204         Map<String, String> personInfo = new HashMap<String,String>();
205         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
206         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
207         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
208         MultipartOutput multipart = 
209                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
210                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
211         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
212         int statusCode = res.getStatus();
213
214         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
215                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
216         Assert.assertEquals(statusCode, STATUS_CREATED);
217         return extractId(res);
218     }
219
220     // Success outcomes
221     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
222         dependsOnMethods = {"createWithAuthRefs"})
223     public void readAndCheckAuthRefs(String testName) throws Exception {
224
225         if (logger.isDebugEnabled()) {
226             logger.debug(testBanner(testName, CLASS_NAME));
227         }
228         // Perform setup.
229         testSetup(STATUS_OK, ServiceRequestType.READ);
230
231         // Submit the request to the service and store the response.
232         LoanoutClient loanoutClient = new LoanoutClient();
233         ClientResponse<MultipartInput> res = loanoutClient.read(knownResourceId);
234         int statusCode = res.getStatus();
235
236         // Check the status code of the response: does it match
237         // the expected response(s)?
238         if(logger.isDebugEnabled()){
239             logger.debug(testName + ".read: status = " + statusCode);
240         }
241         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
242             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
243         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
244
245         MultipartInput input = (MultipartInput) res.getEntity();
246         LoansoutCommon loanout = (LoansoutCommon) extractPart(input,
247             loanoutClient.getCommonPartName(), LoansoutCommon.class);
248         Assert.assertNotNull(loanout);
249         if(logger.isDebugEnabled()){
250             logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
251         }
252         // Check a couple of fields
253         Assert.assertEquals(loanout.getBorrower(), borrowerRefName);
254         Assert.assertEquals(loanout.getBorrowersContact(), borrowersContactRefName);
255         Assert.assertEquals(loanout.getLendersAuthorizer(), lendersAuthorizerRefName);
256         Assert.assertEquals(loanout.getLendersContact(), lendersContactRefName);
257         
258         // Get the auth refs and check them
259         ClientResponse<AuthorityRefList> res2 =
260            loanoutClient.getAuthorityRefs(knownResourceId);
261         statusCode = res2.getStatus();
262
263         if(logger.isDebugEnabled()){
264             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
265         }
266         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
267                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
268         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
269         AuthorityRefList list = res2.getEntity();
270
271         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
272         int numAuthRefsFound = items.size();
273         if(logger.isDebugEnabled()){
274             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
275                 " authority references, found " + numAuthRefsFound);
276         }
277         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
278             "Did not find all expected authority references! " +
279             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
280             
281         // Optionally output additional data about list members for debugging.
282         boolean iterateThroughList = true;
283         if(iterateThroughList && logger.isDebugEnabled()){
284             int i = 0;
285             for(AuthorityRefList.AuthorityRefItem item : items){
286                 logger.debug(testName + ": list-item[" + i + "] Field:" +
287                                 item.getSourceField() + "= " +
288                         item.getAuthDisplayName() +
289                         item.getItemDisplayName());
290                 logger.debug(testName + ": list-item[" + i + "] refName=" +
291                         item.getRefName());
292                 logger.debug(testName + ": list-item[" + i + "] URI=" +
293                         item.getUri());
294                 i++;
295             }
296         }
297     }
298
299
300     // ---------------------------------------------------------------
301     // Cleanup of resources created during testing
302     // ---------------------------------------------------------------
303
304     /**
305      * Deletes all resources created by tests, after all tests have been run.
306      *
307      * This cleanup method will always be run, even if one or more tests fail.
308      * For this reason, it attempts to remove all resources created
309      * at any point during testing, even if some of those resources
310      * may be expected to be deleted by certain tests.
311      */
312     @AfterClass(alwaysRun=true)
313     public void cleanUp() {
314         String noTest = System.getProperty("noTestCleanup");
315         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
316             if (logger.isDebugEnabled()) {
317                 logger.debug("Skipping Cleanup phase ...");
318             }
319             return;
320         }
321         if (logger.isDebugEnabled()) {
322             logger.debug("Cleaning up temporary resources created for testing ...");
323         }
324         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
325         // Delete Person resource(s) (before PersonAuthority resources).
326         for (String resourceId : personIdsCreated) {
327             // Note: Any non-success responses are ignored and not reported.
328             personAuthClient.deleteItem(personAuthCSID, resourceId);
329         }
330         // Delete PersonAuthority resource(s).
331         // Note: Any non-success response is ignored and not reported.
332         if (personAuthCSID != null) {
333                 personAuthClient.delete(personAuthCSID);
334                 // Delete Loans In resource(s).
335                 LoanoutClient loanoutClient = new LoanoutClient();
336                 for (String resourceId : loanoutIdsCreated) {
337                     // Note: Any non-success responses are ignored and not reported.
338                     loanoutClient.delete(resourceId);
339                 }
340         }
341     }
342
343     // ---------------------------------------------------------------
344     // Utility methods used by tests above
345     // ---------------------------------------------------------------
346     @Override
347     public String getServicePathComponent() {
348         return SERVICE_PATH_COMPONENT;
349     }
350
351    private MultipartOutput createLoanoutInstance(String loanoutNumber,
352                 String returnDate,
353                 String borrower,
354                 String borrowersContact,
355                 String lendersAuthorizer,
356                 String lendersContact) {
357         LoansoutCommon loanout = new LoansoutCommon();
358         loanout.setLoanOutNumber(loanoutNumber);
359         loanout.setLoanReturnDate(returnDate);
360         loanout.setBorrower(borrower);
361         loanout.setBorrowersContact(borrowersContact);
362         loanout.setLendersAuthorizer(lendersAuthorizer);
363         loanout.setLendersContact(lendersContact);
364         MultipartOutput multipart = new MultipartOutput();
365         OutputPart commonPart =
366             multipart.addPart(loanout, MediaType.APPLICATION_XML_TYPE);
367         commonPart.getHeaders().add("label", new LoanoutClient().getCommonPartName());
368
369         if(logger.isDebugEnabled()){
370             logger.debug("to be created, loanout common");
371             logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
372         }
373
374         return multipart;
375     }
376 }