]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
dd96fe9cc2906a9864925bfbab5068263e581c2f
[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.PayloadOutputPart;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
39 import org.collectionspace.services.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 //import org.collectionspace.services.common.authorityref.AuthorityRefList.AuthorityRefItem;
43 import org.collectionspace.services.jaxb.AbstractCommonList;
44 import org.collectionspace.services.loanout.LoansoutCommon;
45 //import org.collectionspace.services.loanout.LoansoutCommonList;
46
47 import org.jboss.resteasy.client.ClientResponse;
48
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_NAME = "loansout";
70     final String SERVICE_PATH_COMPONENT = "loansout";
71     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
72     private String knownResourceId = null;
73     private List<String> loanoutIdsCreated = new ArrayList<String>();
74     private List<String> personIdsCreated = new ArrayList<String>();
75     private String personAuthCSID = null;
76     private String borrowerRefName = 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 = 4;
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         if (logger.isDebugEnabled()) {
111             logger.debug(testBanner(testName, CLASS_NAME));
112         }
113         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
114
115         // Submit the request to the service and store the response.
116         String identifier = createIdentifier();
117
118         // Create all the person refs and entities
119         createPersonRefs();
120
121         // Create a new Loans In resource.
122         //
123         // One or more fields in this resource will be PersonAuthority
124         // references, and will refer to Person resources by their refNames.
125         LoanoutClient loanoutClient = new LoanoutClient();
126         PoxPayloadOut multipart = createLoanoutInstance(
127                 "loanOutNumber-" + identifier,
128                 "returnDate-" + identifier,
129                 borrowerRefName,
130                 borrowersContactRefName,
131                 lendersAuthorizerRefName,
132                 lendersContactRefName);
133         ClientResponse<Response> res = loanoutClient.create(multipart);
134         int statusCode = res.getStatus();
135
136         // Check the status code of the response: does it match
137         // the expected response(s)?
138         //
139         // Specifically:
140         // Does it fall within the set of valid status codes?
141         // Does it exactly match the expected status code?
142         if(logger.isDebugEnabled()){
143             logger.debug(testName + ": status = " + statusCode);
144         }
145         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
146                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
147         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
148
149         // Store the ID returned from the first resource created
150         // for additional tests below.
151         if (knownResourceId == null){
152             knownResourceId = extractId(res);
153             if (logger.isDebugEnabled()) {
154                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
155             }
156         }
157         
158         // Store the IDs from every resource created by tests,
159         // so they can be deleted after tests have been run.
160         loanoutIdsCreated.add(extractId(res));
161     }
162
163     protected void createPersonRefs(){
164
165         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
166         // Create a temporary PersonAuthority resource, and its corresponding
167         // refName by which it can be identified.
168         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
169             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
170         ClientResponse<Response> res = personAuthClient.create(multipart);
171         int statusCode = res.getStatus();
172
173         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
174             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
175         Assert.assertEquals(statusCode, STATUS_CREATED);
176         personAuthCSID = extractId(res);
177         
178         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
179
180         // Create temporary Person resources, and their corresponding refNames
181         // by which they can be identified.
182
183         String csid = "";
184
185         csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
186         personIdsCreated.add(csid);
187         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
188
189         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
190         personIdsCreated.add(csid);
191         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
192
193         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
194         personIdsCreated.add(csid);
195         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
196
197         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
198         personIdsCreated.add(csid);
199         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
200     
201     }
202     
203     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
204         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
205         Map<String, String> personInfo = new HashMap<String,String>();
206         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
207         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
208         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
209         PoxPayloadOut multipart =
210                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
211                                 authRefName, personInfo, personAuthClient.getItemCommonPartName());
212         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
213         int statusCode = res.getStatus();
214
215         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
216                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
217         Assert.assertEquals(statusCode, STATUS_CREATED);
218         return extractId(res);
219     }
220
221     // Success outcomes
222     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
223         dependsOnMethods = {"createWithAuthRefs"})
224     public void readAndCheckAuthRefs(String testName) throws Exception {
225
226         if (logger.isDebugEnabled()) {
227             logger.debug(testBanner(testName, CLASS_NAME));
228         }
229         // Perform setup.
230         testSetup(STATUS_OK, ServiceRequestType.READ);
231
232         // Submit the request to the service and store the response.
233         LoanoutClient loanoutClient = new LoanoutClient();
234         ClientResponse<String> res = loanoutClient.read(knownResourceId);
235         int statusCode = res.getStatus();
236
237         // Check the status code of the response: does it match
238         // the expected response(s)?
239         if(logger.isDebugEnabled()){
240             logger.debug(testName + ".read: status = " + statusCode);
241         }
242         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
243             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
244         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
245
246         // Extract the common part from the response.
247         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
248         LoansoutCommon loanoutCommon = (LoansoutCommon) extractPart(input,
249             loanoutClient.getCommonPartName(), LoansoutCommon.class);
250         Assert.assertNotNull(loanoutCommon);
251         if(logger.isDebugEnabled()){
252             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
253         }
254         // Check a couple of fields
255         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
256         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
257         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
258         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
259         
260         // Get the auth refs and check them
261         ClientResponse<AuthorityRefList> res2 =
262            loanoutClient.getAuthorityRefs(knownResourceId);
263         statusCode = res2.getStatus();
264
265         if(logger.isDebugEnabled()){
266             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
267         }
268         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
269                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
270         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
271         AuthorityRefList list = res2.getEntity();
272
273         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
274         int numAuthRefsFound = items.size();
275         if(logger.isDebugEnabled()){
276             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
277                 " authority references, found " + numAuthRefsFound);
278         }
279         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
280             "Did not find all expected authority references! " +
281             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
282             
283         // Optionally output additional data about list members for debugging.
284         boolean iterateThroughList = true;
285         if(iterateThroughList && logger.isDebugEnabled()){
286             int i = 0;
287             for(AuthorityRefList.AuthorityRefItem item : items){
288                 logger.debug(testName + ": list-item[" + i + "] Field:" +
289                                 item.getSourceField() + "= " +
290                         item.getAuthDisplayName() +
291                         item.getItemDisplayName());
292                 logger.debug(testName + ": list-item[" + i + "] refName=" +
293                         item.getRefName());
294                 logger.debug(testName + ": list-item[" + i + "] URI=" +
295                         item.getUri());
296                 i++;
297             }
298         }
299     }
300
301
302     // ---------------------------------------------------------------
303     // Cleanup of resources created during testing
304     // ---------------------------------------------------------------
305
306     /**
307      * Deletes all resources created by tests, after all tests have been run.
308      *
309      * This cleanup method will always be run, even if one or more tests fail.
310      * For this reason, it attempts to remove all resources created
311      * at any point during testing, even if some of those resources
312      * may be expected to be deleted by certain tests.
313      */
314     @AfterClass(alwaysRun=true)
315     public void cleanUp() {
316         String noTest = System.getProperty("noTestCleanup");
317         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
318             if (logger.isDebugEnabled()) {
319                 logger.debug("Skipping Cleanup phase ...");
320             }
321             return;
322         }
323         if (logger.isDebugEnabled()) {
324             logger.debug("Cleaning up temporary resources created for testing ...");
325         }
326         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
327         // Delete Person resource(s) (before PersonAuthority resources).
328         for (String resourceId : personIdsCreated) {
329             // Note: Any non-success responses are ignored and not reported.
330             personAuthClient.deleteItem(personAuthCSID, resourceId);
331         }
332         // Delete PersonAuthority resource(s).
333         // Note: Any non-success response is ignored and not reported.
334         if (personAuthCSID != null) {
335                 personAuthClient.delete(personAuthCSID);
336                 // Delete Loans In resource(s).
337                 LoanoutClient loanoutClient = new LoanoutClient();
338                 for (String resourceId : loanoutIdsCreated) {
339                     // Note: Any non-success responses are ignored and not reported.
340                     loanoutClient.delete(resourceId);
341                 }
342         }
343     }
344
345     // ---------------------------------------------------------------
346     // Utility methods used by tests above
347     // ---------------------------------------------------------------
348     public String getServiceName() {
349         return SERVICE_NAME;
350     }
351
352     @Override
353     public String getServicePathComponent() {
354         return SERVICE_PATH_COMPONENT;
355     }
356
357    private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
358                 String returnDate,
359                 String borrower,
360                 String borrowersContact,
361                 String lendersAuthorizer,
362                 String lendersContact) {
363         LoansoutCommon loanoutCommon = new LoansoutCommon();
364         loanoutCommon.setLoanOutNumber(loanoutNumber);
365         loanoutCommon.setLoanReturnDate(returnDate);
366         loanoutCommon.setBorrower(borrower);
367         loanoutCommon.setBorrowersContact(borrowersContact);
368         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
369         loanoutCommon.setLendersContact(lendersContact);
370
371         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
372         PayloadOutputPart commonPart =
373             multipart.addPart(loanoutCommon, MediaType.APPLICATION_XML_TYPE);
374         commonPart.setLabel(new LoanoutClient().getCommonPartName());
375
376         if(logger.isDebugEnabled()){
377             logger.debug("to be created, loanout common");
378             logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
379         }
380
381         return multipart;
382     }
383 }