]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
0e6ed24524eb6e8d0c7ef72ad7c6bc54850dd473
[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
38 import org.jboss.resteasy.client.ClientResponse;
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() {
110         return new PersonAuthorityClient();
111     }
112     
113     /* (non-Javadoc)
114      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
115      */
116     @Override
117         protected AbstractCommonList getCommonList(
118                         ClientResponse<AbstractCommonList> response) {
119         return response.getEntity(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         ClientResponse<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.releaseConnection();
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         personMap.put(PersonJAXBSchema.DISPLAY_NAME_COMPUTED, "true");
207         personMap.put(PersonJAXBSchema.FORE_NAME, firstName);
208         personMap.put(PersonJAXBSchema.SUR_NAME, lastName);
209         Map<String, List<String>> personRepeatablesMap = new HashMap<String, List<String>>();
210         PoxPayloadOut multipart =
211             PersonAuthorityClientUtils.createPersonInstance(authId, null, //authRefName, 
212                         personMap, personRepeatablesMap, client.getItemCommonPartName() );
213
214         String newID = null;
215         ClientResponse<Response> res = client.createItem(authId, multipart);
216         try {
217             assertStatusCode(res, "createItem");
218             newID = PersonAuthorityClientUtils.extractId(res);
219         } finally {
220                 if (res != null) {
221                 res.releaseConnection();
222             }
223         }
224
225         // Store the IDs from any item resources created
226         // by tests, along with the IDs of their parents, so these items
227         // can be deleted after all tests have been run.
228         allItemIdsCreated.add(newID);
229     }
230
231     private void createItems()
232         throws Exception {
233         PersonAuthorityClient client = new PersonAuthorityClient();
234         String fullTest = System.getProperty("runFullItemsTest");
235         runFullTest = Boolean.TRUE.toString().equalsIgnoreCase(fullTest); 
236                 int maxSuff = shortTestLimit;
237                 int maxLN = shortTestLimit; 
238         if(runFullTest) {
239             logger.debug("Creating full items set ...");
240                 maxSuff = firstNameSuffixes.length;
241                 maxLN = lastNames.length; 
242         } else {
243             logger.debug("Creating short items set ...");
244         }
245         for(String fname:firstNames) {
246                 for( int iSuff=0; iSuff<maxSuff; iSuff++ ) {
247                         String fns = firstNameSuffixes[iSuff];
248                         for( int iLN=0; iLN<maxLN; iLN++ ) {
249                                 String lname = lastNames[iLN];
250                         createItem(fname+fns, lname, null);
251                 }               
252                 }               
253         }
254         logger.debug("createItems created {} items.", allItemIdsCreated.size());
255     }
256     
257     /**
258      * Reads an item list by partial term.
259      */
260     @Test(dataProvider="testName")
261     public void partialTermMatch(String testName) {
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<AbstractCommonList> res = null;
301         if (authorityCsid != null) {
302                 res = client.readItemList(authorityCsid, partialTerm, keywords);
303         } else {
304             Assert.fail(testName+" passed null csid!");
305         }
306         AbstractCommonList list = null;
307         try {
308             assertStatusCode(res, testName);
309             list = res.getEntity();
310         } finally {
311                 if (res != null) {
312                 res.releaseConnection();
313             }
314         }
315
316         List<AbstractCommonList.ListItem> items = list.getListItem();
317         return (int)list.getTotalItems();
318     }
319     // ---------------------------------------------------------------
320     // Utility methods used by tests above
321     // ---------------------------------------------------------------
322     /**
323      * Deletes all resources created by tests, after all tests have been run.
324      *
325      * This cleanup method will always be run, even if one or more tests fail.
326      * For this reason, it attempts to remove all resources created
327      * at any point during testing, even if some of those resources
328      * may be expected to be deleted by certain tests.
329      */
330     @AfterClass(alwaysRun=true)
331     public void cleanUp() {
332         String noTest = System.getProperty("noTestCleanup");
333         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
334             if (logger.isDebugEnabled()) {
335                 logger.debug("Skipping Cleanup phase ...");
336             }
337             return;
338         }
339         // Note: Any non-success responses from the delete operations
340         // below are ignored and not reported.
341         PersonAuthorityClient client = new PersonAuthorityClient();
342         // Clean up item resources.
343         for (String itemId : allItemIdsCreated) {
344             client.deleteItem(authId, itemId).releaseConnection();
345         }
346         client.delete(authId).releaseConnection();
347     }
348
349
350 }