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