]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a72e48426fa071059283ff592a9a25f12f054dca
[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 //    /** The SERVICE path component. */
86 //    final String SERVICE_PATH_COMPONENT = "locationauthorities";
87 //    
88 //    /** The ITEM service path component. */
89 //    final String ITEM_SERVICE_PATH_COMPONENT = "items";
90 //    
91 //    /** The CONTACT service path component. */
92 //    final String CONTACT_SERVICE_PATH_COMPONENT = "contacts";
93     
94     final String TEST_NAME = "Shelf 1";
95     final String TEST_SHORTID = "shelf1";
96     final String TEST_CONDITION_NOTE = "Basically clean";
97     final String TEST_CONDITION_NOTE_DATE = CURRENT_DATE_UTC;
98     final String TEST_SECURITY_NOTE = "Kind of safe";
99     final String TEST_ACCESS_NOTE = "Only right-thinkers may see";
100     final String TEST_ADDRESS = "123 Main Street, Anytown USA";
101     // TODO Make loc type be a controlled vocab term.
102     final String TEST_LOCATION_TYPE = "Shelf";
103     // TODO Make status type be a controlled vocab term.
104     final String TEST_STATUS = "Approved";
105     
106     /** The known resource id. */
107     private String knownResourceShortIdentifer = null;
108     private String knownResourceRefName = null;
109     
110     private String knownLocationTypeRefName = null;
111     private String knownContactResourceId = null;
112         
113     /* (non-Javadoc)
114      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
115      */
116     @Override
117     protected CollectionSpaceClient getClientInstance() {
118         return new LocationAuthorityClient();
119     }
120     
121     /**
122      * Creates the item in authority.
123      *
124      * @param vcsid the vcsid
125      * @param authRefName the auth ref name
126      * @return the string
127      */
128     private String createItemInAuthority(String vcsid, String authRefName) {
129         final String testName = "createItemInAuthority("+vcsid+","+authRefName+")";
130
131         // Submit the request to the service and store the response.
132         LocationAuthorityClient client = new LocationAuthorityClient();
133         Map<String, String> shelf1Map = new HashMap<String,String>();
134         // TODO Make loc type and status be controlled vocabs.
135         shelf1Map.put(LocationJAXBSchema.NAME, TEST_NAME);
136         shelf1Map.put(LocationJAXBSchema.SHORT_IDENTIFIER, TEST_SHORTID);
137         shelf1Map.put(LocationJAXBSchema.CONDITION_NOTE, TEST_CONDITION_NOTE);
138         shelf1Map.put(LocationJAXBSchema.CONDITION_NOTE_DATE, TEST_CONDITION_NOTE_DATE);
139         shelf1Map.put(LocationJAXBSchema.SECURITY_NOTE, TEST_SECURITY_NOTE);
140         shelf1Map.put(LocationJAXBSchema.ACCESS_NOTE, TEST_ACCESS_NOTE);
141         shelf1Map.put(LocationJAXBSchema.ADDRESS, TEST_ADDRESS);
142         shelf1Map.put(LocationJAXBSchema.LOCATION_TYPE, TEST_LOCATION_TYPE);
143         shelf1Map.put(LocationJAXBSchema.TERM_STATUS, TEST_STATUS);
144         
145         String newID = LocationAuthorityClientUtils.createItemInAuthority(vcsid,
146                         authRefName, shelf1Map, 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, TEST_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 item display name.
167      *
168      * @param testName the test name
169      * @throws Exception the exception
170      */
171     @Test(dataProvider="testName",
172         dependsOnMethods = {"readItem", "updateItem"})
173     public void verifyItemDisplayName(String testName) throws Exception {
174         // Perform setup.
175         setupRead();
176         //
177         // First, read our known item resource
178         //
179         LocationAuthorityClient client = new LocationAuthorityClient();
180         ClientResponse<String> res = client.readItem(knownResourceId, knownItemResourceId);
181         LocationsCommon location = null;
182         try {
183             assertStatusCode(res, testName);
184                 // Check whether location has expected displayName.
185                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
186                 location = (LocationsCommon) extractPart(input,
187                         client.getItemCommonPartName(), LocationsCommon.class);
188                 Assert.assertNotNull(location);
189         } finally {
190                 if (res != null) {
191                 res.releaseConnection();
192             }
193         }
194         //
195         // Now prepare an updated payload.
196         //
197         String displayName = location.getDisplayName();
198         // Make sure displayName matches computed form
199         String expectedDisplayName = 
200             LocationAuthorityClientUtils.prepareDefaultDisplayName(TEST_NAME);
201         Assert.assertNotNull(displayName, expectedDisplayName);
202         
203         // Update the shortName and verify the computed name is updated.
204         location.setCsid(null);
205         location.setDisplayNameComputed(true);
206         location.setName("updated-" + TEST_NAME);
207         expectedDisplayName = 
208             LocationAuthorityClientUtils.prepareDefaultDisplayName("updated-" + TEST_NAME);
209
210         // Submit the updated resource to the service and store the response.
211         PoxPayloadOut output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
212         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), location);
213
214         setupUpdate();        
215         res = client.updateItem(knownResourceId, knownItemResourceId, output);
216         LocationsCommon updatedLocation = null;
217         try {
218                 assertStatusCode(res, testName);
219                 // Retrieve the updated resource and verify that its contents exist.
220                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
221                 updatedLocation = (LocationsCommon) extractPart(input,
222                                 client.getItemCommonPartName(), LocationsCommon.class);
223                 Assert.assertNotNull(updatedLocation);
224         } finally {
225                 if (res != null) {
226                 res.releaseConnection();
227             }
228         }
229
230         // Verify that the updated resource received the correct data.
231         Assert.assertEquals(updatedLocation.getName(), location.getName(),
232             "Updated ForeName in Location did not match submitted data.");
233         // Verify that the updated resource computes the right displayName.
234         Assert.assertEquals(updatedLocation.getDisplayName(), expectedDisplayName,
235             "Updated ForeName in Location not reflected in computed DisplayName.");
236         //
237         // Now Update the displayName, not computed and verify the computed name is overriden.
238         //
239         location.setDisplayNameComputed(false);
240         expectedDisplayName = "TestName";
241         location.setDisplayName(expectedDisplayName);
242
243         // Submit the updated resource to the service and store the response.
244         output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
245         commonPart = output.addPart(client.getItemCommonPartName(), location);
246         setupUpdate();        
247         res = client.updateItem(knownResourceId, knownItemResourceId, output);
248         try {
249                 assertStatusCode(res, testName);
250                 // Retrieve the updated resource and verify that its contents exist.
251                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
252                 updatedLocation = (LocationsCommon) extractPart(input,
253                                 client.getItemCommonPartName(), LocationsCommon.class);
254                 Assert.assertNotNull(updatedLocation);
255         } finally {
256                 if (res != null) {
257                 res.releaseConnection();
258             }
259         }
260
261         // Verify that the updated resource received the correct data.
262         Assert.assertEquals(updatedLocation.isDisplayNameComputed(), false,
263                 "Updated displayNameComputed in Location did not match submitted data.");
264         // Verify that the updated resource computes the right displayName.
265         Assert.assertEquals(updatedLocation.getDisplayName(),
266                         expectedDisplayName,
267                 "Updated DisplayName (not computed) in Location not stored.");
268     }
269
270     /**
271      * Verify illegal item display name.
272      *
273      * @param testName the test name
274      * @throws Exception the exception
275      */
276     @Test(dataProvider="testName",
277             dependsOnMethods = {"verifyItemDisplayName"})
278     public void verifyIllegalItemDisplayName(String testName) throws Exception {
279         // Perform setup for read.
280         setupRead();
281
282         // Submit the request to the service and store the response.
283         LocationAuthorityClient client = new LocationAuthorityClient();
284         ClientResponse<String> res = client.readItem(knownResourceId, knownItemResourceId);
285         LocationsCommon location = null;
286         try {
287             assertStatusCode(res, testName);        
288                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
289                 location = (LocationsCommon) extractPart(input,
290                         client.getItemCommonPartName(), LocationsCommon.class);
291                 Assert.assertNotNull(location);
292             } finally {
293                 if (res != null) {
294                 res.releaseConnection();
295             }
296             }
297                 
298         // Try to Update with computed false and no displayName
299         location.setDisplayNameComputed(false);
300         location.setDisplayName(null);
301         
302         // Submit the updated resource to the service and store the response.
303         PoxPayloadOut output = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
304         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), location);
305         setupUpdateWithInvalidBody(); // we expected a failure here.
306         res = client.updateItem(knownResourceId, knownItemResourceId, output);
307         try {
308                 assertStatusCode(res, testName);
309         } finally {
310                 if (res != null) {
311                 res.releaseConnection();
312             }
313         }
314     }
315
316     /**
317      * Read item list.
318      */
319     @Test(dataProvider = "testName", groups = {"readList"},
320                 dependsOnMethods = {"readList"})
321     public void readItemList(String testName) {
322         readItemList(knownAuthorityWithItems, null);
323     }
324
325     /**
326      * Read item list by authority name.
327      */
328     @Test(dataProvider = "testName", groups = {"readList"},
329                 dependsOnMethods = {"readItemList"})
330     public void readItemListByAuthorityName(String testName) {
331         readItemList(null, READITEMS_SHORT_IDENTIFIER);
332     }
333     
334         /**
335          * Read item list.
336          * 
337          * @param vcsid
338          *            the vcsid
339          * @param name
340          *            the name
341          */
342         private void readItemList(String vcsid, String shortId) {
343                 String testName = "readItemList";
344
345                 // Perform setup.
346                 setupReadList();
347
348                 // Submit the request to the service and store the response.
349                 LocationAuthorityClient client = new LocationAuthorityClient();
350                 ClientResponse<AbstractCommonList> res = null;
351                 if (vcsid != null) {
352                         res = client.readItemList(vcsid, null, null);
353                 } else if (shortId != null) {
354                         res = client.readItemListForNamedAuthority(shortId, null, null);
355                 } else {
356                         Assert.fail("readItemList passed null csid and name!");
357                 }
358                 
359                 AbstractCommonList list = null;
360                 try {
361                         assertStatusCode(res, testName);
362                         list = res.getEntity();
363                 } finally {
364                         if (res != null) {
365                 res.releaseConnection();
366             }
367                 }
368                 
369                 List<AbstractCommonList.ListItem> items = list.getListItem();
370                 int nItemsReturned = items.size();
371                 // There will be 'nItemsToCreateInList'
372                 // items created by the createItemList test,
373                 // all associated with the same parent resource.
374                 int nExpectedItems = nItemsToCreateInList;
375                 if (logger.isDebugEnabled()) {
376                         logger.debug(testName + ": Expected " + nExpectedItems
377                                         + " items; got: " + nItemsReturned);
378                 }
379                 Assert.assertEquals(nItemsReturned, nExpectedItems);
380
381                 for (AbstractCommonList.ListItem item : items) {
382                         String value = AbstractCommonListUtils.ListItemGetElementValue(
383                                         item, REFNAME);
384                         Assert.assertTrue((null != value), "Item refName is null!");
385                         value = AbstractCommonListUtils.ListItemGetElementValue(item,
386                                         DISPLAYNAME);
387                         Assert.assertTrue((null != value), "Item displayName is null!");
388                 }
389                 if (logger.isTraceEnabled()) {
390                         AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger,
391                                         testName);
392                 }
393         }
394
395     @Override
396     public void delete(String testName) throws Exception {
397         // Do nothing.  See localDelete().  This ensure proper test order.
398     }
399     
400     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
401     public void localDelete(String testName) throws Exception {
402         super.delete(testName);
403     }
404
405     @Override
406     public void deleteItem(String testName) throws Exception {
407         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
408         // its dependencies will get run first and then we can call the base class' delete method.
409     }
410     
411     @Test(dataProvider = "testName", groups = {"delete"},
412         dependsOnMethods = {"verifyIllegalItemDisplayName"})
413     public void localDeleteItem(String testName) throws Exception {
414         super.deleteItem(testName);
415     }
416     
417     // ---------------------------------------------------------------
418     // Cleanup of resources created during testing
419     // ---------------------------------------------------------------
420     
421     /**
422      * Deletes all resources created by tests, after all tests have been run.
423      *
424      * This cleanup method will always be run, even if one or more tests fail.
425      * For this reason, it attempts to remove all resources created
426      * at any point during testing, even if some of those resources
427      * may be expected to be deleted by certain tests.
428      */
429
430     @AfterClass(alwaysRun=true)
431     public void cleanUp() {
432         String noTest = System.getProperty("noTestCleanup");
433         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
434             if (logger.isDebugEnabled()) {
435                 logger.debug("Skipping Cleanup phase ...");
436             }
437             return;
438         }
439         if (logger.isDebugEnabled()) {
440             logger.debug("Cleaning up temporary resources created for testing ...");
441         }
442         String parentResourceId;
443         String itemResourceId;
444         // Clean up contact resources.
445         LocationAuthorityClient client = new LocationAuthorityClient();
446         parentResourceId = knownResourceId;
447         // Clean up item resources.
448         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
449             itemResourceId = entry.getKey();
450             parentResourceId = entry.getValue();
451             // Note: Any non-success responses from the delete operation
452             // below are ignored and not reported.
453             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
454         }
455         // Clean up parent resources.
456         for (String resourceId : allResourceIdsCreated) {
457             // Note: Any non-success responses from the delete operation
458             // below are ignored and not reported.
459             client.delete(resourceId).releaseConnection();
460         }
461     }
462
463     // ---------------------------------------------------------------
464     // Utility methods used by tests above
465     // ---------------------------------------------------------------
466     /* (non-Javadoc)
467      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
468      */
469
470     /**
471      * Returns the root URL for the item service.
472      *
473      * This URL consists of a base URL for all services, followed by
474      * a path component for the owning parent, followed by the
475      * path component for the items.
476      *
477      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
478      * parent authority resource of the relevant item resource.
479      *
480      * @return The root URL for the item service.
481      */
482     protected String getItemServiceRootURL(String parentResourceIdentifier) {
483         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
484     }
485
486     /**
487      * Returns the URL of a specific item resource managed by a service, and
488      * designated by an identifier (such as a universally unique ID, or UUID).
489      *
490      * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
491      * parent authority resource of the relevant item resource.
492      *
493      * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
494      * item resource.
495      *
496      * @return The URL of a specific item resource managed by a service.
497      */
498     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
499         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
500     }
501
502         @Override
503         public void authorityTests(String testName) {
504                 // TODO Auto-generated method stub
505                 
506         }
507
508         //
509         // Location specific overrides
510         //
511         
512         @Override
513         protected PoxPayloadOut createInstance(String commonPartName,
514                         String identifier) {
515         // Submit the request to the service and store the response.
516         String shortId = identifier;
517         String displayName = "displayName-" + shortId;
518         // String baseRefName = LocationAuthorityClientUtils.createLocationAuthRefName(shortId, null);          
519         PoxPayloadOut result = 
520             LocationAuthorityClientUtils.createLocationAuthorityInstance(
521             displayName, shortId, commonPartName);
522                 return result;
523         }
524         
525         @Override
526     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
527         String displayName = "displayName-NON_EXISTENT_ID";
528         PoxPayloadOut result = LocationAuthorityClientUtils.createLocationAuthorityInstance(
529                                 displayName, "nonEx", commonPartName);
530         return result;
531     }
532
533         @Override
534         protected LocationauthoritiesCommon updateInstance(LocationauthoritiesCommon locationauthoritiesCommon) {
535                 LocationauthoritiesCommon result = new LocationauthoritiesCommon();
536                 
537                 result.setDisplayName("updated-" + locationauthoritiesCommon.getDisplayName());
538                 result.setVocabType("updated-" + locationauthoritiesCommon.getVocabType());
539                 
540                 return result;
541         }
542
543         @Override
544         protected void compareUpdatedInstances(LocationauthoritiesCommon original,
545                         LocationauthoritiesCommon updated) throws Exception {
546         Assert.assertEquals(updated.getDisplayName(),
547                         original.getDisplayName(),
548                 "Display name in updated object did not match submitted data.");
549         }
550
551         protected void compareReadInstances(LocationauthoritiesCommon original,
552                         LocationauthoritiesCommon fromRead) throws Exception {
553         Assert.assertNotNull(fromRead.getDisplayName());
554         Assert.assertNotNull(fromRead.getShortIdentifier());
555         Assert.assertNotNull(fromRead.getRefName());
556         }
557         
558         //
559         // Authority item specific overrides
560         //
561         
562         @Override
563         protected String createItemInAuthority(String authorityId) {
564                 return createItemInAuthority(authorityId, null /*refname*/);
565         }
566
567         @Override
568         protected LocationsCommon updateItemInstance(LocationsCommon locationsCommon) {
569                 LocationsCommon result = new LocationsCommon();
570                 
571         result.setName("updated-" + locationsCommon.getName());
572                 result.setDisplayName("updated-" + locationsCommon.getDisplayName());
573                 
574                 return result;
575         }
576
577         @Override
578         protected void compareUpdatedItemInstances(LocationsCommon original,
579                         LocationsCommon updated) throws Exception {
580         Assert.assertEquals(updated.getName(), original.getName(),
581                 "Data in updated Location did not match submitted data.");
582         }
583
584         @Override
585         protected void verifyReadItemInstance(LocationsCommon item)
586                         throws Exception {
587                 // TODO Auto-generated method stub
588                 
589         }
590
591         @Override
592         protected PoxPayloadOut createNonExistenceItemInstance(
593                         String commonPartName, String identifier) {
594         Map<String, String> nonexMap = new HashMap<String,String>();
595         nonexMap.put(LocationJAXBSchema.NAME, TEST_NAME);
596         nonexMap.put(LocationJAXBSchema.SHORT_IDENTIFIER, "nonEx");
597         nonexMap.put(LocationJAXBSchema.LOCATION_TYPE, TEST_LOCATION_TYPE);
598         nonexMap.put(LocationJAXBSchema.TERM_STATUS, TEST_STATUS);
599         // PoxPayloadOut multipart = 
600         // LocationAuthorityClientUtils.createLocationInstance(
601         //              LocationAuthorityClientUtils.createLocationRefName(knownResourceRefName, "nonEx", "Non Existent"), 
602         //              nonexMap, client.getItemCommonPartName() );
603         final String EMPTY_REFNAME = "";
604         PoxPayloadOut result = 
605                 LocationAuthorityClientUtils.createLocationInstance(EMPTY_REFNAME, 
606                         nonexMap, commonPartName);
607                 return result;
608         }
609 }