]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
2a4869438bd6a1bd88d7da26cae254975f8abcf5
[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.Response;
31
32 import org.collectionspace.services.PersonJAXBSchema;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.LoanoutClient;
35 import org.collectionspace.services.client.PayloadOutputPart;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.jaxb.AbstractCommonList;
43 import org.collectionspace.services.loanout.LoansoutCommon;
44 import org.collectionspace.services.person.PersonTermGroup;
45
46 import org.jboss.resteasy.client.ClientResponse;
47
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * LoanoutAuthRefsTest, carries out Authority References tests against a
57  * deployed and running Loanout (aka Loans Out) Service.
58  *
59  * $LastChangedRevision$
60  * $LastChangedDate$
61  */
62 public class LoanoutAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
63
64     private final String CLASS_NAME = LoanoutAuthRefsTest.class.getName();
65     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
66
67     // Instance variables specific to this test.
68     final String SERVICE_NAME = "loansout";
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 String personAuthCSID = null;
75     private String borrowerRefName = null;
76     private String borrowersContactRefName = null;
77     private String lendersAuthorizerRefName = null;
78     private String lendersContactRefName = null;
79
80     // FIXME: Can add 'borrower' - likely to be an organization
81     // authority - as an authRef to tests below, and increase the
82     // number of expected authRefs to 4.
83     private final int NUM_AUTH_REFS_EXPECTED = 4;
84     
85     private final static String CURRENT_DATE_UTC =
86             GregorianCalendarDateTimeUtils.currentDateUTC();
87
88     /* (non-Javadoc)
89      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
90      */
91     @Override
92     protected CollectionSpaceClient getClientInstance() {
93         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
94     }
95     
96     /* (non-Javadoc)
97      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
98      */
99     @Override
100         protected AbstractCommonList getCommonList(
101                         ClientResponse<AbstractCommonList> response) {
102         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
103     }
104
105     // ---------------------------------------------------------------
106     // CRUD tests : CREATE tests
107     // ---------------------------------------------------------------
108     // Success outcomes
109     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
110     public void createWithAuthRefs(String testName) throws Exception {
111         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
112
113         // Submit the request to the service and store the response.
114         String identifier = createIdentifier();
115
116         // Create all the person refs and entities
117         createPersonRefs();
118
119         // Create a new Loans In resource.
120         //
121         // One or more fields in this resource will be PersonAuthority
122         // references, and will refer to Person resources by their refNames.
123         LoanoutClient loanoutClient = new LoanoutClient();
124         PoxPayloadOut multipart = createLoanoutInstance(
125                 "loanOutNumber-" + identifier,
126                 CURRENT_DATE_UTC,
127                 borrowerRefName,
128                 borrowersContactRefName,
129                 lendersAuthorizerRefName,
130                 lendersContactRefName);
131         ClientResponse<Response> res = loanoutClient.create(multipart);
132         int statusCode = res.getStatus();
133
134         // Check the status code of the response: does it match
135         // the expected response(s)?
136         //
137         // Specifically:
138         // Does it fall within the set of valid status codes?
139         // Does it exactly match the expected status code?
140         if(logger.isDebugEnabled()){
141             logger.debug(testName + ": status = " + statusCode);
142         }
143         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
144                 invalidStatusCodeMessage(testRequestType, statusCode));
145         Assert.assertEquals(statusCode, testExpectedStatusCode);
146
147         // Store the ID returned from the first resource created
148         // for additional tests below.
149         if (knownResourceId == null){
150             knownResourceId = extractId(res);
151             if (logger.isDebugEnabled()) {
152                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
153             }
154         }
155         
156         // Store the IDs from every resource created by tests,
157         // so they can be deleted after tests have been run.
158         loanoutIdsCreated.add(extractId(res));
159     }
160
161     protected void createPersonRefs(){
162
163         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
164         // Create a temporary PersonAuthority resource, and its corresponding
165         // refName by which it can be identified.
166         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
167             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
168         ClientResponse<Response> res = personAuthClient.create(multipart);
169         int statusCode = res.getStatus();
170
171         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
172             invalidStatusCodeMessage(testRequestType, statusCode));
173         Assert.assertEquals(statusCode, STATUS_CREATED);
174         personAuthCSID = extractId(res);
175         
176         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
177
178         // Create temporary Person resources, and their corresponding refNames
179         // by which they can be identified.
180
181         String csid = "";
182
183         csid = createPerson("Betty", "Borrower", "bettyBorrower", authRefName);
184         personIdsCreated.add(csid);
185         borrowerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
186
187         csid = createPerson("Bradley", "BorrowersContact", "bradleyBorrowersContact", authRefName);
188         personIdsCreated.add(csid);
189         borrowersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
190
191         csid = createPerson("Art", "Lendersauthorizor", "artLendersauthorizor", authRefName);
192         personIdsCreated.add(csid);
193         lendersAuthorizerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
194
195         csid = createPerson("Larry", "Lenderscontact", "larryLenderscontact", authRefName);
196         personIdsCreated.add(csid);
197         lendersContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
198     
199     }
200     
201     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
202         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
203         Map<String, String> personInfo = new HashMap<String,String>();
204         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
205         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
206         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
207         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
208         PersonTermGroup term = new PersonTermGroup();
209         String termName = firstName + " " + surName;
210         term.setTermDisplayName(termName);
211         term.setTermName(termName);
212         personTerms.add(term);
213         PoxPayloadOut multipart =
214                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
215                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
216         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
217         int statusCode = res.getStatus();
218
219         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
220                 invalidStatusCodeMessage(testRequestType, statusCode));
221         Assert.assertEquals(statusCode, STATUS_CREATED);
222         return extractId(res);
223     }
224
225     // Success outcomes
226     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
227         dependsOnMethods = {"createWithAuthRefs"})
228     public void readAndCheckAuthRefs(String testName) throws Exception {
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         LoansoutCommon loanoutCommon = null;
236         try {
237                 assertStatusCode(res, testName);
238                 // Extract the common part from the response.
239                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
240                 loanoutCommon = (LoansoutCommon) extractPart(input,
241                     loanoutClient.getCommonPartName(), LoansoutCommon.class);
242                 Assert.assertNotNull(loanoutCommon);
243                 if(logger.isDebugEnabled()){
244                     logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
245                 }
246         } finally {
247                 if (res != null) {
248                 res.releaseConnection();
249             }
250         }
251         
252         // Check a couple of fields
253         Assert.assertEquals(loanoutCommon.getBorrower(), borrowerRefName);
254         Assert.assertEquals(loanoutCommon.getBorrowersContact(), borrowersContactRefName);
255         Assert.assertEquals(loanoutCommon.getLendersAuthorizer(), lendersAuthorizerRefName);
256         Assert.assertEquals(loanoutCommon.getLendersContact(), lendersContactRefName);
257         
258         // Get the auth refs and check them
259         ClientResponse<AuthorityRefList> res2 = loanoutClient.getAuthorityRefs(knownResourceId);
260         AuthorityRefList list = null;
261         try {
262                 assertStatusCode(res2, testName);
263                 list = res2.getEntity();
264         } finally {
265                 if (res2 != null) {
266                         res2.releaseConnection();
267             }
268         }
269
270         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
271         int numAuthRefsFound = items.size();
272         if(logger.isDebugEnabled()){
273             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
274                 " authority references, found " + numAuthRefsFound);
275         }
276         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
277             "Did not find all expected authority references! " +
278             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
279             
280         // Optionally output additional data about list members for debugging.
281         boolean iterateThroughList = true;
282         if(iterateThroughList && logger.isDebugEnabled()){
283             int i = 0;
284             for(AuthorityRefList.AuthorityRefItem item : items){
285                 logger.debug(testName + ": list-item[" + i + "] Field:" +
286                                 item.getSourceField() + "= " +
287                         item.getAuthDisplayName() +
288                         item.getItemDisplayName());
289                 logger.debug(testName + ": list-item[" + i + "] refName=" +
290                         item.getRefName());
291                 logger.debug(testName + ": list-item[" + i + "] URI=" +
292                         item.getUri());
293                 i++;
294             }
295         }
296     }
297
298
299     // ---------------------------------------------------------------
300     // Cleanup of resources created during testing
301     // ---------------------------------------------------------------
302
303     /**
304      * Deletes all resources created by tests, after all tests have been run.
305      *
306      * This cleanup method will always be run, even if one or more tests fail.
307      * For this reason, it attempts to remove all resources created
308      * at any point during testing, even if some of those resources
309      * may be expected to be deleted by certain tests.
310      */
311     @AfterClass(alwaysRun=true)
312     public void cleanUp() {
313         String noTest = System.getProperty("noTestCleanup");
314         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
315             if (logger.isDebugEnabled()) {
316                 logger.debug("Skipping Cleanup phase ...");
317             }
318             return;
319         }
320         if (logger.isDebugEnabled()) {
321             logger.debug("Cleaning up temporary resources created for testing ...");
322         }
323         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
324         // Delete Person resource(s) (before PersonAuthority resources).
325         for (String resourceId : personIdsCreated) {
326             // Note: Any non-success responses are ignored and not reported.
327             personAuthClient.deleteItem(personAuthCSID, resourceId);
328         }
329         // Delete PersonAuthority resource(s).
330         // Note: Any non-success response is ignored and not reported.
331         if (personAuthCSID != null) {
332                 personAuthClient.delete(personAuthCSID);
333                 // Delete Loans In resource(s).
334                 LoanoutClient loanoutClient = new LoanoutClient();
335                 for (String resourceId : loanoutIdsCreated) {
336                     // Note: Any non-success responses are ignored and not reported.
337                     loanoutClient.delete(resourceId);
338                 }
339         }
340     }
341
342     // ---------------------------------------------------------------
343     // Utility methods used by tests above
344     // ---------------------------------------------------------------
345     public String getServiceName() {
346         return SERVICE_NAME;
347     }
348
349     @Override
350     public String getServicePathComponent() {
351         return SERVICE_PATH_COMPONENT;
352     }
353
354     private PoxPayloadOut createLoanoutInstance(String loanoutNumber,
355                 String returnDate,
356                 String borrower,
357                 String borrowersContact,
358                 String lendersAuthorizer,
359                 String lendersContact) {
360         LoansoutCommon loanoutCommon = new LoansoutCommon();
361         loanoutCommon.setLoanOutNumber(loanoutNumber);
362         loanoutCommon.setLoanReturnDate(returnDate);
363         loanoutCommon.setBorrower(borrower);
364         loanoutCommon.setBorrowersContact(borrowersContact);
365         loanoutCommon.setLendersAuthorizer(lendersAuthorizer);
366         loanoutCommon.setLendersContact(lendersContact);
367
368         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
369         PayloadOutputPart commonPart =
370                         multipart.addPart(new LoanoutClient().getCommonPartName(), loanoutCommon);
371
372         if(logger.isDebugEnabled()){
373                 logger.debug("to be created, loanout common");
374                 logger.debug(objectAsXmlString(loanoutCommon, LoansoutCommon.class));
375         }
376
377         return multipart;
378     }
379
380     @Override
381     protected Class<AbstractCommonList> getCommonListType() {
382         // TODO Auto-generated method stub
383         return null;
384     }
385 }