]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d7c3670cb9669470c3ed51b53732e94986ea854d
[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 borrowersContactRefName = null;
76     private String lendersAuthorizerRefName = null;
77     private String lendersContactRefName = null;
78
79     // FIXME: Can add 'borrower' - likely to be an organization
80     // authority - as an authRef to tests below, and increase the
81     // number of expected authRefs to 4.
82     private final int NUM_AUTH_REFS_EXPECTED = 3;
83
84     /* (non-Javadoc)
85      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
86      */
87     @Override
88     protected CollectionSpaceClient getClientInstance() {
89         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
90     }
91     
92     /* (non-Javadoc)
93      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
94      */
95     @Override
96         protected AbstractCommonList getAbstractCommonList(
97                         ClientResponse<AbstractCommonList> response) {
98         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
99     }
100
101     // ---------------------------------------------------------------
102     // CRUD tests : CREATE tests
103     // ---------------------------------------------------------------
104     // Success outcomes
105     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
106     public void createWithAuthRefs(String testName) throws Exception {
107
108         if (logger.isDebugEnabled()) {
109             logger.debug(testBanner(testName, CLASS_NAME));
110         }
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         MultipartOutput multipart = createLoanoutInstance(
125                 "loanOutNumber-" + identifier,
126                 "returnDate-" + identifier,
127                 borrowersContactRefName,
128                 lendersAuthorizerRefName,
129                 lendersContactRefName);
130         ClientResponse<Response> res = loanoutClient.create(multipart);
131         int statusCode = res.getStatus();
132
133         // Check the status code of the response: does it match
134         // the expected response(s)?
135         //
136         // Specifically:
137         // Does it fall within the set of valid status codes?
138         // Does it exactly match the expected status code?
139         if(logger.isDebugEnabled()){
140             logger.debug(testName + ": status = " + statusCode);
141         }
142         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
143                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
144         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
145
146         // Store the ID returned from the first resource created
147         // for additional tests below.
148         if (knownResourceId == null){
149             knownResourceId = extractId(res);
150             if (logger.isDebugEnabled()) {
151                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
152             }
153         }
154         
155         // Store the IDs from every resource created by tests,
156         // so they can be deleted after tests have been run.
157         loanoutIdsCreated.add(extractId(res));
158     }
159
160     protected void createPersonRefs(){
161
162         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
163         // Create a temporary PersonAuthority resource, and its corresponding
164         // refName by which it can be identified.
165         String authRefName = 
166                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
167         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
168             PERSON_AUTHORITY_NAME, authRefName, 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         // Create temporary Person resources, and their corresponding refNames
178         // by which they can be identified.
179         borrowersContactRefName =
180             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Bradley BorrowersContact", true);
181         personIdsCreated.add(createPerson("Bradley", "BorrowersContact", borrowersContactRefName));
182
183         lendersAuthorizerRefName =
184             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
185         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
186
187         lendersContactRefName =
188             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
189         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
190     }
191     
192     protected String createPerson(String firstName, String surName, String refName ) {
193         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
194         Map<String, String> personInfo = new HashMap<String,String>();
195         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
196         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
197         MultipartOutput multipart = 
198                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
199                                 refName, personInfo, personAuthClient.getItemCommonPartName());
200         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
201         int statusCode = res.getStatus();
202
203         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
204                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
205         Assert.assertEquals(statusCode, STATUS_CREATED);
206         return extractId(res);
207     }
208
209     // Success outcomes
210     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
211         dependsOnMethods = {"createWithAuthRefs"})
212     public void readAndCheckAuthRefs(String testName) throws Exception {
213
214         if (logger.isDebugEnabled()) {
215             logger.debug(testBanner(testName, CLASS_NAME));
216         }
217         // Perform setup.
218         testSetup(STATUS_OK, ServiceRequestType.READ);
219
220         // Submit the request to the service and store the response.
221         LoanoutClient loanoutClient = new LoanoutClient();
222         ClientResponse<MultipartInput> res = loanoutClient.read(knownResourceId);
223         int statusCode = res.getStatus();
224
225         // Check the status code of the response: does it match
226         // the expected response(s)?
227         if(logger.isDebugEnabled()){
228             logger.debug(testName + ".read: status = " + statusCode);
229         }
230         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
231             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
232         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
233
234         MultipartInput input = (MultipartInput) res.getEntity();
235         LoansoutCommon loanout = (LoansoutCommon) extractPart(input,
236             loanoutClient.getCommonPartName(), LoansoutCommon.class);
237         Assert.assertNotNull(loanout);
238         if(logger.isDebugEnabled()){
239             logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
240         }
241         // Check a couple of fields
242         // FIXME
243         Assert.assertEquals(loanout.getLendersAuthorizer(), lendersAuthorizerRefName);
244         Assert.assertEquals(loanout.getLendersContact(), lendersContactRefName);
245         
246         // Get the auth refs and check them
247         ClientResponse<AuthorityRefList> res2 =
248            loanoutClient.getAuthorityRefs(knownResourceId);
249         statusCode = res2.getStatus();
250
251         if(logger.isDebugEnabled()){
252             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
253         }
254         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
255                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
256         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
257         AuthorityRefList list = res2.getEntity();
258
259         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
260         int numAuthRefsFound = items.size();
261         if(logger.isDebugEnabled()){
262             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
263                 " authority references, found " + numAuthRefsFound);
264         }
265         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
266             "Did not find all expected authority references! " +
267             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
268             
269         // Optionally output additional data about list members for debugging.
270         boolean iterateThroughList = true;
271         if(iterateThroughList && logger.isDebugEnabled()){
272             int i = 0;
273             for(AuthorityRefList.AuthorityRefItem item : items){
274                 logger.debug(testName + ": list-item[" + i + "] Field:" +
275                                 item.getSourceField() + "= " +
276                         item.getAuthDisplayName() +
277                         item.getItemDisplayName());
278                 logger.debug(testName + ": list-item[" + i + "] refName=" +
279                         item.getRefName());
280                 logger.debug(testName + ": list-item[" + i + "] URI=" +
281                         item.getUri());
282                 i++;
283             }
284         }
285     }
286
287
288     // ---------------------------------------------------------------
289     // Cleanup of resources created during testing
290     // ---------------------------------------------------------------
291
292     /**
293      * Deletes all resources created by tests, after all tests have been run.
294      *
295      * This cleanup method will always be run, even if one or more tests fail.
296      * For this reason, it attempts to remove all resources created
297      * at any point during testing, even if some of those resources
298      * may be expected to be deleted by certain tests.
299      */
300     @AfterClass(alwaysRun=true)
301     public void cleanUp() {
302         String noTest = System.getProperty("noTestCleanup");
303         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
304             if (logger.isDebugEnabled()) {
305                 logger.debug("Skipping Cleanup phase ...");
306             }
307             return;
308         }
309         if (logger.isDebugEnabled()) {
310             logger.debug("Cleaning up temporary resources created for testing ...");
311         }
312         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
313         // Delete Person resource(s) (before PersonAuthority resources).
314         for (String resourceId : personIdsCreated) {
315             // Note: Any non-success responses are ignored and not reported.
316             personAuthClient.deleteItem(personAuthCSID, resourceId);
317         }
318         // Delete PersonAuthority resource(s).
319         // Note: Any non-success response is ignored and not reported.
320         if (personAuthCSID != null) {
321                 personAuthClient.delete(personAuthCSID);
322                 // Delete Loans In resource(s).
323                 LoanoutClient loanoutClient = new LoanoutClient();
324                 for (String resourceId : loanoutIdsCreated) {
325                     // Note: Any non-success responses are ignored and not reported.
326                     loanoutClient.delete(resourceId);
327                 }
328         }
329     }
330
331     // ---------------------------------------------------------------
332     // Utility methods used by tests above
333     // ---------------------------------------------------------------
334     @Override
335     public String getServicePathComponent() {
336         return SERVICE_PATH_COMPONENT;
337     }
338
339    private MultipartOutput createLoanoutInstance(String loanoutNumber,
340                 String returnDate,
341                 String borrowersContact,
342                 String lendersAuthorizer,
343                 String lendersContact) {
344         LoansoutCommon loanout = new LoansoutCommon();
345         loanout.setLoanOutNumber(loanoutNumber);
346         loanout.setLoanReturnDate(returnDate);
347         loanout.setBorrowersContact(lendersContact);
348         loanout.setLendersAuthorizer(lendersAuthorizer);
349         loanout.setLendersContact(lendersContact);
350         MultipartOutput multipart = new MultipartOutput();
351         OutputPart commonPart =
352             multipart.addPart(loanout, MediaType.APPLICATION_XML_TYPE);
353         commonPart.getHeaders().add("label", new LoanoutClient().getCommonPartName());
354
355         if(logger.isDebugEnabled()){
356             logger.debug("to be created, loanout common");
357             logger.debug(objectAsXmlString(loanout, LoansoutCommon.class));
358         }
359
360         return multipart;
361     }
362 }