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