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