]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
63f093412c94f631221467cf6cfb4be288f1cd82
[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.PlaceJAXBSchema;
33 import org.collectionspace.services.client.AbstractCommonListUtils;
34 import org.collectionspace.services.client.AuthorityClient;
35 import org.collectionspace.services.client.CollectionSpaceClient;
36 import org.collectionspace.services.client.PayloadOutputPart;
37 import org.collectionspace.services.client.PoxPayloadIn;
38 import org.collectionspace.services.client.PoxPayloadOut;
39 import org.collectionspace.services.client.PlaceAuthorityClient;
40 import org.collectionspace.services.client.PlaceAuthorityClientUtils;
41 import org.collectionspace.services.jaxb.AbstractCommonList;
42 import org.collectionspace.services.place.PlaceTermGroup;
43 import org.collectionspace.services.place.PlaceTermGroupList;
44 import org.collectionspace.services.place.PlaceauthoritiesCommon;
45 import org.collectionspace.services.place.PlacesCommon;
46
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 /**
54  * PlaceAuthorityServiceTest, carries out tests against a
55  * deployed and running PlaceAuthority Service.
56  *
57  * $LastChangedRevision: 753 $
58  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
59  */
60 public class PlaceAuthorityServiceTest extends AbstractAuthorityServiceTest<PlaceauthoritiesCommon, PlacesCommon> {
61
62     /** The logger. */
63     private final String CLASS_NAME = PlaceAuthorityServiceTest.class.getName();
64     private final Logger logger = LoggerFactory.getLogger(PlaceAuthorityServiceTest.class);
65
66         @Override
67         public String getServicePathComponent() {
68                 return PlaceAuthorityClient.SERVICE_PATH_COMPONENT;
69         }
70
71         @Override
72         protected String getServiceName() {
73                 return PlaceAuthorityClient.SERVICE_NAME;
74         }
75     
76     public String getItemServicePathComponent() {
77         return AuthorityClient.ITEMS;
78     }   
79     
80     // Instance variables specific to this test.
81     
82 //    /** The SERVICE path component. */
83 //    final String SERVICE_PATH_COMPONENT = "placeauthorities";
84 //    
85 //    /** The ITEM service path component. */
86 //    final String ITEM_SERVICE_PATH_COMPONENT = "items";
87 //    
88     
89     final String TEST_DNAME = "San Jose, CA";
90     final String TEST_NAME = "San Jose";
91     final String TEST_SHORTID = "sanjose";
92     // TODO Make place type be a controlled vocab term.
93     final String TEST_PLACE_TYPE = "City";
94     // TODO Make status type be a controlled vocab term.
95     final String TEST_STATUS = "Approved";
96     final String TEST_NOTE = "My hometown";
97     final String TEST_SOURCE = "Peralta's Places of California";
98     final String TEST_SOURCE_PAGE = "p.21";
99     final String TEST_DISPLAY_DATE = "This year";
100     final String TEST_EARLIEST_SINGLE_YEAR = "2012";
101     
102     /** The known resource id. */
103     private String knownResourceShortIdentifer = null;
104     private String knownResourceRefName = null;
105     private String knownPlaceTypeRefName = null;
106     
107     /* (non-Javadoc)
108      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
109      */
110     @Override
111     protected CollectionSpaceClient getClientInstance() {
112         return new PlaceAuthorityClient();
113     }
114
115         @Override
116         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
117         return new PlaceAuthorityClient(clientPropertiesFilename);
118         }
119         
120         /**
121      * Creates the item in authority.
122      *
123      * @param vcsid the vcsid
124      * @param authRefName the auth ref name
125      * @return the string
126      */
127     private String createItemInAuthority(AuthorityClient client, String vcsid, String authRefName) {
128         final String testName = "createItemInAuthority("+vcsid+","+authRefName+")"; 
129     
130         // Submit the request to the service and store the response.
131         Map<String, String> sanjoseMap = new HashMap<String,String>();
132         // TODO Make place type and status be controlled vocabs.
133         sanjoseMap.put(PlaceJAXBSchema.SHORT_IDENTIFIER, TEST_SHORTID);
134         sanjoseMap.put(PlaceJAXBSchema.PLACE_TYPE, TEST_PLACE_TYPE);
135         sanjoseMap.put(PlaceJAXBSchema.NOTE, TEST_NOTE);
136         
137         List<PlaceTermGroup> terms = new ArrayList<PlaceTermGroup>();
138         PlaceTermGroup term = new PlaceTermGroup();
139         term.setTermDisplayName(TEST_DNAME);
140         term.setTermName(TEST_NAME);
141         term.setTermSource(TEST_SOURCE);
142         term.setTermSourceDetail(TEST_SOURCE_PAGE);
143         term.setTermStatus(TEST_STATUS);
144         terms.add(term);
145         
146         String newID = PlaceAuthorityClientUtils.createItemInAuthority(vcsid,
147                         authRefName, sanjoseMap, terms, (PlaceAuthorityClient) client);    
148
149         // Store the ID returned from the first item resource created
150         // for additional tests below.
151         if (knownItemResourceId == null){
152                 setKnownItemResource(newID, TEST_SHORTID);
153             if (logger.isDebugEnabled()) {
154                 logger.debug(testName + ": knownItemResourceId=" + newID);
155             }
156         }
157         
158         // Store the IDs from any item resources created
159         // by tests, along with the IDs of their parents, so these items
160         // can be deleted after all tests have been run.
161         allResourceItemIdsCreated.put(newID, vcsid);
162
163         return newID;
164     }
165
166     /**
167      * Verify illegal item display name.
168      *
169      * @param testName the test name
170      * @throws Exception the exception
171      */
172     @Test(dataProvider="testName")
173     public void verifyIllegalItemDisplayName(String testName) throws Exception {
174         // Perform setup for read.
175         setupRead();
176
177         // Submit the request to the service and store the response.
178         PlaceAuthorityClient client = new PlaceAuthorityClient();
179         Response res = client.readItem(knownResourceId, knownItemResourceId);
180         PlacesCommon place= null;
181         try {
182             assertStatusCode(res, testName);        
183                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
184                 place = (PlacesCommon) extractPart(input,
185                         client.getItemCommonPartName(), PlacesCommon.class);
186                 Assert.assertNotNull(place);
187             } finally {
188                 if (res != null) {
189                 res.close();
190             }
191         }
192
193         //
194         // Make an invalid UPDATE request, without a display name
195         //
196         PlaceTermGroupList termList = place.getPlaceTermGroupList();
197         Assert.assertNotNull(termList);
198         List<PlaceTermGroup> terms = termList.getPlaceTermGroup();
199         Assert.assertNotNull(terms);
200         Assert.assertTrue(terms.size() > 0);
201         terms.get(0).setTermDisplayName(null);
202         terms.get(0).setTermName(null);
203         
204         setupUpdateWithInvalidBody(); // we expect a failure
205         
206         // Submit the updated resource to the service and store the response.
207         PoxPayloadOut output = new PoxPayloadOut(PlaceAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
208         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), place);
209         setupUpdateWithInvalidBody(); // we expected a failure here.
210         res = client.updateItem(knownResourceId, knownItemResourceId, output);
211         try {
212                 assertStatusCode(res, testName);
213         } finally {
214                 if (res != null) {
215                 res.close();
216             }
217         }
218     }
219
220     /**
221      * Read item list.
222      */
223     @Test(dataProvider = "testName", groups = {"readList"},
224                dependsOnMethods = {"readList"})
225     public void readItemList(String testName) {
226         readItemList(knownAuthorityWithItems, null);
227     }
228
229     /**
230      * Read item list by authority name.
231      */
232     @Test(dataProvider = "testName", groups = {"readList"},
233                 dependsOnMethods = {"readItemList"})
234     public void readItemListByAuthorityName(String testName) {
235         readItemList(null, READITEMS_SHORT_IDENTIFIER);
236     }
237     
238         /**
239          * Read item list.
240          * 
241          * @param vcsid
242          *            the vcsid
243          * @param name
244          *            the name
245          */
246         private void readItemList(String vcsid, String shortId) {
247                 String testName = "readItemList";
248
249                 // Perform setup.
250                 setupReadList();
251
252                 // Submit the request to the service and store the response.
253                 PlaceAuthorityClient client = new PlaceAuthorityClient();
254                 Response res = null;
255                 if (vcsid != null) {
256                         res = client.readItemList(vcsid, null, null);
257                 } else if (shortId != null) {
258                         res = client.readItemListForNamedAuthority(shortId, null, null);
259                 } else {
260                         Assert.fail("readItemList passed null csid and name!");
261                 }
262                 
263                 AbstractCommonList list = null;
264                 try {
265                         assertStatusCode(res, testName);
266                         list = res.readEntity(AbstractCommonList.class);
267                 } finally {
268                         if (res != null) {
269                 res.close();
270             }
271                 }
272                 
273                 List<AbstractCommonList.ListItem> items = list.getListItem();
274                 int nItemsReturned = items.size();
275                 // There will be 'nItemsToCreateInList'
276                 // items created by the createItemList test,
277                 // all associated with the same parent resource.
278                 int nExpectedItems = nItemsToCreateInList;
279                 if (logger.isDebugEnabled()) {
280                         logger.debug(testName + ": Expected " + nExpectedItems
281                                         + " items; got: " + nItemsReturned);
282                 }
283                 Assert.assertEquals(nItemsReturned, nExpectedItems);
284
285                 for (AbstractCommonList.ListItem item : items) {
286                         String value = AbstractCommonListUtils.ListItemGetElementValue(
287                                         item, PlaceJAXBSchema.REF_NAME);
288                         Assert.assertTrue((null != value), "Item refName is null!");
289                         value = AbstractCommonListUtils.ListItemGetElementValue(item,
290                                         PlaceJAXBSchema.TERM_DISPLAY_NAME);
291                         Assert.assertTrue((null != value), "Item termDisplayName is null!");
292                 }
293                 if (logger.isTraceEnabled()) {
294                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger,
295                                         testName);
296                 }
297         }
298
299     @Override
300     public void delete(String testName) throws Exception {
301         // Do nothing.  See localDelete().  This ensure proper test order.
302     }
303     
304     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
305     public void localDelete(String testName) throws Exception {
306         super.delete(testName);
307     }
308
309     @Override
310     public void deleteItem(String testName) throws Exception {
311         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
312         // its dependencies will get run first and then we can call the base class' delete method.
313     }
314     
315     @Test(dataProvider = "testName", groups = {"delete"},
316         dependsOnMethods = {"verifyIllegalItemDisplayName"})
317     public void localDeleteItem(String testName) throws Exception {
318         super.deleteItem(testName);
319     }
320     
321     // ---------------------------------------------------------------
322     // Cleanup of resources created during testing
323     // ---------------------------------------------------------------
324     
325     /**
326      * Deletes all resources created by tests, after all tests have been run.
327      *
328      * This cleanup method will always be run, even if one or more tests fail.
329      * For this reason, it attempts to remove all resources created
330      * at any point during testing, even if some of those resources
331      * may be expected to be deleted by certain tests.
332      */
333
334     @AfterClass(alwaysRun=true)
335     public void cleanUp() {
336         String noTest = System.getProperty("noTestCleanup");
337         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
338             if (logger.isDebugEnabled()) {
339                 logger.debug("Skipping Cleanup phase ...");
340             }
341             return;
342         }
343         if (logger.isDebugEnabled()) {
344             logger.debug("Cleaning up temporary resources created for testing ...");
345         }
346         String parentResourceId;
347         String itemResourceId;
348         // Clean up contact resources.
349         PlaceAuthorityClient client = new PlaceAuthorityClient();
350         parentResourceId = knownResourceId;
351         // Clean up item resources.
352         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
353             itemResourceId = entry.getKey();
354             parentResourceId = entry.getValue();
355             // Note: Any non-success responses from the delete operation
356             // below are ignored and not reported.
357             client.deleteItem(parentResourceId, itemResourceId).close();
358         }
359         // Clean up parent resources.
360         for (String resourceId : allResourceIdsCreated) {
361             // Note: Any non-success responses from the delete operation
362             // below are ignored and not reported.
363             client.delete(resourceId).close();
364         }
365     }
366
367     // ---------------------------------------------------------------
368     // Utility methods used by tests above
369     // ---------------------------------------------------------------
370     /* (non-Javadoc)
371      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
372      */
373
374     /**
375      * Returns the root URL for the item service.
376      *
377      * This URL consists of a base URL for all services, followed by
378      * a path component for the owning parent, followed by the
379      * path component for the items.
380      *
381      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
382      * parent authority resource of the relevant item resource.
383      *
384      * @return The root URL for the item service.
385      */
386     protected String getItemServiceRootURL(String parentResourceIdentifier) {
387         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
388     }
389
390     /**
391      * Returns the URL of a specific item resource managed by a service, and
392      * designated by an identifier (such as a universally unique ID, or UUID).
393      *
394      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
395      * parent authority resource of the relevant item resource.
396      *
397      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
398      * item resource.
399      *
400      * @return The URL of a specific item resource managed by a service.
401      */
402     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
403         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
404     }
405
406         @Override
407         public void authorityTests(String testName) {
408                 // TODO Auto-generated method stub
409                 
410         }
411
412         //
413         // Place specific overrides
414         //
415         
416         @Override
417         protected PoxPayloadOut createInstance(String commonPartName,
418                         String identifier) {
419         // Submit the request to the service and store the response.
420         String shortId = identifier;
421         String displayName = "displayName-" + shortId;
422         // String baseRefName = PlaceAuthorityClientUtils.createPlaceAuthRefName(shortId, null);        
423         PoxPayloadOut result = 
424             PlaceAuthorityClientUtils.createPlaceAuthorityInstance(
425             displayName, shortId, commonPartName);
426                 return result;
427         }
428         
429         @Override
430     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
431         String displayName = "displayName-NON_EXISTENT_ID";
432         PoxPayloadOut result = PlaceAuthorityClientUtils.createPlaceAuthorityInstance(
433                                 displayName, "nonEx", commonPartName);
434         return result;
435     }
436
437         @Override
438         protected PlaceauthoritiesCommon updateInstance(PlaceauthoritiesCommon placeauthoritiesCommon) {
439                 PlaceauthoritiesCommon result = new PlaceauthoritiesCommon();
440                 
441                 result.setDisplayName("updated-" + placeauthoritiesCommon.getDisplayName());
442                 result.setVocabType("updated-" + placeauthoritiesCommon.getVocabType());
443                 
444                 return result;
445         }
446
447         @Override
448         protected void compareUpdatedInstances(PlaceauthoritiesCommon original,
449                         PlaceauthoritiesCommon updated) throws Exception {
450         Assert.assertEquals(updated.getDisplayName(),
451                         original.getDisplayName(),
452                 "Display name in updated object did not match submitted data.");
453         }
454
455         protected void compareReadInstances(PlaceauthoritiesCommon original,
456                         PlaceauthoritiesCommon fromRead) throws Exception {
457         Assert.assertNotNull(fromRead.getDisplayName());
458         Assert.assertNotNull(fromRead.getShortIdentifier());
459         Assert.assertNotNull(fromRead.getRefName());
460         }
461         
462         //
463         // Authority item specific overrides
464         //
465         
466         @Override
467         protected String createItemInAuthority(AuthorityClient client, String authorityId) {
468                 return createItemInAuthority(client, authorityId, null /*refname*/);
469         }
470
471         @Override
472         protected PlacesCommon updateItemInstance(PlacesCommon placesCommon) {
473                             
474             PlaceTermGroupList termList = placesCommon.getPlaceTermGroupList();
475             Assert.assertNotNull(termList);
476             List<PlaceTermGroup> terms = termList.getPlaceTermGroup();
477             Assert.assertNotNull(terms);
478             Assert.assertTrue(terms.size() > 0);
479             terms.get(0).setTermDisplayName("updated-" + terms.get(0).getTermDisplayName());
480             terms.get(0).setTermName("updated-" + terms.get(0).getTermName());
481             placesCommon.setPlaceTermGroupList(termList);
482
483             return placesCommon;
484         }
485
486         @Override
487         protected void compareUpdatedItemInstances(PlacesCommon original,
488                         PlacesCommon updated) throws Exception {
489             
490             PlaceTermGroupList originalTermList = original.getPlaceTermGroupList();
491             Assert.assertNotNull(originalTermList);
492             List<PlaceTermGroup> originalTerms = originalTermList.getPlaceTermGroup();
493             Assert.assertNotNull(originalTerms);
494             Assert.assertTrue(originalTerms.size() > 0);
495             
496             PlaceTermGroupList updatedTermList = updated.getPlaceTermGroupList();
497             Assert.assertNotNull(updatedTermList);
498             List<PlaceTermGroup> updatedTerms = updatedTermList.getPlaceTermGroup();
499             Assert.assertNotNull(updatedTerms);
500             Assert.assertTrue(updatedTerms.size() > 0);
501             
502             Assert.assertEquals(updatedTerms.get(0).getTermDisplayName(),
503                 originalTerms.get(0).getTermDisplayName(),
504                 "Value in updated record did not match submitted data.");
505         }
506
507         @Override
508         protected void verifyReadItemInstance(PlacesCommon item)
509                         throws Exception {
510                 // TODO Auto-generated method stub
511                 
512         }
513
514         @Override
515         protected PoxPayloadOut createNonExistenceItemInstance(
516                         String commonPartName, String identifier) {
517         Map<String, String> nonexMap = new HashMap<String,String>();
518         nonexMap.put(PlaceJAXBSchema.PLACE_NAME, TEST_NAME);
519         nonexMap.put(PlaceJAXBSchema.SHORT_IDENTIFIER, "nonEx");
520         nonexMap.put(PlaceJAXBSchema.PLACE_TYPE, TEST_PLACE_TYPE);
521         final String EMPTY_REFNAME = "";
522         PoxPayloadOut result = 
523                 PlaceAuthorityClientUtils.createPlaceInstance(EMPTY_REFNAME, 
524                         nonexMap, PlaceAuthorityClientUtils.getTermGroupInstance(TEST_NAME), commonPartName);
525                 return result;
526         }
527
528 }