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