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