]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7485d5a11422867f4cadf98cb9d8dfbd71fce335
[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.LoaninClient;
35 import org.collectionspace.services.client.PersonAuthorityClient;
36 import org.collectionspace.services.client.PersonAuthorityClientUtils;
37 import org.collectionspace.services.common.authorityref.AuthorityRefList;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList.AuthorityRefItem;
39 import org.collectionspace.services.loanin.LoansinCommon;
40 import org.collectionspace.services.loanin.LoansinCommonList;
41
42 import org.jboss.resteasy.client.ClientResponse;
43
44 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
45 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
46 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
47 import org.testng.Assert;
48 import org.testng.annotations.AfterClass;
49 import org.testng.annotations.Test;
50
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * LoaninAuthRefsTest, carries out Authority References tests against a
56  * deployed and running Loanin (aka Loans In) Service.
57  *
58  * $LastChangedRevision: 1327 $
59  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
60  */
61 public class LoaninAuthRefsTest extends BaseServiceTest {
62
63    private final Logger logger =
64        LoggerFactory.getLogger(LoaninAuthRefsTest.class);
65
66     // Instance variables specific to this test.
67     private LoaninClient loaninClient = new LoaninClient();
68     private PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
69     final String SERVICE_PATH_COMPONENT = "loansin";
70     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
71     private String knownResourceId = null;
72     private List<String> loaninIdsCreated = new ArrayList();
73     private List<String> personIdsCreated = new ArrayList();
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 lendersAuthorizerRefName = null;
78     private String lendersContactRefName = null;
79     private String loanInContactRefName = null;
80     // FIXME: May change when repeatable / multivalue 'lenders' field is added
81     // to tenant-bindings.xml
82     private final int NUM_AUTH_REFS_EXPECTED = 3;
83
84     // ---------------------------------------------------------------
85     // CRUD tests : CREATE tests
86     // ---------------------------------------------------------------
87     // Success outcomes
88     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
89     public void createWithAuthRefs(String testName) throws Exception {
90
91         testSetup(CREATED_STATUS, ServiceRequestType.CREATE,testName);
92
93         // Submit the request to the service and store the response.
94         String identifier = createIdentifier();
95         
96         // Create all the person refs and entities
97         createPersonRefs();
98
99         // Create a new Loans In resource.
100         //
101         // One or more fields in this resource will be PersonAuthority
102         // references, and will refer to Person resources by their refNames.
103         MultipartOutput multipart = createLoaninInstance(
104                 "loanInNumber-" + identifier,
105                 "returnDate-" + identifier,
106                 lendersAuthorizerRefName,
107                 lendersContactRefName,
108                 loanInContactRefName);
109
110         ClientResponse<Response> res = loaninClient.create(multipart);
111
112         int statusCode = res.getStatus();
113
114         // Check the status code of the response: does it match
115         // the expected response(s)?
116         //
117         // Specifically:
118         // Does it fall within the set of valid status codes?
119         // Does it exactly match the expected status code?
120         if(logger.isDebugEnabled()){
121             logger.debug(testName + ": status = " + statusCode);
122         }
123         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
124                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
125         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
126
127         // Store the ID returned from the first resource created
128         // for additional tests below.
129         if (knownResourceId == null){
130             knownResourceId = extractId(res);
131             if (logger.isDebugEnabled()) {
132                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
133             }
134         }
135         
136         // Store the IDs from every resource created by tests,
137         // so they can be deleted after tests have been run.
138         loaninIdsCreated.add(extractId(res));
139     }
140     
141     protected void createPersonRefs(){
142
143         // Create a temporary PersonAuthority resource, and its corresponding
144         // refName by which it can be identified.
145         String authRefName = 
146                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
147         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
148             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
149         ClientResponse<Response> res = personAuthClient.create(multipart);
150         int statusCode = res.getStatus();
151
152         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
153             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
154         Assert.assertEquals(statusCode, CREATED_STATUS);
155         personAuthCSID = extractId(res);
156
157         // Create temporary Person resources, and their corresponding refNames
158         // by which they can be identified.
159         lendersAuthorizerRefName =
160             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
161         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
162
163         lendersContactRefName =
164             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
165         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
166         
167         loanInContactRefName =
168             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Carrie Loanincontact", true);
169         personIdsCreated.add(createPerson("Carrie", "Loanincontact", loanInContactRefName));
170
171         // FIXME: Add instance(s) of 'lenders' field when we can work with
172         // repeatable / multivalued authority reference fields.  Be sure to
173         // change the NUM_AUTH_REFS_EXPECTED constant accordingly, or otherwise
174         // revise check for numbers of authority fields expected in readAndCheckAuthRefs.
175     }
176     
177     protected String createPerson(String firstName, String surName, String refName ) {
178         Map<String, String> personInfo = new HashMap<String,String>();
179         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
180         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
181         MultipartOutput multipart = 
182                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
183                                 refName, personInfo, personAuthClient.getItemCommonPartName());
184         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
185         int statusCode = res.getStatus();
186
187         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
188                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
189         Assert.assertEquals(statusCode, CREATED_STATUS);
190         return extractId(res);
191     }
192
193     // Success outcomes
194     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
195         dependsOnMethods = {"createWithAuthRefs"})
196     public void readAndCheckAuthRefs(String testName) throws Exception {
197
198         // Perform setup.
199         testSetup(OK_STATUS, ServiceRequestType.READ,testName);
200
201         // Submit the request to the service and store the response.
202         ClientResponse<MultipartInput> res = loaninClient.read(knownResourceId);
203         int statusCode = res.getStatus();
204
205         // Check the status code of the response: does it match
206         // the expected response(s)?
207         if(logger.isDebugEnabled()){
208             logger.debug(testName + ".read: status = " + statusCode);
209         }
210         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
211             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
212         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
213
214         MultipartInput input = (MultipartInput) res.getEntity();
215         LoansinCommon loanin = (LoansinCommon) extractPart(input,
216             loaninClient.getCommonPartName(), LoansinCommon.class);
217         Assert.assertNotNull(loanin);
218         if(logger.isDebugEnabled()){
219             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
220         }
221         // Check a couple of fields
222         // FIXME
223         Assert.assertEquals(loanin.getLendersAuthorizer(), lendersAuthorizerRefName);
224         Assert.assertEquals(loanin.getLendersContact(), lendersContactRefName);
225         Assert.assertEquals(loanin.getLoanInContact(), loanInContactRefName);
226         
227         // Get the auth refs and check them
228         ClientResponse<AuthorityRefList> res2 =
229            loaninClient.getAuthorityRefs(knownResourceId);
230         statusCode = res2.getStatus();
231
232         if(logger.isDebugEnabled()){
233             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
234         }
235         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
236                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
237         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
238         AuthorityRefList list = res2.getEntity();
239
240         // Optionally output additional data about list members for debugging.
241         boolean iterateThroughList = true;
242         if(iterateThroughList && logger.isDebugEnabled()){
243             List<AuthorityRefList.AuthorityRefItem> items =
244                     list.getAuthorityRefItem();
245             int i = 0;
246             for(AuthorityRefList.AuthorityRefItem item : items){
247                 logger.debug(testName + ": list-item[" + i + "] Field:" +
248                                 item.getSourceField() + "= " +
249                         item.getAuthDisplayName() +
250                         item.getItemDisplayName());
251                 logger.debug(testName + ": list-item[" + i + "] refName=" +
252                         item.getRefName());
253                 logger.debug(testName + ": list-item[" + i + "] URI=" +
254                         item.getUri());
255                 i++;
256             }
257             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
258         }
259     }
260
261
262     // ---------------------------------------------------------------
263     // Cleanup of resources created during testing
264     // ---------------------------------------------------------------
265
266     /**
267      * Deletes all resources created by tests, after all tests have been run.
268      *
269      * This cleanup method will always be run, even if one or more tests fail.
270      * For this reason, it attempts to remove all resources created
271      * at any point during testing, even if some of those resources
272      * may be expected to be deleted by certain tests.
273      */
274     @AfterClass(alwaysRun=true)
275     public void cleanUp() {
276         if (logger.isDebugEnabled()) {
277             logger.debug("Cleaning up temporary resources created for testing ...");
278         }
279         // Note: Any non-success responses are ignored and not reported.
280
281         // Delete Person resource(s) (before PersonAuthority resources).
282         ClientResponse<Response> res;
283         for (String resourceId : personIdsCreated) {
284             res = personAuthClient.deleteItem(personAuthCSID, resourceId);
285         }
286         // Delete PersonAuthority resource(s).
287         res = personAuthClient.delete(personAuthCSID);
288         // Delete Loans In resource(s).
289         for (String resourceId : loaninIdsCreated) {
290             res = loaninClient.delete(resourceId);
291         }
292     }
293
294     // ---------------------------------------------------------------
295     // Utility methods used by tests above
296     // ---------------------------------------------------------------
297     @Override
298     public String getServicePathComponent() {
299         return SERVICE_PATH_COMPONENT;
300     }
301
302    private MultipartOutput createLoaninInstance(String loaninNumber,
303                 String returnDate,
304                 String lendersAuthorizer,
305                 String lendersContact,
306                 String loanInContact) {
307         LoansinCommon loanin = new LoansinCommon();
308         loanin.setLoanInNumber(loaninNumber);
309         loanin.setLoanInNumber(returnDate);
310         loanin.setLendersAuthorizer(lendersAuthorizer);
311         loanin.setLendersContact(lendersContact);
312         loanin.setLoanInContact(loanInContact);
313         MultipartOutput multipart = new MultipartOutput();
314         OutputPart commonPart =
315             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
316         commonPart.getHeaders().add("label", loaninClient.getCommonPartName());
317
318         if(logger.isDebugEnabled()){
319             logger.debug("to be created, loanin common");
320             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
321         }
322
323         return multipart;
324     }
325 }