]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f08a1f2447512f290cbfb54004af7e16b4c999e2
[tmp/jakarta-migration.git] /
1 /**
2  * This document is a part of the source code and related artifacts for
3  * CollectionSpace, an open source collections management system for museums and
4  * related institutions:
5  *
6  * http://www.collectionspace.org http://wiki.collectionspace.org
7  *
8  * Copyright (c)) 2009 Regents of the University of California
9  *
10  * Licensed under the Educational Community License (ECL), Version 2.0. You may
11  * not use this file except in compliance with this License.
12  *
13  * You may obtain a copy of the ECL 2.0 License at
14  * https://source.collectionspace.org/collection-space/LICENSE.txt
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19  * License for the specific language governing permissions and limitations under
20  * the License.
21  */
22 package org.collectionspace.services.client.test;
23
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.collectionspace.services.TaxonJAXBSchema;
29 import org.collectionspace.services.client.AbstractCommonListUtils;
30 import org.collectionspace.services.client.AuthorityClient;
31 import org.collectionspace.services.client.CollectionSpaceClient;
32 import org.collectionspace.services.client.PayloadOutputPart;
33 import org.collectionspace.services.client.PoxPayloadIn;
34 import org.collectionspace.services.client.PoxPayloadOut;
35 import org.collectionspace.services.client.TaxonomyAuthorityClient;
36 import org.collectionspace.services.client.TaxonomyAuthorityClientUtils;
37 import org.collectionspace.services.client.TaxonomyAuthorityProxy;
38 import org.collectionspace.services.jaxb.AbstractCommonList;
39
40 import org.collectionspace.services.taxonomy.CommonNameGroup;
41 import org.collectionspace.services.taxonomy.CommonNameGroupList;
42 import org.collectionspace.services.taxonomy.TaxonAuthorGroup;
43 import org.collectionspace.services.taxonomy.TaxonAuthorGroupList;
44 import org.collectionspace.services.taxonomy.TaxonCitationList;
45 import org.collectionspace.services.taxonomy.TaxonCommon;
46 import org.collectionspace.services.taxonomy.TaxonTermGroup;
47 import org.collectionspace.services.taxonomy.TaxonTermGroupList;
48 import org.collectionspace.services.taxonomy.TaxonomyauthorityCommon;
49
50 import javax.ws.rs.core.Response;
51
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.testng.Assert;
55 import org.testng.annotations.AfterClass;
56 import org.testng.annotations.Test;
57
58 /**
59  * TaxonomyAuthorityServiceTest, carries out tests against a deployed and
60  * running TaxonomyAuthority Service.
61  *
62  * $LastChangedRevision$ $LastChangedDate$
63  */
64 public class TaxonomyAuthorityServiceTest extends AbstractAuthorityServiceTest<TaxonomyauthorityCommon, TaxonCommon> {
65
66     /**
67      * Default constructor.  Used to set the short ID for all tests authority items
68      */
69         TaxonomyAuthorityServiceTest() {
70             TEST_SHORTID = "CentauruspleurexanthemusGreen1832";         
71         }
72         
73     /**
74      * The logger.
75      */
76     private final String CLASS_NAME = TaxonomyAuthorityServiceTest.class.getName();
77     private final Logger logger = LoggerFactory.getLogger(TaxonomyAuthorityServiceTest.class);
78     private final String TEST_TERM_STATUS = "accepted";
79     private final String TEST_TAXON_FULL_NAME = "Centaurus pleurexanthemus Green 1832";
80     // TODO Re-implement the Taxon Rank field so as to provide an orderable
81     // ranking value, as well as a display name.
82     private final String TEST_TAXON_RANK = "species";
83     private final String TEST_TAXON_AUTHOR = "J. Green";
84     private final String TEST_TAXON_AUTHOR_TYPE = "ascribed";
85     private final String TEST_TAXON_CITATION = "A Monograph of the Trilobites of North America";
86     private final String TEST_TAXON_CURRENCY = "current";
87     private final String TEST_TAXON_YEAR = "1832";
88     private final String TEST_TAXONOMIC_STATUS = "valid";
89     private final String TEST_TAXON_IS_NAMED_HYBRID = "false";
90     private final List<TaxonTermGroup> NULL_TAXON_TERMS_LIST = null;
91     private final TaxonAuthorGroupList NULL_TAXON_AUTHOR_GROUP_LIST = null;
92     private final TaxonCitationList NULL_TAXON_CITATION_LIST = null;
93     private final CommonNameGroupList NULL_COMMON_NAME_GROUP_LIST = null;
94
95     @Override
96     public String getServicePathComponent() {
97         return TaxonomyAuthorityClient.SERVICE_PATH_COMPONENT;
98     }
99
100     @Override
101     protected String getServiceName() {
102         return TaxonomyAuthorityClient.SERVICE_NAME;
103     }
104
105     public String getItemServicePathComponent() {
106         return AuthorityClient.ITEMS;
107     }
108
109     /*
110      * (non-Javadoc) @see
111      * org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
112      */
113     @Override
114     protected CollectionSpaceClient<AbstractCommonList, PoxPayloadOut, String, TaxonomyAuthorityProxy> getClientInstance() {
115         return new TaxonomyAuthorityClient();
116     }
117
118         @Override
119         protected CollectionSpaceClient<AbstractCommonList, PoxPayloadOut, String, TaxonomyAuthorityProxy> getClientInstance(String clientPropertiesFilename) {
120         return new TaxonomyAuthorityClient(clientPropertiesFilename);
121         }
122         
123     @Override
124     protected String createItemInAuthority(AuthorityClient client, String authorityId, String shortId) {
125         return createItemInAuthority(client, authorityId, shortId, null /** refname */);
126     }
127
128     /**
129      * Creates the item in authority.
130      *
131      * @param vcsid the vcsid
132      * @param authRefName the auth ref name
133      * @return the string
134      */
135     private String createItemInAuthority(AuthorityClient client, String vcsid, String shortId, String authRefName) {
136
137         final String testName = "createItemInAuthority(" + vcsid + "," + authRefName + ")";
138         if (logger.isDebugEnabled()) {
139             logger.debug(getTestBanner(testName, CLASS_NAME));
140         }
141
142         // Submit the request to the service and store the response.
143         Map<String, String> taxonMap = new HashMap<String, String>();
144
145         // Fields present in all authority records.
146         taxonMap.put(TaxonJAXBSchema.SHORT_IDENTIFIER, shortId);
147         // TODO Make term status be controlled vocab.
148         taxonMap.put(TaxonJAXBSchema.TERM_STATUS, TEST_TERM_STATUS);
149
150         // Fields specific to this specific authority record type.
151         taxonMap.put(TaxonJAXBSchema.NAME, TEST_TAXON_FULL_NAME);
152         taxonMap.put(TaxonJAXBSchema.TAXON_RANK, TEST_TAXON_RANK);
153         taxonMap.put(TaxonJAXBSchema.TAXON_CURRENCY, TEST_TAXON_CURRENCY);
154         taxonMap.put(TaxonJAXBSchema.TAXON_YEAR, TEST_TAXON_YEAR);
155         taxonMap.put(TaxonJAXBSchema.TAXONOMIC_STATUS, TEST_TAXONOMIC_STATUS);
156         taxonMap.put(TaxonJAXBSchema.TAXON_IS_NAMED_HYBRID, TEST_TAXON_IS_NAMED_HYBRID);
157
158         TaxonCitationList taxonCitationList = new TaxonCitationList();
159         List<String> taxonCitations = taxonCitationList.getTaxonCitation();
160         taxonCitations.add(TEST_TAXON_CITATION);
161
162         TaxonAuthorGroupList taxonAuthorGroupList = new TaxonAuthorGroupList();
163         List<TaxonAuthorGroup> taxonAuthorGroups = taxonAuthorGroupList.getTaxonAuthorGroup();
164         TaxonAuthorGroup taxonAuthorGroup = new TaxonAuthorGroup();
165         taxonAuthorGroup.setTaxonAuthor(TEST_TAXON_AUTHOR);
166         taxonAuthorGroup.setTaxonAuthorType(TEST_TAXON_AUTHOR_TYPE);
167         taxonAuthorGroups.add(taxonAuthorGroup);
168                 
169         CommonNameGroupList commonNameGroupList = new CommonNameGroupList();
170         List<CommonNameGroup> commonNameGroups = commonNameGroupList.getCommonNameGroup();
171         CommonNameGroup commonNameGroup = new CommonNameGroup();
172         commonNameGroup.setCommonName(TEST_TAXON_FULL_NAME);
173         commonNameGroups.add(commonNameGroup);
174
175         // FIXME: Add additional fields in the Taxon record here,
176         // including at least one each of:
177         // * a Boolean field (when implemented)
178         // * an authref field (when implemented)
179
180         String newID = TaxonomyAuthorityClientUtils.createItemInAuthority(vcsid,
181                 authRefName, taxonMap, NULL_TAXON_TERMS_LIST, taxonAuthorGroupList,
182                 taxonCitationList, commonNameGroupList, (TaxonomyAuthorityClient)client);
183
184         // Store the ID returned from the first item resource created
185         // for additional tests below.
186         if (knownItemResourceId == null) {
187             setKnownItemResource(newID, shortId);
188             if (logger.isDebugEnabled()) {
189                 logger.debug(testName + ": knownItemResourceId=" + newID + " inAuthority=" + vcsid);
190             }
191         }
192
193         // Store the IDs from any item resources created
194         // by tests, along with the IDs of their parents, so these items
195         // can be deleted after all tests have been run.
196         allResourceItemIdsCreated.put(newID, vcsid);
197
198         return newID;
199     }
200
201     /**
202      * Verify illegal item display name.
203      *
204      * @param testName the test name
205      * @throws Exception the exception
206      */
207     @Test(dataProvider = "testName")
208     public void verifyIllegalItemDisplayName(String testName) throws Exception {
209         //
210         // First read in our known resource.
211         //
212         setupRead();
213         TaxonomyAuthorityClient client = new TaxonomyAuthorityClient();
214         Response res = client.readItem(knownResourceId, knownItemResourceId);
215         TaxonCommon taxon = null;
216         try {
217             assertStatusCode(res, testName);
218             // Check whether Taxonomy has expected displayName.
219             PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
220             taxon = (TaxonCommon) extractPart(input,
221                     client.getItemCommonPartName(), TaxonCommon.class);
222             Assert.assertNotNull(taxon);
223         } finally {
224             if (res != null) {
225                 res.close();
226             }
227         }
228         //
229         // Make an invalid UPDATE request, without a display name
230         //
231         TaxonTermGroupList termList = taxon.getTaxonTermGroupList();
232         Assert.assertNotNull(termList);
233         List<TaxonTermGroup> terms = termList.getTaxonTermGroup();
234         Assert.assertNotNull(terms);
235         Assert.assertTrue(terms.size() > 0);
236         terms.get(0).setTermDisplayName(null);
237         terms.get(0).setTermName(null);
238
239         PoxPayloadOut output = new PoxPayloadOut(TaxonomyAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
240         PayloadOutputPart commonPart = output.addPart(client.getItemCommonPartName(), taxon);
241         setupUpdateWithInvalidBody(); // we expect a failure here
242         res = client.updateItem(knownResourceId, knownItemResourceId, output);
243         try {
244             assertStatusCode(res, testName);
245         } finally {
246             res.close();
247         }
248     }
249
250     /**
251      * Read item list.
252      */
253     @Test(dataProvider = "testName", groups = {"readList"},
254     dependsOnMethods = {"readList"})
255     public void readItemList(String testName) {
256         readItemList(knownAuthorityWithItems, null);
257     }
258
259     /**
260      * Read item list by authority name.
261      */
262     @Test(dataProvider = "testName", groups = {"readList"},
263     dependsOnMethods = {"readItemList"})
264     public void readItemListByAuthorityName(String testName) {
265         readItemList(null, READITEMS_SHORT_IDENTIFIER);
266     }
267
268     /**
269      * Read item list.
270      *
271      * @param vcsid the vcsid
272      * @param name the name
273      */
274     private void readItemList(String vcsid, String shortId) {
275         String testName = "readItemList";
276
277         // Perform setup.
278         setupReadList();
279
280         // Submit the request to the service and store the response.
281         TaxonomyAuthorityClient client = new TaxonomyAuthorityClient();
282         Response res = null;
283         if (vcsid != null) {
284             res = client.readItemList(vcsid, null, null);
285         } else if (shortId != null) {
286             res = client.readItemListForNamedAuthority(shortId, null, null);
287         } else {
288             Assert.fail("readItemList passed null csid and name!");
289         }
290         try {
291             assertStatusCode(res, testName);
292             AbstractCommonList list = res.readEntity(AbstractCommonList.class);
293             int statusCode = res.getStatus();
294
295             // Check the status code of the response: does it match
296             // the expected response(s)?
297             if (logger.isDebugEnabled()) {
298                 logger.debug(testName + ": status = " + statusCode);
299             }
300             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
301                     invalidStatusCodeMessage(testRequestType, statusCode));
302             Assert.assertEquals(statusCode, testExpectedStatusCode);
303
304             List<AbstractCommonList.ListItem> items = list.getListItem();
305             int nItemsReturned = items.size();
306             // There will be 'nItemsToCreateInList'
307             // items created by the createItemList test,
308             // all associated with the same parent resource.
309             int nExpectedItems = nItemsToCreateInList;
310             if (logger.isDebugEnabled()) {
311                 logger.debug(testName + ": Expected "
312                         + nExpectedItems + " items; got: " + nItemsReturned);
313             }
314             Assert.assertEquals(nItemsReturned, nExpectedItems);
315
316             for (AbstractCommonList.ListItem item : items) {
317                 String value =
318                         AbstractCommonListUtils.ListItemGetElementValue(item, TaxonJAXBSchema.REF_NAME);
319                 Assert.assertTrue((null != value), "Item refName is null!");
320                 value =
321                         AbstractCommonListUtils.ListItemGetElementValue(item, TaxonJAXBSchema.TERM_DISPLAY_NAME);
322                 Assert.assertTrue((null != value), "Item termDisplayName is null!");
323             }
324             if (logger.isTraceEnabled()) {
325                 AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
326             }
327         } finally {
328             res.close();
329         }
330     }
331
332     @Override
333     public void delete(String testName) throws Exception {
334         // Do nothing.  See localDelete().  This ensure proper test order.
335     }
336
337     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})
338     public void localDelete(String testName) throws Exception {
339         super.delete(testName);
340     }
341
342     @Override
343     public void deleteItem(String testName) throws Exception {
344         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
345         // its dependencies will get run first and then we can call the base class' delete method.
346     }
347
348     @Test(dataProvider = "testName", groups = {"delete"},
349     dependsOnMethods = {"verifyIllegalItemDisplayName"})
350     public void localDeleteItem(String testName) throws Exception {
351         super.deleteItem(testName);
352     }
353
354     // ---------------------------------------------------------------
355     // Cleanup of resources created during testing
356     // ---------------------------------------------------------------
357     /**
358      * Deletes all resources created by tests, after all tests have been run.
359      *
360      * This cleanup method will always be run, even if one or more tests fail.
361      * For this reason, it attempts to remove all resources created at any point
362      * during testing, even if some of those resources may be expected to be
363      * deleted by certain tests.
364      */
365     @AfterClass(alwaysRun = true)
366     public void cleanUp() {
367         String noTest = System.getProperty("noTestCleanup");
368         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
369             if (logger.isDebugEnabled()) {
370                 logger.debug("Skipping Cleanup phase ...");
371             }
372             return;
373         }
374         if (logger.isDebugEnabled()) {
375             logger.debug("Cleaning up temporary resources created for testing ...");
376         }
377         String parentResourceId;
378         String itemResourceId;
379         // Clean up contact resources.
380         TaxonomyAuthorityClient client = new TaxonomyAuthorityClient();
381         parentResourceId = knownResourceId;
382         // Clean up item resources.
383         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
384             itemResourceId = entry.getKey();
385             parentResourceId = entry.getValue();
386             // Note: Any non-success responses from the delete operation
387             // below are ignored and not reported.
388             client.deleteItem(parentResourceId, itemResourceId).close();
389         }
390         
391         // Clean up parent resources.
392         for (String resourceId : allResourceIdsCreated) {
393             // Note: Any non-success responses from the delete operation
394             // below are ignored and not reported.
395             client.delete(resourceId).close();
396         }
397     }
398
399     // ---------------------------------------------------------------
400     // Utility methods used by tests above
401     // ---------------------------------------------------------------
402     /*
403      * (non-Javadoc) @see
404      * org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
405      */
406     /**
407      * Returns the root URL for the item service.
408      *
409      * This URL consists of a base URL for all services, followed by a path
410      * component for the owning parent, followed by the path component for the
411      * items.
412      *
413      * @param parentResourceIdentifier An identifier (such as a UUID) for the
414      * parent authority resource of the relevant item resource.
415      *
416      * @return The root URL for the item service.
417      */
418     protected String getItemServiceRootURL(String parentResourceIdentifier) {
419         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
420     }
421
422     /**
423      * Returns the URL of a specific item resource managed by a service, and
424      * designated by an identifier (such as a universally unique ID, or UUID).
425      *
426      * @param parentResourceIdentifier An identifier (such as a UUID) for the
427      * parent authority resource of the relevant item resource.
428      *
429      * @param itemResourceIdentifier An identifier (such as a UUID) for an item
430      * resource.
431      *
432      * @return The URL of a specific item resource managed by a service.
433      */
434     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
435         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
436     }
437
438     @Override
439     public void authorityTests(String testName) {
440         // TODO Auto-generated method stub
441     }
442
443     //
444     // Taxonomy authority specific instances
445     //
446     @Override
447     protected PoxPayloadOut createInstance(String commonPartName,
448             String identifier) {
449         String shortId = identifier;
450         String displayName = "displayName-" + shortId;
451         PoxPayloadOut multipart = TaxonomyAuthorityClientUtils.createTaxonomyAuthorityInstance(
452                 displayName, shortId, commonPartName);
453         return multipart;
454     }
455
456     @Override
457     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
458         String displayName = "displayName-NON_EXISTENT_ID";
459         PoxPayloadOut result = TaxonomyAuthorityClientUtils.createTaxonomyAuthorityInstance(
460                 displayName, "nonEx", commonPartName);
461         return result;
462     }
463
464     @Override
465     protected TaxonomyauthorityCommon updateInstance(
466             TaxonomyauthorityCommon taxonomyAuthority) {
467         TaxonomyauthorityCommon result = new TaxonomyauthorityCommon();
468
469         result.setDisplayName("updated-" + taxonomyAuthority.getDisplayName());
470         result.setVocabType("updated-" + taxonomyAuthority.getVocabType());
471
472         return result;
473     }
474
475     @Override
476     protected void compareUpdatedInstances(TaxonomyauthorityCommon original,
477             TaxonomyauthorityCommon updated) throws Exception {
478         // Verify that the updated resource received the correct data.
479         Assert.assertEquals(updated.getDisplayName(),
480                 original.getDisplayName(),
481                 "Display name in updated object did not match submitted data.");
482     }
483
484     //
485     // Authority item specific overrides
486     //
487     @Override
488     protected TaxonCommon updateItemInstance(TaxonCommon taxonCommon) {
489         TaxonCommon result = taxonCommon;
490         TaxonTermGroupList termList = taxonCommon.getTaxonTermGroupList();
491         Assert.assertNotNull(termList);
492         List<TaxonTermGroup> terms = termList.getTaxonTermGroup();
493         Assert.assertNotNull(terms);
494         Assert.assertTrue(terms.size() > 0);
495         terms.get(0).setTermDisplayName("updated-" + terms.get(0).getTermDisplayName());
496         terms.get(0).setTermName("updated-" + terms.get(0).getTermName());
497         result.setTaxonTermGroupList(termList);
498         return result;
499     }
500
501     @Override
502     protected void compareUpdatedItemInstances(TaxonCommon original,
503             TaxonCommon updated) throws Exception {
504
505         TaxonTermGroupList originalTermList = original.getTaxonTermGroupList();
506         Assert.assertNotNull(originalTermList);
507         List<TaxonTermGroup> originalTerms = originalTermList.getTaxonTermGroup();
508         Assert.assertNotNull(originalTerms);
509         Assert.assertTrue(originalTerms.size() > 0);
510
511         TaxonTermGroupList updatedTermList = updated.getTaxonTermGroupList();
512         Assert.assertNotNull(updatedTermList);
513         List<TaxonTermGroup> updatedTerms = updatedTermList.getTaxonTermGroup();
514         Assert.assertNotNull(updatedTerms);
515         Assert.assertTrue(updatedTerms.size() > 0);
516
517         Assert.assertEquals(updatedTerms.get(0).getTermDisplayName(),
518                 originalTerms.get(0).getTermDisplayName(),
519                 "Value in updated record did not match submitted data.");
520     }
521
522     @Override
523     protected void verifyReadItemInstance(TaxonCommon item) throws Exception {
524         
525         TaxonTermGroupList termList = item.getTaxonTermGroupList();
526         Assert.assertNotNull(termList);
527         List<TaxonTermGroup> terms = termList.getTaxonTermGroup();
528         Assert.assertNotNull(terms);
529         Assert.assertTrue(terms.size() > 0);
530         
531         String preferredTermName = terms.get(0).getTermName();
532         Assert.assertNotNull(preferredTermName, "Field value is unexpectedly null.");
533         Assert.assertEquals(preferredTermName, TEST_TAXON_FULL_NAME,
534                 "Field value " + preferredTermName
535                 + "does not match expected value " + TEST_TAXON_FULL_NAME);
536     }
537
538     @Override
539     protected PoxPayloadOut createNonExistenceItemInstance(
540             String commonPartName, String identifier) {
541         Map<String, String> nonexMap = new HashMap<String, String>();
542         nonexMap.put(TaxonJAXBSchema.NAME, TEST_TAXON_FULL_NAME);
543         nonexMap.put(TaxonJAXBSchema.SHORT_IDENTIFIER, "nonEx");
544         nonexMap.put(TaxonJAXBSchema.TERM_STATUS, TEST_TERM_STATUS);
545         final String EMPTY_REFNAME = "";
546         PoxPayloadOut result =
547                 TaxonomyAuthorityClientUtils.createTaxonInstance(EMPTY_REFNAME,
548                 nonexMap, NULL_TAXON_TERMS_LIST, NULL_TAXON_AUTHOR_GROUP_LIST, NULL_TAXON_CITATION_LIST,
549                 NULL_COMMON_NAME_GROUP_LIST, commonPartName);
550         return result;
551     }
552 }