]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d23707081ee04bcc70d0d93c69e46425eb8bd842
[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.LoaninClient;
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.loanin.LoansinCommon;
42 //import org.collectionspace.services.loanin.LoansinCommonList;
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  * LoaninAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Loanin (aka Loans In) Service.
59  *
60  * $LastChangedRevision: 1327 $
61  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
62  */
63 public class LoaninAuthRefsTest extends BaseServiceTest {
64
65    private final Logger logger =
66        LoggerFactory.getLogger(LoaninAuthRefsTest.class);
67
68     // Instance variables specific to this test.
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<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 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     /* (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         testSetup(CREATED_STATUS, ServiceRequestType.CREATE,testName);
109
110         // Submit the request to the service and store the response.
111         String identifier = createIdentifier();
112         
113         // Create all the person refs and entities
114         createPersonRefs();
115
116         // Create a new Loans In resource.
117         //
118         // One or more fields in this resource will be PersonAuthority
119         // references, and will refer to Person resources by their refNames.
120         LoaninClient loaninClient = new LoaninClient();
121         MultipartOutput multipart = createLoaninInstance(
122                 "loanInNumber-" + identifier,
123                 "returnDate-" + identifier,
124                 lendersAuthorizerRefName,
125                 lendersContactRefName,
126                 loanInContactRefName);
127         ClientResponse<Response> response = loaninClient.create(multipart);
128         int statusCode = response.getStatus();
129         try {
130                 // Check the status code of the response: does it match
131                 // the expected response(s)?
132                 //
133                 // Specifically:
134                 // Does it fall within the set of valid status codes?
135                 // Does it exactly match the expected status code?
136                 if(logger.isDebugEnabled()){
137                     logger.debug(testName + ": status = " + statusCode);
138                 }
139                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
140                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
141                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
142         
143                 // Store the ID returned from the first resource created
144                 // for additional tests below.
145                 if (knownResourceId == null){
146                     knownResourceId = extractId(response);
147                     if (logger.isDebugEnabled()) {
148                         logger.debug(testName + ": knownResourceId=" + knownResourceId);
149                     }
150                 }
151                 
152                 // Store the IDs from every resource created by tests,
153                 // so they can be deleted after tests have been run.
154                 loaninIdsCreated.add(extractId(response));
155         } finally {
156                 response.releaseConnection();
157         }
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, CREATED_STATUS);
175         personAuthCSID = extractId(res);
176
177         // Create temporary Person resources, and their corresponding refNames
178         // by which they can be identified.
179         lendersAuthorizerRefName =
180             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
181         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
182
183         lendersContactRefName =
184             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
185         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
186         
187         loanInContactRefName =
188             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Carrie Loanincontact", true);
189         personIdsCreated.add(createPerson("Carrie", "Loanincontact", loanInContactRefName));
190
191         // FIXME: Add instance(s) of 'lenders' field when we can work with
192         // repeatable / multivalued authority reference fields.  Be sure to
193         // change the NUM_AUTH_REFS_EXPECTED constant accordingly, or otherwise
194         // revise check for numbers of authority fields expected in readAndCheckAuthRefs.
195     }
196     
197     protected String createPerson(String firstName, String surName, String refName ) {
198         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
199         Map<String, String> personInfo = new HashMap<String,String>();
200         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
201         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
202         MultipartOutput multipart = 
203                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
204                                 refName, personInfo, personAuthClient.getItemCommonPartName());
205         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
206         int statusCode = res.getStatus();
207
208         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
209                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
210         Assert.assertEquals(statusCode, CREATED_STATUS);
211         return extractId(res);
212     }
213
214     // Success outcomes
215     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
216         dependsOnMethods = {"createWithAuthRefs"})
217     public void readAndCheckAuthRefs(String testName) throws Exception {
218
219         // Perform setup.
220         testSetup(OK_STATUS, ServiceRequestType.READ,testName);
221
222         // Submit the request to the service and store the response.
223         LoaninClient loaninClient = new LoaninClient();
224         ClientResponse<MultipartInput> res = loaninClient.read(knownResourceId);
225         int statusCode = res.getStatus();
226
227         // Check the status code of the response: does it match
228         // the expected response(s)?
229         if(logger.isDebugEnabled()){
230             logger.debug(testName + ".read: status = " + statusCode);
231         }
232         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
233             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
234         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
235
236         MultipartInput input = (MultipartInput) res.getEntity();
237         LoansinCommon loanin = (LoansinCommon) extractPart(input,
238             loaninClient.getCommonPartName(), LoansinCommon.class);
239         Assert.assertNotNull(loanin);
240         if(logger.isDebugEnabled()){
241             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
242         }
243         // Check a couple of fields
244         // FIXME
245         Assert.assertEquals(loanin.getLendersAuthorizer(), lendersAuthorizerRefName);
246         Assert.assertEquals(loanin.getLendersContact(), lendersContactRefName);
247         Assert.assertEquals(loanin.getLoanInContact(), loanInContactRefName);
248         
249         // Get the auth refs and check them
250         ClientResponse<AuthorityRefList> res2 =
251            loaninClient.getAuthorityRefs(knownResourceId);
252         statusCode = res2.getStatus();
253
254         if(logger.isDebugEnabled()){
255             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
256         }
257         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
258                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
259         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
260         AuthorityRefList list = res2.getEntity();
261
262         // Optionally output additional data about list members for debugging.
263         boolean iterateThroughList = true;
264         if(iterateThroughList && logger.isDebugEnabled()){
265             List<AuthorityRefList.AuthorityRefItem> items =
266                     list.getAuthorityRefItem();
267             int i = 0;
268             for(AuthorityRefList.AuthorityRefItem item : items){
269                 logger.debug(testName + ": list-item[" + i + "] Field:" +
270                                 item.getSourceField() + "= " +
271                         item.getAuthDisplayName() +
272                         item.getItemDisplayName());
273                 logger.debug(testName + ": list-item[" + i + "] refName=" +
274                         item.getRefName());
275                 logger.debug(testName + ": list-item[" + i + "] URI=" +
276                         item.getUri());
277                 i++;
278             }
279             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
280         }
281     }
282
283
284     // ---------------------------------------------------------------
285     // Cleanup of resources created during testing
286     // ---------------------------------------------------------------
287
288     /**
289      * Deletes all resources created by tests, after all tests have been run.
290      *
291      * This cleanup method will always be run, even if one or more tests fail.
292      * For this reason, it attempts to remove all resources created
293      * at any point during testing, even if some of those resources
294      * may be expected to be deleted by certain tests.
295      */
296     @AfterClass(alwaysRun=true)
297     public void cleanUp() {
298         String noTest = System.getProperty("noTestCleanup");
299         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
300             if (logger.isDebugEnabled()) {
301                 logger.debug("Skipping Cleanup phase ...");
302             }
303             return;
304         }
305         if (logger.isDebugEnabled()) {
306             logger.debug("Cleaning up temporary resources created for testing ...");
307         }
308         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
309         // Delete Person resource(s) (before PersonAuthority resources).
310         
311         for (String resourceId : personIdsCreated) {
312             // Note: Any non-success responses are ignored and not reported.
313                 ClientResponse<Response> response = 
314                         personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
315                 response.releaseConnection();
316         }
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                 LoaninClient loaninClient = new LoaninClient();
324                 ClientResponse<Response> response = null;
325                 for (String resourceId : loaninIdsCreated) {
326                     // Note: Any non-success responses are ignored and not reported.
327                     response = loaninClient.delete(resourceId); // alternative to loaninClient.delete(resourceId).releaseConnection();
328                     response.releaseConnection();
329                 }
330         }
331     }
332
333     // ---------------------------------------------------------------
334     // Utility methods used by tests above
335     // ---------------------------------------------------------------
336     @Override
337     public String getServicePathComponent() {
338         return SERVICE_PATH_COMPONENT;
339     }
340
341    private MultipartOutput createLoaninInstance(String loaninNumber,
342                 String returnDate,
343                 String lendersAuthorizer,
344                 String lendersContact,
345                 String loaninContact) {
346         LoansinCommon loanin = new LoansinCommon();
347         loanin.setLoanInNumber(loaninNumber);
348         loanin.setLoanInNumber(returnDate);
349         loanin.setLendersAuthorizer(lendersAuthorizer);
350         loanin.setLendersContact(lendersContact);
351         loanin.setLoanInContact(loaninContact);
352         MultipartOutput multipart = new MultipartOutput();
353         OutputPart commonPart =
354             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
355         commonPart.getHeaders().add("label", new LoaninClient().getCommonPartName());
356
357         if(logger.isDebugEnabled()){
358             logger.debug("to be created, loanin common");
359             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
360         }
361
362         return multipart;
363     }
364 }