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