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