]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
5ccf8709b55d80c75f4b6b7bbee0b9705e4c04e1
[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> res = loaninClient.create(multipart);
128         int statusCode = res.getStatus();
129
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(res);
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(res));
155     }
156     
157     protected void createPersonRefs(){
158
159         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
160         // Create a temporary PersonAuthority resource, and its corresponding
161         // refName by which it can be identified.
162         String authRefName = 
163                 PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
164         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
165             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
166         ClientResponse<Response> res = personAuthClient.create(multipart);
167         int statusCode = res.getStatus();
168
169         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
170             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
171         Assert.assertEquals(statusCode, CREATED_STATUS);
172         personAuthCSID = extractId(res);
173
174         // Create temporary Person resources, and their corresponding refNames
175         // by which they can be identified.
176         lendersAuthorizerRefName =
177             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Art Lendersauthorizor", true);
178         personIdsCreated.add(createPerson("Art", "Lendersauthorizor", lendersAuthorizerRefName));
179
180         lendersContactRefName =
181             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Larry Lenderscontact", true);
182         personIdsCreated.add(createPerson("Larry", "Lenderscontact", lendersContactRefName));
183         
184         loanInContactRefName =
185             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Carrie Loanincontact", true);
186         personIdsCreated.add(createPerson("Carrie", "Loanincontact", loanInContactRefName));
187
188         // FIXME: Add instance(s) of 'lenders' field when we can work with
189         // repeatable / multivalued authority reference fields.  Be sure to
190         // change the NUM_AUTH_REFS_EXPECTED constant accordingly, or otherwise
191         // revise check for numbers of authority fields expected in readAndCheckAuthRefs.
192     }
193     
194     protected String createPerson(String firstName, String surName, String refName ) {
195         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
196         Map<String, String> personInfo = new HashMap<String,String>();
197         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
198         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
199         MultipartOutput multipart = 
200                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
201                                 refName, personInfo, personAuthClient.getItemCommonPartName());
202         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
203         int statusCode = res.getStatus();
204
205         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
206                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
207         Assert.assertEquals(statusCode, CREATED_STATUS);
208         return extractId(res);
209     }
210
211     // Success outcomes
212     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
213         dependsOnMethods = {"createWithAuthRefs"})
214     public void readAndCheckAuthRefs(String testName) throws Exception {
215
216         // Perform setup.
217         testSetup(OK_STATUS, ServiceRequestType.READ,testName);
218
219         // Submit the request to the service and store the response.
220         LoaninClient loaninClient = new LoaninClient();
221         ClientResponse<MultipartInput> res = loaninClient.read(knownResourceId);
222         int statusCode = res.getStatus();
223
224         // Check the status code of the response: does it match
225         // the expected response(s)?
226         if(logger.isDebugEnabled()){
227             logger.debug(testName + ".read: status = " + statusCode);
228         }
229         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
230             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
231         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
232
233         MultipartInput input = (MultipartInput) res.getEntity();
234         LoansinCommon loanin = (LoansinCommon) extractPart(input,
235             loaninClient.getCommonPartName(), LoansinCommon.class);
236         Assert.assertNotNull(loanin);
237         if(logger.isDebugEnabled()){
238             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
239         }
240         // Check a couple of fields
241         // FIXME
242         Assert.assertEquals(loanin.getLendersAuthorizer(), lendersAuthorizerRefName);
243         Assert.assertEquals(loanin.getLendersContact(), lendersContactRefName);
244         Assert.assertEquals(loanin.getLoanInContact(), loanInContactRefName);
245         
246         // Get the auth refs and check them
247         ClientResponse<AuthorityRefList> res2 =
248            loaninClient.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         // Optionally output additional data about list members for debugging.
260         boolean iterateThroughList = true;
261         if(iterateThroughList && logger.isDebugEnabled()){
262             List<AuthorityRefList.AuthorityRefItem> items =
263                     list.getAuthorityRefItem();
264             int i = 0;
265             for(AuthorityRefList.AuthorityRefItem item : items){
266                 logger.debug(testName + ": list-item[" + i + "] Field:" +
267                                 item.getSourceField() + "= " +
268                         item.getAuthDisplayName() +
269                         item.getItemDisplayName());
270                 logger.debug(testName + ": list-item[" + i + "] refName=" +
271                         item.getRefName());
272                 logger.debug(testName + ": list-item[" + i + "] URI=" +
273                         item.getUri());
274                 i++;
275             }
276             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
277         }
278     }
279
280
281     // ---------------------------------------------------------------
282     // Cleanup of resources created during testing
283     // ---------------------------------------------------------------
284
285     /**
286      * Deletes all resources created by tests, after all tests have been run.
287      *
288      * This cleanup method will always be run, even if one or more tests fail.
289      * For this reason, it attempts to remove all resources created
290      * at any point during testing, even if some of those resources
291      * may be expected to be deleted by certain tests.
292      */
293     @AfterClass(alwaysRun=true)
294     public void cleanUp() {
295         String noTest = System.getProperty("noTestCleanup");
296         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
297             if (logger.isDebugEnabled()) {
298                 logger.debug("Skipping Cleanup phase ...");
299             }
300             return;
301         }
302         if (logger.isDebugEnabled()) {
303             logger.debug("Cleaning up temporary resources created for testing ...");
304         }
305         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
306         // Delete Person resource(s) (before PersonAuthority resources).
307         
308         for (String resourceId : personIdsCreated) {
309             // Note: Any non-success responses are ignored and not reported.
310                 personAuthClient.deleteItem(personAuthCSID, resourceId);
311         }
312         
313         // Delete PersonAuthority resource(s).
314         // Note: Any non-success response is ignored and not reported.
315         if (personAuthCSID != null) {
316                 personAuthClient.delete(personAuthCSID);
317                 // Delete Loans In resource(s).
318                 LoaninClient loaninClient = new LoaninClient();
319                 for (String resourceId : loaninIdsCreated) {
320                     // Note: Any non-success responses are ignored and not reported.
321                     loaninClient.delete(resourceId);
322                 }
323         }
324     }
325
326     // ---------------------------------------------------------------
327     // Utility methods used by tests above
328     // ---------------------------------------------------------------
329     @Override
330     public String getServicePathComponent() {
331         return SERVICE_PATH_COMPONENT;
332     }
333
334    private MultipartOutput createLoaninInstance(String loaninNumber,
335                 String returnDate,
336                 String lendersAuthorizer,
337                 String lendersContact,
338                 String loaninContact) {
339         LoansinCommon loanin = new LoansinCommon();
340         loanin.setLoanInNumber(loaninNumber);
341         loanin.setLoanInNumber(returnDate);
342         loanin.setLendersAuthorizer(lendersAuthorizer);
343         loanin.setLendersContact(lendersContact);
344         loanin.setLoanInContact(loaninContact);
345         MultipartOutput multipart = new MultipartOutput();
346         OutputPart commonPart =
347             multipart.addPart(loanin, MediaType.APPLICATION_XML_TYPE);
348         commonPart.getHeaders().add("label", new LoaninClient().getCommonPartName());
349
350         if(logger.isDebugEnabled()){
351             logger.debug("to be created, loanin common");
352             logger.debug(objectAsXmlString(loanin, LoansinCommon.class));
353         }
354
355         return multipart;
356     }
357 }