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