]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
c7d66a88ba0bacd5bcec5e1b09c4a8e5a0fcedd4
[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 Logger logger = LoggerFactory.getLogger(PlaceAuthorityServiceTest.class);
64
65     /**
66      * Default constructor.  Used to set the short ID for all tests authority items
67      */
68     public PlaceAuthorityServiceTest() {
69         super();
70         TEST_SHORTID = "sanjose";
71     }
72     
73         @Override
74         public String getServicePathComponent() {
75                 return PlaceAuthorityClient.SERVICE_PATH_COMPONENT;
76         }
77
78         @Override
79         protected String getServiceName() {
80                 return PlaceAuthorityClient.SERVICE_NAME;
81         }
82     
83     public String getItemServicePathComponent() {
84         return AuthorityClient.ITEMS;
85     }   
86     
87     // Instance variables specific to this test.
88         
89     final String TEST_DNAME = "San Jose, CA";
90     final String TEST_NAME = "San Jose";
91     // TODO Make place type be a controlled vocab term.
92     final String TEST_PLACE_TYPE = "City";
93     // TODO Make status type be a controlled vocab term.
94     final String TEST_STATUS = "Approved";
95     final String TEST_NOTE = "My hometown";
96     final String TEST_SOURCE = "Peralta's Places of California";
97     final String TEST_SOURCE_PAGE = "p.21";
98     final String TEST_DISPLAY_DATE = "This year";
99     final String TEST_EARLIEST_SINGLE_YEAR = "2012";
100         
101     /* (non-Javadoc)
102      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
103      */
104     @Override
105     protected CollectionSpaceClient getClientInstance() {
106         return new PlaceAuthorityClient();
107     }
108
109         @Override
110         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
111         return new PlaceAuthorityClient(clientPropertiesFilename);
112         }
113         
114         @Override
115         protected String createItemInAuthority(AuthorityClient client, String authorityId, String shortId) {
116                 return createItemInAuthority(client, authorityId, shortId, null /*refname*/);
117         }
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 shortId, 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, 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, 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         setupUpdateWithInvalidBody(); // we expected a failure here.
209         res = client.updateItem(knownResourceId, knownItemResourceId, output);
210         try {
211                 assertStatusCode(res, testName);
212         } finally {
213                 if (res != null) {
214                 res.close();
215             }
216         }
217     }
218
219     /**
220      * Read item list.
221      */
222     @Test(dataProvider = "testName", groups = {"readList"},
223                dependsOnMethods = {"readList"})
224     public void readItemList(String testName) {
225         readItemList(knownAuthorityWithItems, null);
226     }
227
228     /**
229      * Read item list by authority name.
230      */
231     @Test(dataProvider = "testName", groups = {"readList"},
232                 dependsOnMethods = {"readItemList"})
233     public void readItemListByAuthorityName(String testName) {
234         readItemList(null, READITEMS_SHORT_IDENTIFIER);
235     }
236     
237         /**
238          * Read item list.
239          * 
240          * @param vcsid
241          *            the vcsid
242          * @param name
243          *            the name
244          */
245         private void readItemList(String vcsid, String shortId) {
246                 String testName = "readItemList";
247
248                 // Perform setup.
249                 setupReadList();
250
251                 // Submit the request to the service and store the response.
252                 PlaceAuthorityClient client = new PlaceAuthorityClient();
253                 Response res = null;
254                 if (vcsid != null) {
255                         res = client.readItemList(vcsid, null, null);
256                 } else if (shortId != null) {
257                         res = client.readItemListForNamedAuthority(shortId, null, null);
258                 } else {
259                         Assert.fail("readItemList passed null csid and name!");
260                 }
261                 
262                 AbstractCommonList list = null;
263                 try {
264                         assertStatusCode(res, testName);
265                         list = res.readEntity(AbstractCommonList.class);
266                 } finally {
267                         if (res != null) {
268                 res.close();
269             }
270                 }
271                 
272                 List<AbstractCommonList.ListItem> items = list.getListItem();
273                 int nItemsReturned = items.size();
274                 // There will be 'nItemsToCreateInList'
275                 // items created by the createItemList test,
276                 // all associated with the same parent resource.
277                 int nExpectedItems = nItemsToCreateInList;
278                 if (logger.isDebugEnabled()) {
279                         logger.debug(testName + ": Expected " + nExpectedItems
280                                         + " items; got: " + nItemsReturned);
281                 }
282                 Assert.assertEquals(nItemsReturned, nExpectedItems);
283
284                 for (AbstractCommonList.ListItem item : items) {
285                         String value = AbstractCommonListUtils.ListItemGetElementValue(
286                                         item, PlaceJAXBSchema.REF_NAME);
287                         Assert.assertTrue((null != value), "Item refName is null!");
288                         value = AbstractCommonListUtils.ListItemGetElementValue(item,
289                                         PlaceJAXBSchema.TERM_DISPLAY_NAME);
290                         Assert.assertTrue((null != value), "Item termDisplayName is null!");
291                 }
292                 if (logger.isTraceEnabled()) {
293                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger,
294                                         testName);
295                 }
296         }
297
298     @Override
299     public void delete(String testName) throws Exception {
300         // Do nothing.  See localDelete().  This ensure proper test order.
301     }
302     
303     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
304     public void localDelete(String testName) throws Exception {
305         super.delete(testName);
306     }
307
308     @Override
309     public void deleteItem(String testName) throws Exception {
310         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
311         // its dependencies will get run first and then we can call the base class' delete method.
312     }
313     
314     @Test(dataProvider = "testName", groups = {"delete"},
315         dependsOnMethods = {"verifyIllegalItemDisplayName"})
316     public void localDeleteItem(String testName) throws Exception {
317         super.deleteItem(testName);
318     }
319     
320     // ---------------------------------------------------------------
321     // Cleanup of resources created during testing
322     // ---------------------------------------------------------------
323     
324     /**
325      * Deletes all resources created by tests, after all tests have been run.
326      *
327      * This cleanup method will always be run, even if one or more tests fail.
328      * For this reason, it attempts to remove all resources created
329      * at any point during testing, even if some of those resources
330      * may be expected to be deleted by certain tests.
331      */
332
333     @AfterClass(alwaysRun=true)
334     public void cleanUp() {
335         String noTest = System.getProperty("noTestCleanup");
336         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
337             if (logger.isDebugEnabled()) {
338                 logger.debug("Skipping Cleanup phase ...");
339             }
340             return;
341         }
342         if (logger.isDebugEnabled()) {
343             logger.debug("Cleaning up temporary resources created for testing ...");
344         }
345         String parentResourceId;
346         String itemResourceId;
347         // Clean up contact resources.
348         PlaceAuthorityClient client = new PlaceAuthorityClient();
349         parentResourceId = knownResourceId;
350         // Clean up item resources.
351         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
352             itemResourceId = entry.getKey();
353             parentResourceId = entry.getValue();
354             // Note: Any non-success responses from the delete operation
355             // below are ignored and not reported.
356             client.deleteItem(parentResourceId, itemResourceId).close();
357         }
358         // Clean up parent resources.
359         for (String resourceId : allResourceIdsCreated) {
360             // Note: Any non-success responses from the delete operation
361             // below are ignored and not reported.
362             client.delete(resourceId).close();
363         }
364     }
365
366     // ---------------------------------------------------------------
367     // Utility methods used by tests above
368     // ---------------------------------------------------------------
369     /* (non-Javadoc)
370      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
371      */
372
373     /**
374      * Returns the root URL for the item service.
375      *
376      * This URL consists of a base URL for all services, followed by
377      * a path component for the owning parent, followed by the
378      * path component for the items.
379      *
380      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
381      * parent authority resource of the relevant item resource.
382      *
383      * @return The root URL for the item service.
384      */
385     protected String getItemServiceRootURL(String parentResourceIdentifier) {
386         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
387     }
388
389     /**
390      * Returns the URL of a specific item resource managed by a service, and
391      * designated by an identifier (such as a universally unique ID, or UUID).
392      *
393      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
394      * parent authority resource of the relevant item resource.
395      *
396      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
397      * item resource.
398      *
399      * @return The URL of a specific item resource managed by a service.
400      */
401     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
402         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
403     }
404
405         @Override
406         public void authorityTests(String testName) {
407                 // TODO Auto-generated method stub
408                 
409         }
410
411         //
412         // Place specific overrides
413         //
414         
415         @Override
416         protected PoxPayloadOut createInstance(String commonPartName,
417                         String identifier) {
418         // Submit the request to the service and store the response.
419         String shortId = identifier;
420         String displayName = "displayName-" + shortId;
421         // String baseRefName = PlaceAuthorityClientUtils.createPlaceAuthRefName(shortId, null);        
422         PoxPayloadOut result = 
423             PlaceAuthorityClientUtils.createPlaceAuthorityInstance(
424             displayName, shortId, commonPartName);
425                 return result;
426         }
427         
428         @Override
429     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
430         String displayName = "displayName-NON_EXISTENT_ID";
431         PoxPayloadOut result = PlaceAuthorityClientUtils.createPlaceAuthorityInstance(
432                                 displayName, "nonEx", commonPartName);
433         return result;
434     }
435
436         @Override
437         protected PlaceauthoritiesCommon updateInstance(PlaceauthoritiesCommon placeauthoritiesCommon) {
438                 PlaceauthoritiesCommon result = new PlaceauthoritiesCommon();
439                 
440                 result.setDisplayName("updated-" + placeauthoritiesCommon.getDisplayName());
441                 result.setVocabType("updated-" + placeauthoritiesCommon.getVocabType());
442                 
443                 return result;
444         }
445
446         @Override
447         protected void compareUpdatedInstances(PlaceauthoritiesCommon original,
448                         PlaceauthoritiesCommon updated) throws Exception {
449         Assert.assertEquals(updated.getDisplayName(),
450                         original.getDisplayName(),
451                 "Display name in updated object did not match submitted data.");
452         }
453
454         protected void compareReadInstances(PlaceauthoritiesCommon original,
455                         PlaceauthoritiesCommon fromRead) throws Exception {
456         Assert.assertNotNull(fromRead.getDisplayName());
457         Assert.assertNotNull(fromRead.getShortIdentifier());
458         Assert.assertNotNull(fromRead.getRefName());
459         }
460         
461         //
462         // Authority item specific overrides
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
522 }