]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
15200e89aa2b3c03c8b54269b4c202be4201279b
[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
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.PersonAuthorityClient;
35 import org.collectionspace.services.client.PersonAuthorityClientUtils;
36 import org.collectionspace.services.client.PoxPayloadOut;
37 import org.collectionspace.services.jaxb.AbstractCommonList;
38 import org.collectionspace.services.person.PersonTermGroup;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.testng.Assert;
42 import org.testng.annotations.AfterClass;
43 import org.testng.annotations.BeforeClass;
44 import org.testng.annotations.Test;
45
46 /**
47  * VocabularyServiceTest, carries out tests against a
48  * deployed and running Vocabulary Service.
49  *
50  * $LastChangedRevision: 753 $
51  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
52  */
53 public class PersonAuthorityServicePerfTest extends BaseServiceTest<AbstractCommonList> {
54
55     private final String CLASS_NAME = PersonAuthorityServicePerfTest.class.getName();
56     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
57
58     // Instance variables specific to this test.
59 //    final String SERVICE_PATH_COMPONENT = "personauthorities";
60 //    final String ITEM_SERVICE_PATH_COMPONENT = "items";
61     private String authId = null;
62     //private String authRefName = null;
63     private List<String> allItemIdsCreated = new ArrayList<String>();
64     private String[] firstNames = { 
65                 "Ann","Anne","Anno",
66                 "George","Geoff","Georgia",
67                 "John","Johanna","Jon",
68                 "Patrick","Patty","Patrik"};
69     private String[] firstNameSuffixes = { 
70                 "1","2","3","4","5","6","7","8","9","0"};
71     private String[] lastNames = { 
72                 "Axis","Black","Cobbler",
73                 "Dunne","England","France",
74                 "Goldsmith","Hart","Indy",
75                 "Jones","Kohn","Lark",
76                 "Maven","Newhart","Overdunne",
77                 "Plaxo","Queen","Roberts",
78                 "Smith","Tate","Underdunne",
79                 "Vicious","Waits","Xavier",
80                 "Yeats","Zoolander"};
81     
82     // Keep these two arrays in sync!!!
83     private String[] partialTerms = {"Ann","John","Patty2"};
84     private int[] nMatches = {
85                 4*lastNames.length*firstNameSuffixes.length, // Johanna too!
86                     lastNames.length*firstNameSuffixes.length,
87                     lastNames.length, };
88     private int shortTestLimit = 2; // Just use first three items in suffix and last name arrays
89     private int[] nMatchesShort = {
90                 4*shortTestLimit*shortTestLimit, // Johanna too!
91                 shortTestLimit*shortTestLimit,
92                 shortTestLimit, };
93     private boolean runFullTest = false;
94     
95         @Override
96         public String getServicePathComponent() {
97                 return PersonAuthorityClient.SERVICE_PATH_COMPONENT;
98         }
99
100         @Override
101         protected String getServiceName() {
102                 return PersonAuthorityClient.SERVICE_NAME;
103         }
104     
105     /* (non-Javadoc)
106      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
107      */
108     @Override
109     protected CollectionSpaceClient getClientInstance() throws Exception {
110         return new PersonAuthorityClient();
111     }
112
113         @Override
114         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) throws Exception {
115         return new PersonAuthorityClient(clientPropertiesFilename);
116         }
117
118     /* (non-Javadoc)
119      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
120      */
121     @Override
122         protected AbstractCommonList getCommonList(Response response) {
123         return response.readEntity(AbstractCommonList.class);
124     }
125  
126     @BeforeClass
127     public void setup() {
128         try {
129             createAuthority();
130         } catch (Exception e) {
131             Assert.fail("Could not create new Authority for search tests.", e);
132         }
133         try {
134                 long startTime = System.currentTimeMillis();
135             createItems();
136                 long stopTime = System.currentTimeMillis();
137                 double runTime = (stopTime - startTime)/1000.0;
138                 logger.info("Created {} items in {} seconds.", 
139                                         allItemIdsCreated.size(), runTime);
140         } catch (Exception e) {
141             Assert.fail("Could not create new item in Authority for search tests.", e);
142         }
143     }
144  
145     // ---------------------------------------------------------------
146     // Utilities: setup routines for search tests
147     // ---------------------------------------------------------------
148
149     public void createAuthority() throws Exception {
150
151         String testName = "createAuthority";
152
153         // Perform setup.
154         int expectedStatusCode = Response.Status.CREATED.getStatusCode();
155         ServiceRequestType requestType = ServiceRequestType.CREATE;
156         testSetup(expectedStatusCode, requestType);
157
158         // Submit the request to the service and store the response.
159         PersonAuthorityClient client = new PersonAuthorityClient();
160         String shortId = "perfTestPersons";
161         String displayName = "Perf Test Person Auth";
162         //String baseRefName = PersonAuthorityClientUtils.createPersonAuthRefName(shortId, null);
163         PoxPayloadOut multipart =
164             PersonAuthorityClientUtils.createPersonAuthorityInstance(
165             displayName, shortId, client.getCommonPartName());
166
167         String newID = null;
168         Response res = client.create(multipart);
169         try {
170             assertStatusCode(res, testName);
171             newID = PersonAuthorityClientUtils.extractId(res);
172             logger.info("{}: succeeded.", testName);
173         } finally {
174                 if (res != null) {
175                 res.close();
176             }
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         
211         List<PersonTermGroup> terms = new ArrayList<PersonTermGroup>();
212         PersonTermGroup term = new PersonTermGroup();
213         term.setTermDisplayName(firstName + " " + lastName);
214         term.setTermName(firstName + " " + lastName);
215         term.setForeName(firstName);
216         term.setSurName(lastName);
217         terms.add(term);
218         
219         Map<String, List<String>> personRepeatablesMap = new HashMap<String, List<String>>();
220         PoxPayloadOut multipart =
221             PersonAuthorityClientUtils.createPersonInstance(authId, null, //authRefName, 
222                         personMap, terms, personRepeatablesMap, client.getItemCommonPartName() );
223
224         String newID = null;
225         Response res = client.createItem(authId, multipart);
226         try {
227             assertStatusCode(res, "createItem");
228             newID = PersonAuthorityClientUtils.extractId(res);
229         } finally {
230                 if (res != null) {
231                 res.close();
232             }
233         }
234
235         // Store the IDs from any item resources created
236         // by tests, along with the IDs of their parents, so these items
237         // can be deleted after all tests have been run.
238         allItemIdsCreated.add(newID);
239     }
240
241     private void createItems()
242         throws Exception {
243         PersonAuthorityClient client = new PersonAuthorityClient();
244         String fullTest = System.getProperty("runFullItemsTest");
245         runFullTest = Boolean.TRUE.toString().equalsIgnoreCase(fullTest); 
246                 int maxSuff = shortTestLimit;
247                 int maxLN = shortTestLimit; 
248         if(runFullTest) {
249             logger.debug("Creating full items set ...");
250                 maxSuff = firstNameSuffixes.length;
251                 maxLN = lastNames.length; 
252         } else {
253             logger.debug("Creating short items set ...");
254         }
255         for(String fname:firstNames) {
256                 for( int iSuff=0; iSuff<maxSuff; iSuff++ ) {
257                         String fns = firstNameSuffixes[iSuff];
258                         for( int iLN=0; iLN<maxLN; iLN++ ) {
259                                 String lname = lastNames[iLN];
260                         createItem(fname+fns, lname, null);
261                 }               
262                 }               
263         }
264         logger.debug("createItems created {} items.", allItemIdsCreated.size());
265     }
266     
267     /**
268      * Reads an item list by partial term.
269      * @throws Exception 
270      */
271     @Test(dataProvider="testName")
272     public void partialTermMatch(String testName) throws Exception {
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      * @throws Exception 
301      */
302     private int readItemListWithFilters(String testName, 
303                 String authorityCsid, String partialTerm, String keywords) throws Exception {
304
305         // Perform setup.
306         int expectedStatusCode = Response.Status.OK.getStatusCode();
307         ServiceRequestType requestType = ServiceRequestType.READ_LIST;
308         testSetup(expectedStatusCode, requestType);
309
310         // Submit the request to the service and store the response.
311         PersonAuthorityClient client = new PersonAuthorityClient();
312         Response res = null;
313         if (authorityCsid != null) {
314                 res = client.readItemList(authorityCsid, partialTerm, keywords);
315         } else {
316             Assert.fail(testName+" passed null csid!");
317         }
318         AbstractCommonList list = null;
319         try {
320             assertStatusCode(res, testName);
321             list = res.readEntity(AbstractCommonList.class);
322         } finally {
323                 if (res != null) {
324                 res.close();
325             }
326         }
327
328         List<AbstractCommonList.ListItem> items = list.getListItem();
329         return (int)list.getTotalItems();
330     }
331     // ---------------------------------------------------------------
332     // Utility methods used by tests above
333     // ---------------------------------------------------------------
334     /**
335      * Deletes all resources created by tests, after all tests have been run.
336      *
337      * This cleanup method will always be run, even if one or more tests fail.
338      * For this reason, it attempts to remove all resources created
339      * at any point during testing, even if some of those resources
340      * may be expected to be deleted by certain tests.
341      * @throws Exception 
342      */
343     @AfterClass(alwaysRun=true)
344     public void cleanUp() throws Exception {
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).close();
358         }
359         client.delete(authId).close();
360     }
361 }