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