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