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