]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3fd836440b42c1d134eea0796ebf6640441b5271
[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 (c)) 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 import javax.ws.rs.core.Response;
30
31 import org.collectionspace.services.PersonJAXBSchema;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.PersonAuthorityClient;
34 import org.collectionspace.services.client.PersonAuthorityClientUtils;
35 import org.collectionspace.services.client.PoxPayloadOut;
36 import org.collectionspace.services.jaxb.AbstractCommonList;
37 import org.collectionspace.services.person.PersonsCommonList;
38
39 import org.jboss.resteasy.client.ClientResponse;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.testng.Assert;
43 import org.testng.annotations.AfterClass;
44 import org.testng.annotations.BeforeClass;
45 import org.testng.annotations.Test;
46
47 /**
48  * VocabularyServiceTest, carries out tests against a
49  * deployed and running Vocabulary Service.
50  *
51  * $LastChangedRevision: 753 $
52  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
53  */
54 public class PersonAuthorityServicePerfTest extends BaseServiceTest {
55
56     private final String CLASS_NAME = PersonAuthorityServicePerfTest.class.getName();
57     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
58
59     // Instance variables specific to this test.
60 //    final String SERVICE_PATH_COMPONENT = "personauthorities";
61 //    final String ITEM_SERVICE_PATH_COMPONENT = "items";
62     private String authId = null;
63     private String authRefName = null;
64     private List<String> allItemIdsCreated = new ArrayList<String>();
65     private String[] firstNames = { 
66                 "Ann","Anne","Anno",
67                 "George","Geoff","Georgia",
68                 "John","Johanna","Jon",
69                 "Patrick","Patty","Patrik"};
70     private String[] firstNameSuffixes = { 
71                 "1","2","3","4","5","6","7","8","9","0"};
72     private String[] lastNames = { 
73                 "Axis","Black","Cobbler",
74                 "Dunne","England","France",
75                 "Goldsmith","Hart","Indy",
76                 "Jones","Kohn","Lark",
77                 "Maven","Newhart","Overdunne",
78                 "Plaxo","Queen","Roberts",
79                 "Smith","Tate","Underdunne",
80                 "Vicious","Waits","Xavier",
81                 "Yeats","Zoolander"};
82     
83     // Keep these two arrays in sync!!!
84     private String[] partialTerms = {"Ann","John","Patty2"};
85     private int[] nMatches = {
86                 4*lastNames.length*firstNameSuffixes.length, // Johanna too!
87                     lastNames.length*firstNameSuffixes.length,
88                     lastNames.length, };
89     private int shortTestLimit = 2; // Just use first three items in suffix and last name arrays
90     private int[] nMatchesShort = {
91                 4*shortTestLimit*shortTestLimit, // Johanna too!
92                 shortTestLimit*shortTestLimit,
93                 shortTestLimit, };
94     private boolean runFullTest = false;
95     
96         @Override
97         public String getServicePathComponent() {
98                 return PersonAuthorityClient.SERVICE_PATH_COMPONENT;
99         }
100
101         @Override
102         protected String getServiceName() {
103                 return PersonAuthorityClient.SERVICE_NAME;
104         }
105     
106     /* (non-Javadoc)
107      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
108      */
109     @Override
110     protected CollectionSpaceClient getClientInstance() {
111         return new PersonAuthorityClient();
112     }
113     
114     /* (non-Javadoc)
115      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
116      */
117     @Override
118         protected AbstractCommonList getAbstractCommonList(
119                         ClientResponse<AbstractCommonList> response) {
120         return response.getEntity(PersonsCommonList.class);
121     }
122  
123     @BeforeClass
124     public void setup() {
125         try {
126             createAuthority();
127         } catch (Exception e) {
128             Assert.fail("Could not create new Authority for search tests.", e);
129         }
130         try {
131                 long startTime = System.currentTimeMillis();
132             createItems();
133                 long stopTime = System.currentTimeMillis();
134                 double runTime = (stopTime - startTime)/1000.0;
135                 logger.info("Created {} items in {} seconds.", 
136                                         allItemIdsCreated.size(), runTime);
137         } catch (Exception e) {
138             Assert.fail("Could not create new item in Authority for search tests.", e);
139         }
140     }
141  
142     // ---------------------------------------------------------------
143     // Utilities: setup routines for search tests
144     // ---------------------------------------------------------------
145
146     public void createAuthority() throws Exception {
147
148         String testName = "createAuthority";
149
150         // Perform setup.
151         int expectedStatusCode = Response.Status.CREATED.getStatusCode();
152         ServiceRequestType requestType = ServiceRequestType.CREATE;
153         testSetup(expectedStatusCode, requestType);
154
155         // Submit the request to the service and store the response.
156         PersonAuthorityClient client = new PersonAuthorityClient();
157         String shortId = "perfTestPersons";
158         String displayName = "Perf Test Person Auth";
159         String baseRefName = PersonAuthorityClientUtils.createPersonAuthRefName(shortId, null);
160         PoxPayloadOut multipart =
161             PersonAuthorityClientUtils.createPersonAuthorityInstance(
162             displayName, shortId, client.getCommonPartName());
163
164         String newID = null;
165         ClientResponse<Response> res = client.create(multipart);
166         try {
167             int statusCode = res.getStatus();
168             // Check the status code of the response: does it match
169             // the expected response(s)?
170             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
171                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
172             Assert.assertEquals(statusCode, this.EXPECTED_STATUS_CODE);
173             newID = PersonAuthorityClientUtils.extractId(res);
174             logger.info("{}: succeeded.", testName);
175         } finally {
176             res.releaseConnection();
177         }
178         // Store the refname from the first resource created
179         // for additional tests below.
180         authRefName = baseRefName;
181         // Store the ID returned from the first resource created
182         // for additional tests below.
183         authId = newID;
184     }
185
186     /**
187      * Creates an item in the authority, used for partial term matching tests.
188      *
189      * @param authorityCsid The CSID of the Authority in which the term will be created.
190      * @param authRefName The refName of the Authority in which the term will be created.
191      */
192     private void createItem(String firstName, String lastName, PersonAuthorityClient client )
193         throws Exception {
194             
195         int expectedStatusCode = Response.Status.CREATED.getStatusCode();
196         ServiceRequestType requestType = ServiceRequestType.CREATE;
197         testSetup(expectedStatusCode, requestType);
198         
199         if(client==null) {
200             client = new PersonAuthorityClient();
201         }
202
203         // Submit the request to the service and store the response.
204         Map<String, String> personMap = new HashMap<String,String>();
205         //
206         // Fill the property map
207         //
208         String shortId = firstName+lastName;
209         personMap.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId );
210         personMap.put(PersonJAXBSchema.DISPLAY_NAME_COMPUTED, "true");
211         personMap.put(PersonJAXBSchema.FORE_NAME, firstName);
212         personMap.put(PersonJAXBSchema.SUR_NAME, lastName);
213         Map<String, List<String>> personRepeatablesMap = new HashMap<String, List<String>>();
214         PoxPayloadOut multipart =
215             PersonAuthorityClientUtils.createPersonInstance(authId, authRefName, 
216                         personMap, personRepeatablesMap, client.getItemCommonPartName() );
217
218         String newID = null;
219         ClientResponse<Response> res = client.createItem(authId, multipart);
220         try {
221             int statusCode = res.getStatus();
222             // Check the status code of the response: does it match
223             // the expected response(s)?
224             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
225                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
226             Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
227
228             newID = PersonAuthorityClientUtils.extractId(res);
229         } finally {
230             res.releaseConnection();
231         }
232
233         // Store the IDs from any item resources created
234         // by tests, along with the IDs of their parents, so these items
235         // can be deleted after all tests have been run.
236         allItemIdsCreated.add(newID);
237     }
238
239     private void createItems()
240         throws Exception {
241         PersonAuthorityClient client = new PersonAuthorityClient();
242         String fullTest = System.getProperty("runFullItemsTest");
243         runFullTest = Boolean.TRUE.toString().equalsIgnoreCase(fullTest); 
244                 int maxSuff = shortTestLimit;
245                 int maxLN = shortTestLimit; 
246         if(runFullTest) {
247             logger.debug("Creating full items set ...");
248                 maxSuff = firstNameSuffixes.length;
249                 maxLN = lastNames.length; 
250         } else {
251             logger.debug("Creating short items set ...");
252         }
253         for(String fname:firstNames) {
254                 for( int iSuff=0; iSuff<maxSuff; iSuff++ ) {
255                         String fns = firstNameSuffixes[iSuff];
256                         for( int iLN=0; iLN<maxLN; iLN++ ) {
257                                 String lname = lastNames[iLN];
258                         createItem(fname+fns, lname, null);
259                 }               
260                 }               
261         }
262         logger.debug("createItems created {} items.", allItemIdsCreated.size());
263     }
264     
265     /**
266      * Reads an item list by partial term.
267      */
268     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
269     public void partialTermMatch(String testName) {
270         if (logger.isDebugEnabled()) {
271             logger.debug(testBanner(testName, CLASS_NAME));
272         }
273         for(int i=0; i<partialTerms.length; i++) {
274                 long startTime = System.currentTimeMillis();
275             int numMatchesFound = readItemListWithFilters(testName, authId, 
276                                                         partialTerms[i], null);
277             Assert.assertEquals(numMatchesFound, (runFullTest?nMatches[i]:nMatchesShort[i]), 
278                 "Did not get expected number of partial term matches for "+partialTerms[i]);
279                 long stopTime = System.currentTimeMillis();
280                 double runTime = (stopTime - startTime)/1000.0;
281             if(logger.isInfoEnabled()){
282                 logger.info("Got: "+numMatchesFound+
283                                 " matches for: \""+partialTerms[i]+"\" in "+
284                                 runTime+" seconds.");
285             }
286         }
287     }
288
289     /**
290      * Reads an item list by partial term or keywords, given an authority and a term.
291      * Only one of partialTerm or keywords should be specified. 
292      * If both are specified, keywords will be ignored.
293      * 
294      * @param testName Calling test name
295      * @param authorityCsid The CSID of the authority within which partial term matching
296      *     will be performed.
297      * @param partialTerm A partial term to match item resources.
298      * @param partialTerm A keyword list to match item resources.
299      * @return The number of item resources matched by the partial term.
300      */
301     private int readItemListWithFilters(String testName, 
302                 String authorityCsid, String partialTerm, String keywords) {
303
304         // Perform setup.
305         int expectedStatusCode = Response.Status.OK.getStatusCode();
306         ServiceRequestType requestType = ServiceRequestType.READ_LIST;
307         testSetup(expectedStatusCode, requestType);
308
309         // Submit the request to the service and store the response.
310         PersonAuthorityClient client = new PersonAuthorityClient();
311         ClientResponse<PersonsCommonList> res = null;
312         if (authorityCsid != null) {
313                 res = client.readItemList(authorityCsid, partialTerm, keywords);
314         } else {
315             Assert.fail(testName+" passed null csid!");
316         }
317         PersonsCommonList list = null;
318         try {
319             int statusCode = res.getStatus();
320             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
321                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
322             Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
323
324             list = res.getEntity();
325         } finally {
326             res.releaseConnection();
327         }
328
329         List<PersonsCommonList.PersonListItem> items = list.getPersonListItem();
330         return (int)list.getTotalItems();
331     }
332     // ---------------------------------------------------------------
333     // Utility methods used by tests above
334     // ---------------------------------------------------------------
335     /**
336      * Deletes all resources created by tests, after all tests have been run.
337      *
338      * This cleanup method will always be run, even if one or more tests fail.
339      * For this reason, it attempts to remove all resources created
340      * at any point during testing, even if some of those resources
341      * may be expected to be deleted by certain tests.
342      */
343     @AfterClass(alwaysRun=true)
344     public void cleanUp() {
345         String noTest = System.getProperty("noTestCleanup");
346         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
347             if (logger.isDebugEnabled()) {
348                 logger.debug("Skipping Cleanup phase ...");
349             }
350             return;
351         }
352         // Note: Any non-success responses from the delete operations
353         // below are ignored and not reported.
354         PersonAuthorityClient client = new PersonAuthorityClient();
355         // Clean up item resources.
356         for (String itemId : allItemIdsCreated) {
357             client.deleteItem(authId, itemId).releaseConnection();
358         }
359         client.delete(authId).releaseConnection();
360     }
361
362
363 }