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