]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7fcb806ad4fbf237aa935d397c86c75ca5c4b933
[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.jaxb.AbstractCommonList;
36 import org.collectionspace.services.person.PersonsCommonList;
37
38 import org.jboss.resteasy.client.ClientResponse;
39 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
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     /* (non-Javadoc)
97      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
98      */
99     @Override
100     protected CollectionSpaceClient getClientInstance() {
101         return new PersonAuthorityClient();
102     }
103     
104     /* (non-Javadoc)
105      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
106      */
107     @Override
108         protected AbstractCommonList getAbstractCommonList(
109                         ClientResponse<AbstractCommonList> response) {
110         return response.getEntity(PersonsCommonList.class);
111     }
112  
113     @BeforeClass
114     public void setup() {
115         try {
116             createAuthority();
117         } catch (Exception e) {
118             Assert.fail("Could not create new Authority for search tests.", e);
119         }
120         try {
121                 long startTime = System.currentTimeMillis();
122             createItems();
123                 long stopTime = System.currentTimeMillis();
124                 double runTime = (stopTime - startTime)/1000.0;
125                 logger.info("Created {} items in {} seconds.", 
126                                         allItemIdsCreated.size(), runTime);
127         } catch (Exception e) {
128             Assert.fail("Could not create new item in Authority for search tests.", e);
129         }
130     }
131  
132     // ---------------------------------------------------------------
133     // Utilities: setup routines for search tests
134     // ---------------------------------------------------------------
135
136     public void createAuthority() throws Exception {
137
138         String testName = "createAuthority";
139
140         // Perform setup.
141         int expectedStatusCode = Response.Status.CREATED.getStatusCode();
142         ServiceRequestType requestType = ServiceRequestType.CREATE;
143         testSetup(expectedStatusCode, requestType);
144
145         // Submit the request to the service and store the response.
146         PersonAuthorityClient client = new PersonAuthorityClient();
147         String shortId = "perfTestPersons";
148         String displayName = "Perf Test Person Auth";
149         String baseRefName = PersonAuthorityClientUtils.createPersonAuthRefName(shortId, null);
150         MultipartOutput multipart =
151             PersonAuthorityClientUtils.createPersonAuthorityInstance(
152             displayName, shortId, client.getCommonPartName());
153
154         String newID = null;
155         ClientResponse<Response> res = client.create(multipart);
156         try {
157             int statusCode = res.getStatus();
158             // Check the status code of the response: does it match
159             // the expected response(s)?
160             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
161                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
162             Assert.assertEquals(statusCode, this.EXPECTED_STATUS_CODE);
163             newID = PersonAuthorityClientUtils.extractId(res);
164             logger.info("{}: succeeded.", testName);
165         } finally {
166             res.releaseConnection();
167         }
168         // Store the refname from the first resource created
169         // for additional tests below.
170         authRefName = baseRefName;
171         // Store the ID returned from the first resource created
172         // for additional tests below.
173         authId = newID;
174     }
175
176     /**
177      * Creates an item in the authority, used for partial term matching tests.
178      *
179      * @param authorityCsid The CSID of the Authority in which the term will be created.
180      * @param authRefName The refName of the Authority in which the term will be created.
181      */
182     private void createItem(String firstName, String lastName, PersonAuthorityClient client )
183         throws Exception {
184             
185         int expectedStatusCode = Response.Status.CREATED.getStatusCode();
186         ServiceRequestType requestType = ServiceRequestType.CREATE;
187         testSetup(expectedStatusCode, requestType);
188         
189         if(client==null) {
190             client = new PersonAuthorityClient();
191         }
192
193         // Submit the request to the service and store the response.
194         Map<String, String> personMap = new HashMap<String,String>();
195         //
196         // Fill the property map
197         //
198         String shortId = firstName+lastName;
199         personMap.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId );
200         personMap.put(PersonJAXBSchema.DISPLAY_NAME_COMPUTED, "true");
201         personMap.put(PersonJAXBSchema.FORE_NAME, firstName);
202         personMap.put(PersonJAXBSchema.SUR_NAME, lastName);
203         MultipartOutput multipart =
204             PersonAuthorityClientUtils.createPersonInstance(authId, authRefName, 
205                         personMap, client.getItemCommonPartName() );
206
207         String newID = null;
208         ClientResponse<Response> res = client.createItem(authId, multipart);
209         try {
210             int statusCode = res.getStatus();
211             // Check the status code of the response: does it match
212             // the expected response(s)?
213             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
214                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
215             Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
216
217             newID = PersonAuthorityClientUtils.extractId(res);
218         } finally {
219             res.releaseConnection();
220         }
221
222         // Store the IDs from any item resources created
223         // by tests, along with the IDs of their parents, so these items
224         // can be deleted after all tests have been run.
225         allItemIdsCreated.add(newID);
226     }
227
228     private void createItems()
229         throws Exception {
230         PersonAuthorityClient client = new PersonAuthorityClient();
231         String fullTest = System.getProperty("runFullItemsTest");
232         runFullTest = Boolean.TRUE.toString().equalsIgnoreCase(fullTest); 
233                 int maxSuff = shortTestLimit;
234                 int maxLN = shortTestLimit; 
235         if(runFullTest) {
236             logger.debug("Creating full items set ...");
237                 maxSuff = firstNameSuffixes.length;
238                 maxLN = lastNames.length; 
239         } else {
240             logger.debug("Creating short items set ...");
241         }
242         for(String fname:firstNames) {
243                 for( int iSuff=0; iSuff<maxSuff; iSuff++ ) {
244                         String fns = firstNameSuffixes[iSuff];
245                         for( int iLN=0; iLN<maxLN; iLN++ ) {
246                                 String lname = lastNames[iLN];
247                         createItem(fname+fns, lname, null);
248                 }               
249                 }               
250         }
251         logger.debug("createItems created {} items.", allItemIdsCreated.size());
252     }
253     
254     /**
255      * Reads an item list by partial term.
256      */
257     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
258     public void partialTermMatch(String testName) {
259         if (logger.isDebugEnabled()) {
260             logger.debug(testBanner(testName, CLASS_NAME));
261         }
262         for(int i=0; i<partialTerms.length; i++) {
263                 long startTime = System.currentTimeMillis();
264             int numMatchesFound = readItemListWithFilters(testName, authId, 
265                                                         partialTerms[i], null);
266             Assert.assertEquals(numMatchesFound, (runFullTest?nMatches[i]:nMatchesShort[i]), 
267                 "Did not get expected number of partial term matches for "+partialTerms[i]);
268                 long stopTime = System.currentTimeMillis();
269                 double runTime = (stopTime - startTime)/1000.0;
270             if(logger.isInfoEnabled()){
271                 logger.info("Got: "+numMatchesFound+
272                                 " matches for: \""+partialTerms[i]+"\" in "+
273                                 runTime+" seconds.");
274             }
275         }
276     }
277
278     /**
279      * Reads an item list by partial term or keywords, given an authority and a term.
280      * Only one of partialTerm or keywords should be specified. 
281      * If both are specified, keywords will be ignored.
282      * 
283      * @param testName Calling test name
284      * @param authorityCsid The CSID of the authority within which partial term matching
285      *     will be performed.
286      * @param partialTerm A partial term to match item resources.
287      * @param partialTerm A keyword list to match item resources.
288      * @return The number of item resources matched by the partial term.
289      */
290     private int readItemListWithFilters(String testName, 
291                 String authorityCsid, String partialTerm, String keywords) {
292
293         // Perform setup.
294         int expectedStatusCode = Response.Status.OK.getStatusCode();
295         ServiceRequestType requestType = ServiceRequestType.READ_LIST;
296         testSetup(expectedStatusCode, requestType);
297
298         // Submit the request to the service and store the response.
299         PersonAuthorityClient client = new PersonAuthorityClient();
300         ClientResponse<PersonsCommonList> res = null;
301         if (authorityCsid != null) {
302                 res = client.readItemList(authorityCsid, partialTerm, keywords);
303         } else {
304             Assert.fail(testName+" passed null csid!");
305         }
306         PersonsCommonList list = null;
307         try {
308             int statusCode = res.getStatus();
309             Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
310                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
311             Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
312
313             list = res.getEntity();
314         } finally {
315             res.releaseConnection();
316         }
317
318         List<PersonsCommonList.PersonListItem> items = list.getPersonListItem();
319         return (int)list.getTotalItems();
320     }
321     // ---------------------------------------------------------------
322     // Utility methods used by tests above
323     // ---------------------------------------------------------------
324     @Override
325     public String getServicePathComponent() {
326         return SERVICE_PATH_COMPONENT;
327     }
328
329     /**
330      * Deletes all resources created by tests, after all tests have been run.
331      *
332      * This cleanup method will always be run, even if one or more tests fail.
333      * For this reason, it attempts to remove all resources created
334      * at any point during testing, even if some of those resources
335      * may be expected to be deleted by certain tests.
336      */
337     @AfterClass(alwaysRun=true)
338     public void cleanUp() {
339         String noTest = System.getProperty("noTestCleanup");
340         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
341             if (logger.isDebugEnabled()) {
342                 logger.debug("Skipping Cleanup phase ...");
343             }
344             return;
345         }
346         // Note: Any non-success responses from the delete operations
347         // below are ignored and not reported.
348         PersonAuthorityClient client = new PersonAuthorityClient();
349         // Clean up item resources.
350         for (String itemId : allItemIdsCreated) {
351             client.deleteItem(authId, itemId).releaseConnection();
352         }
353         client.delete(authId).releaseConnection();
354     }
355
356
357 }