]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9ff14e513ee86511c30f423b6ebbc1135e3b2848
[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.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import org.collectionspace.services.LocationJAXBSchema;
30 import org.collectionspace.services.client.AbstractCommonListUtils;
31 import org.collectionspace.services.client.AuthorityClient;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.PayloadOutputPart;
34 import org.collectionspace.services.client.PoxPayloadIn;
35 import org.collectionspace.services.client.PoxPayloadOut;
36 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
37 import org.collectionspace.services.client.LocationAuthorityClient;
38 import org.collectionspace.services.client.LocationAuthorityClientUtils;
39 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.collectionspace.services.location.LocationauthoritiesCommon;
41 import org.collectionspace.services.location.LocationsCommon;
42
43 import org.jboss.resteasy.client.ClientResponse;
44
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51
52 /**
53  * LocationAuthorityServiceTest, carries out tests against a
54  * deployed and running LocationAuthority Service.
55  *
56  * $LastChangedRevision: 753 $
57  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
58  */
59 public class LocationAuthorityServiceTest extends AbstractAuthorityServiceTest<LocationauthoritiesCommon, LocationsCommon> {
60
61     /** The logger. */
62     private final String CLASS_NAME = LocationAuthorityServiceTest.class.getName();
63     private final Logger logger = LoggerFactory.getLogger(LocationAuthorityServiceTest.class);
64     private final String REFNAME = "refName";
65     private final String DISPLAYNAME = "displayName";
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.NAME, TEST_NAME);
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         shelf1Map.put(LocationJAXBSchema.TERM_STATUS, TEST_STATUS);
131         
132         String newID = LocationAuthorityClientUtils.createItemInAuthority(vcsid,
133                         authRefName, shelf1Map, client );
134
135         // Store the ID returned from the first item resource created
136         // for additional tests below.
137         if (knownItemResourceId == null){
138                 setKnownItemResource(newID, TEST_SHORTID);
139             if (logger.isDebugEnabled()) {
140                 logger.debug(testName + ": knownItemResourceId=" + newID);
141             }
142         }
143
144         // Store the IDs from any item resources created
145         // by tests, along with the IDs of their parents, so these items
146         // can be deleted after all tests have been run.
147         allResourceItemIdsCreated.put(newID, vcsid);
148
149         return newID;
150     }
151
152     /**
153      * Verify item display name.
154      *
155      * @param testName the test name
156      * @throws Exception the exception
157      */
158     @Test(dataProvider="testName",
159         dependsOnMethods = {"readItem", "updateItem"})
160     public void verifyItemDisplayName(String testName) throws Exception {
161         // Perform setup.
162         setupRead();
163         //
164         // First, read our known item resource
165         //
166         LocationAuthorityClient client = new LocationAuthorityClient();
167         ClientResponse<String> res = client.readItem(knownResourceId, knownItemResourceId);
168         LocationsCommon location = null;
169         try {
170             assertStatusCode(res, testName);
171                 // Check whether location has expected displayName.
172                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
173                 location = (LocationsCommon) extractPart(input,
174                         client.getItemCommonPartName(), LocationsCommon.class);
175                 Assert.assertNotNull(location);
176         } finally {
177                 if (res != null) {
178                 res.releaseConnection();
179             }
180         }
181         //
182         // Now prepare an updated payload.
183         //
184         String displayName = location.getDisplayName();
185         // Make sure displayName matches computed form
186         String expectedDisplayName = 
187             LocationAuthorityClientUtils.prepareDefaultDisplayName(TEST_NAME);
188         Assert.assertNotNull(displayName, expectedDisplayName);
189         
190         // Update the shortName and verify the computed name is updated.
191         location.setCsid(null);
192         location.setDisplayNameComputed(true);
193         location.setName("updated-" + TEST_NAME);
194         expectedDisplayName = 
195             LocationAuthorityClientUtils.prepareDefaultDisplayName("updated-" + TEST_NAME);
196
197         // Submit the updated resource to the service and store the response.
198         PoxPayloadOut output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
199         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), location);
200
201         setupUpdate();        
202         res = client.updateItem(knownResourceId, knownItemResourceId, output);
203         LocationsCommon updatedLocation = null;
204         try {
205                 assertStatusCode(res, testName);
206                 // Retrieve the updated resource and verify that its contents exist.
207                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
208                 updatedLocation = (LocationsCommon) extractPart(input,
209                                 client.getItemCommonPartName(), LocationsCommon.class);
210                 Assert.assertNotNull(updatedLocation);
211         } finally {
212                 if (res != null) {
213                 res.releaseConnection();
214             }
215         }
216
217         // Verify that the updated resource received the correct data.
218         Assert.assertEquals(updatedLocation.getName(), location.getName(),
219             "Updated ForeName in Location did not match submitted data.");
220         // Verify that the updated resource computes the right displayName.
221         Assert.assertEquals(updatedLocation.getDisplayName(), expectedDisplayName,
222             "Updated ForeName in Location not reflected in computed DisplayName.");
223         //
224         // Now Update the displayName, not computed and verify the computed name is overriden.
225         //
226         location.setDisplayNameComputed(false);
227         expectedDisplayName = "TestName";
228         location.setDisplayName(expectedDisplayName);
229
230         // Submit the updated resource to the service and store the response.
231         output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
232         commonPart = output.addPart(client.getItemCommonPartName(), location);
233         setupUpdate();        
234         res = client.updateItem(knownResourceId, knownItemResourceId, output);
235         try {
236                 assertStatusCode(res, testName);
237                 // Retrieve the updated resource and verify that its contents exist.
238                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
239                 updatedLocation = (LocationsCommon) extractPart(input,
240                                 client.getItemCommonPartName(), LocationsCommon.class);
241                 Assert.assertNotNull(updatedLocation);
242         } finally {
243                 if (res != null) {
244                 res.releaseConnection();
245             }
246         }
247
248         // Verify that the updated resource received the correct data.
249         Assert.assertEquals(updatedLocation.isDisplayNameComputed(), false,
250                 "Updated displayNameComputed in Location did not match submitted data.");
251         // Verify that the updated resource computes the right displayName.
252         Assert.assertEquals(updatedLocation.getDisplayName(),
253                         expectedDisplayName,
254                 "Updated DisplayName (not computed) in Location not stored.");
255     }
256
257     /**
258      * Verify illegal item display name.
259      *
260      * @param testName the test name
261      * @throws Exception the exception
262      */
263     @Test(dataProvider="testName",
264             dependsOnMethods = {"verifyItemDisplayName"})
265     public void verifyIllegalItemDisplayName(String testName) throws Exception {
266         // Perform setup for read.
267         setupRead();
268
269         // Submit the request to the service and store the response.
270         LocationAuthorityClient client = new LocationAuthorityClient();
271         ClientResponse<String> res = client.readItem(knownResourceId, knownItemResourceId);
272         LocationsCommon location = null;
273         try {
274             assertStatusCode(res, testName);        
275                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
276                 location = (LocationsCommon) extractPart(input,
277                         client.getItemCommonPartName(), LocationsCommon.class);
278                 Assert.assertNotNull(location);
279             } finally {
280                 if (res != null) {
281                 res.releaseConnection();
282             }
283             }
284                 
285         // Try to Update with computed false and no displayName
286         location.setDisplayNameComputed(false);
287         location.setDisplayName(null);
288         
289         // Submit the updated resource to the service and store the response.
290         PoxPayloadOut output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
291         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), location);
292         setupUpdateWithInvalidBody(); // we expected a failure here.
293         res = client.updateItem(knownResourceId, knownItemResourceId, output);
294         try {
295                 assertStatusCode(res, testName);
296         } finally {
297                 if (res != null) {
298                 res.releaseConnection();
299             }
300         }
301     }
302
303     /**
304      * Read item list.
305      */
306     @Test(dataProvider = "testName", groups = {"readList"},
307                 dependsOnMethods = {"readList"})
308     public void readItemList(String testName) {
309         readItemList(knownAuthorityWithItems, null);
310     }
311
312     /**
313      * Read item list by authority name.
314      */
315     @Test(dataProvider = "testName", groups = {"readList"},
316                 dependsOnMethods = {"readItemList"})
317     public void readItemListByAuthorityName(String testName) {
318         readItemList(null, READITEMS_SHORT_IDENTIFIER);
319     }
320     
321         /**
322          * Read item list.
323          * 
324          * @param vcsid
325          *            the vcsid
326          * @param name
327          *            the name
328          */
329         private void readItemList(String vcsid, String shortId) {
330                 String testName = "readItemList";
331
332                 // Perform setup.
333                 setupReadList();
334
335                 // Submit the request to the service and store the response.
336                 LocationAuthorityClient client = new LocationAuthorityClient();
337                 ClientResponse<AbstractCommonList> res = null;
338                 if (vcsid != null) {
339                         res = client.readItemList(vcsid, null, null);
340                 } else if (shortId != null) {
341                         res = client.readItemListForNamedAuthority(shortId, null, null);
342                 } else {
343                         Assert.fail("readItemList passed null csid and name!");
344                 }
345                 
346                 AbstractCommonList list = null;
347                 try {
348                         assertStatusCode(res, testName);
349                         list = res.getEntity();
350                 } finally {
351                         if (res != null) {
352                 res.releaseConnection();
353             }
354                 }
355                 
356                 List<AbstractCommonList.ListItem> items = list.getListItem();
357                 int nItemsReturned = items.size();
358                 // There will be 'nItemsToCreateInList'
359                 // items created by the createItemList test,
360                 // all associated with the same parent resource.
361                 int nExpectedItems = nItemsToCreateInList;
362                 if (logger.isDebugEnabled()) {
363                         logger.debug(testName + ": Expected " + nExpectedItems
364                                         + " items; got: " + nItemsReturned);
365                 }
366                 Assert.assertEquals(nItemsReturned, nExpectedItems);
367
368                 for (AbstractCommonList.ListItem item : items) {
369                         String value = AbstractCommonListUtils.ListItemGetElementValue(
370                                         item, REFNAME);
371                         Assert.assertTrue((null != value), "Item refName is null!");
372                         value = AbstractCommonListUtils.ListItemGetElementValue(item,
373                                         DISPLAYNAME);
374                         Assert.assertTrue((null != value), "Item displayName is null!");
375                 }
376                 if (logger.isTraceEnabled()) {
377                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger,
378                                         testName);
379                 }
380         }
381
382     @Override
383     public void delete(String testName) throws Exception {
384         // Do nothing.  See localDelete().  This ensure proper test order.
385     }
386     
387     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
388     public void localDelete(String testName) throws Exception {
389         super.delete(testName);
390     }
391
392     @Override
393     public void deleteItem(String testName) throws Exception {
394         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
395         // its dependencies will get run first and then we can call the base class' delete method.
396     }
397     
398     @Test(dataProvider = "testName", groups = {"delete"},
399         dependsOnMethods = {"verifyIllegalItemDisplayName"})
400     public void localDeleteItem(String testName) throws Exception {
401         super.deleteItem(testName);
402     }
403     
404     // ---------------------------------------------------------------
405     // Cleanup of resources created during testing
406     // ---------------------------------------------------------------
407     
408     /**
409      * Deletes all resources created by tests, after all tests have been run.
410      *
411      * This cleanup method will always be run, even if one or more tests fail.
412      * For this reason, it attempts to remove all resources created
413      * at any point during testing, even if some of those resources
414      * may be expected to be deleted by certain tests.
415      */
416
417     @AfterClass(alwaysRun=true)
418     public void cleanUp() {
419         String noTest = System.getProperty("noTestCleanup");
420         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
421             if (logger.isDebugEnabled()) {
422                 logger.debug("Skipping Cleanup phase ...");
423             }
424             return;
425         }
426         if (logger.isDebugEnabled()) {
427             logger.debug("Cleaning up temporary resources created for testing ...");
428         }
429         String parentResourceId;
430         String itemResourceId;
431         // Clean up contact resources.
432         LocationAuthorityClient client = new LocationAuthorityClient();
433         parentResourceId = knownResourceId;
434         // Clean up item resources.
435         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
436             itemResourceId = entry.getKey();
437             parentResourceId = entry.getValue();
438             // Note: Any non-success responses from the delete operation
439             // below are ignored and not reported.
440             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
441         }
442         // Clean up parent resources.
443         for (String resourceId : allResourceIdsCreated) {
444             // Note: Any non-success responses from the delete operation
445             // below are ignored and not reported.
446             client.delete(resourceId).releaseConnection();
447         }
448     }
449
450     // ---------------------------------------------------------------
451     // Utility methods used by tests above
452     // ---------------------------------------------------------------
453     /* (non-Javadoc)
454      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
455      */
456
457     /**
458      * Returns the root URL for the item service.
459      *
460      * This URL consists of a base URL for all services, followed by
461      * a path component for the owning parent, followed by the
462      * path component for the items.
463      *
464      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
465      * parent authority resource of the relevant item resource.
466      *
467      * @return The root URL for the item service.
468      */
469     protected String getItemServiceRootURL(String parentResourceIdentifier) {
470         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
471     }
472
473     /**
474      * Returns the URL of a specific item resource managed by a service, and
475      * designated by an identifier (such as a universally unique ID, or UUID).
476      *
477      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
478      * parent authority resource of the relevant item resource.
479      *
480      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
481      * item resource.
482      *
483      * @return The URL of a specific item resource managed by a service.
484      */
485     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
486         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
487     }
488
489         @Override
490         public void authorityTests(String testName) {
491                 // TODO Auto-generated method stub
492                 
493         }
494
495         //
496         // Location specific overrides
497         //
498         
499         @Override
500         protected PoxPayloadOut createInstance(String commonPartName,
501                         String identifier) {
502         // Submit the request to the service and store the response.
503         String shortId = identifier;
504         String displayName = "displayName-" + shortId;
505         // String baseRefName = LocationAuthorityClientUtils.createLocationAuthRefName(shortId, null);          
506         PoxPayloadOut result = 
507             LocationAuthorityClientUtils.createLocationAuthorityInstance(
508             displayName, shortId, commonPartName);
509                 return result;
510         }
511         
512         @Override
513     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
514         String displayName = "displayName-NON_EXISTENT_ID";
515         PoxPayloadOut result = LocationAuthorityClientUtils.createLocationAuthorityInstance(
516                                 displayName, "nonEx", commonPartName);
517         return result;
518     }
519
520         @Override
521         protected LocationauthoritiesCommon updateInstance(LocationauthoritiesCommon locationauthoritiesCommon) {
522                 LocationauthoritiesCommon result = new LocationauthoritiesCommon();
523                 
524                 result.setDisplayName("updated-" + locationauthoritiesCommon.getDisplayName());
525                 result.setVocabType("updated-" + locationauthoritiesCommon.getVocabType());
526                 
527                 return result;
528         }
529
530         @Override
531         protected void compareUpdatedInstances(LocationauthoritiesCommon original,
532                         LocationauthoritiesCommon updated) throws Exception {
533         Assert.assertEquals(updated.getDisplayName(),
534                         original.getDisplayName(),
535                 "Display name in updated object did not match submitted data.");
536         }
537
538         protected void compareReadInstances(LocationauthoritiesCommon original,
539                         LocationauthoritiesCommon fromRead) throws Exception {
540         Assert.assertNotNull(fromRead.getDisplayName());
541         Assert.assertNotNull(fromRead.getShortIdentifier());
542         Assert.assertNotNull(fromRead.getRefName());
543         }
544         
545         //
546         // Authority item specific overrides
547         //
548         
549         @Override
550         protected String createItemInAuthority(String authorityId) {
551                 return createItemInAuthority(authorityId, null /*refname*/);
552         }
553
554         @Override
555         protected LocationsCommon updateItemInstance(LocationsCommon locationsCommon) {
556                 LocationsCommon result = new LocationsCommon();
557                 
558         result.setName("updated-" + locationsCommon.getName());
559                 result.setDisplayName("updated-" + locationsCommon.getDisplayName());
560                 
561                 return result;
562         }
563
564         @Override
565         protected void compareUpdatedItemInstances(LocationsCommon original,
566                         LocationsCommon updated) throws Exception {
567         Assert.assertEquals(updated.getName(), original.getName(),
568                 "Data in updated Location did not match submitted data.");
569         }
570
571         @Override
572         protected void verifyReadItemInstance(LocationsCommon item)
573                         throws Exception {
574                 // TODO Auto-generated method stub
575                 
576         }
577
578         @Override
579         protected PoxPayloadOut createNonExistenceItemInstance(
580                         String commonPartName, String identifier) {
581         Map<String, String> nonexMap = new HashMap<String,String>();
582         nonexMap.put(LocationJAXBSchema.NAME, TEST_NAME);
583         nonexMap.put(LocationJAXBSchema.SHORT_IDENTIFIER, "nonEx");
584         nonexMap.put(LocationJAXBSchema.LOCATION_TYPE, TEST_LOCATION_TYPE);
585         nonexMap.put(LocationJAXBSchema.TERM_STATUS, TEST_STATUS);
586         final String EMPTY_REFNAME = "";
587         PoxPayloadOut result = 
588                 LocationAuthorityClientUtils.createLocationInstance(EMPTY_REFNAME, 
589                         nonexMap, commonPartName);
590                 return result;
591         }
592 }