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