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