]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
98f99d3f20af84d3e29a7c3956b146fc3b8c0852
[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.List;
25 import java.util.Map;
26 import org.collectionspace.services.CitationJAXBSchema;
27 import org.collectionspace.services.citation.CitationTermGroup;
28 import org.collectionspace.services.citation.CitationTermGroupList;
29 import org.collectionspace.services.citation.CitationauthoritiesCommon;
30 import org.collectionspace.services.citation.CitationsCommon;
31 import org.collectionspace.services.client.AbstractCommonListUtils;
32 import org.collectionspace.services.client.AuthorityClient;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.CitationAuthorityClient;
35 import org.collectionspace.services.client.CitationAuthorityClientUtils;
36 import org.collectionspace.services.client.PoxPayloadOut;
37 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
38 import org.collectionspace.services.jaxb.AbstractCommonList;
39 import org.dom4j.DocumentException;
40 import org.jboss.resteasy.client.ClientResponse;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.testng.Assert;
44 import org.testng.annotations.AfterClass;
45 import org.testng.annotations.Test;
46
47 /**
48  * ConceptAuthorityServiceTest, carries out tests against a deployed and running
49  * ConceptAuthority Service.
50  *
51  * $LastChangedRevision: 753 $ $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed,
52  * 23 Sep 2009) $
53  */
54 public class CitationAuthorityServiceTest extends AbstractAuthorityServiceTest<CitationauthoritiesCommon, CitationsCommon> {
55
56     /**
57      * The logger.
58      */
59     private final String CLASS_NAME = CitationAuthorityServiceTest.class.getName();
60     private final Logger logger = LoggerFactory.getLogger(CitationAuthorityServiceTest.class);
61     private final static String CURRENT_DATE_UTC =
62             GregorianCalendarDateTimeUtils.currentDateUTC();
63     // Instance variables specific to this test.
64     final String TEST_NAME = "Citation 1";
65     final String TEST_SHORTID = "citation1";
66     final String TEST_SCOPE_NOTE = "A representative citation";
67     // TODO Make status type be a controlled vocab term.
68     final String TEST_STATUS = "Approved";
69
70     @Override
71     public String getServicePathComponent() {
72         return CitationAuthorityClient.SERVICE_PATH_COMPONENT;
73     }
74
75     @Override
76     protected String getServiceName() {
77         return CitationAuthorityClient.SERVICE_NAME;
78     }
79
80     public String getItemServicePathComponent() {
81         return AuthorityClient.ITEMS;
82     }
83
84     /* (non-Javadoc)
85      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
86      */
87     @Override
88     protected CollectionSpaceClient getClientInstance() {
89         return new CitationAuthorityClient();
90     }
91
92     /**
93      * Creates an item in an authority.
94      *
95      * @param authorityId an identifier for the authority item
96      * @return the string
97      */
98     @Override
99     protected String createItemInAuthority(String authorityId) {
100
101         final String testName = "createItemInAuthority(" + authorityId + ")";
102         if (logger.isDebugEnabled()) {
103             logger.debug(testName);
104         }
105
106         // Submit the request to the service and store the response.
107         CitationAuthorityClient client = new CitationAuthorityClient();
108
109         String commonPartXML = createCommonPartXMLForItem(TEST_SHORTID, TEST_NAME);
110
111         String newID;
112         try {
113             newID = CitationAuthorityClientUtils.createItemInAuthority(authorityId,
114                     commonPartXML, client);
115         } catch (Exception e) {
116             logger.error("Problem creating item from XML: " + e.getLocalizedMessage());
117             logger.debug("commonPartXML: " + commonPartXML);
118             return null;
119         }
120
121         // Store the ID returned from the first item resource created
122         // for additional tests below.
123         if (knownItemResourceId == null) {
124             setKnownItemResource(newID, TEST_SHORTID);
125             if (logger.isDebugEnabled()) {
126                 logger.debug(testName + ": knownItemResourceId=" + newID);
127             }
128         }
129
130         // Store the IDs from any item resources created
131         // by tests, along with the IDs of their parents, so these items
132         // can be deleted after all tests have been run.
133         allResourceItemIdsCreated.put(newID, authorityId);
134
135         return newID;
136     }
137
138     /**
139      * Read item list.
140      */
141     @Test(dataProvider = "testName", groups = {"readList"},
142             dependsOnMethods = {"readList"})
143     public void readItemList(String testName) {
144         readItemList(knownAuthorityWithItems, null);
145     }
146
147     /**
148      * Read item list by authority name.
149      */
150     @Test(dataProvider = "testName", groups = {"readList"},
151             dependsOnMethods = {"readItemList"})
152     public void readItemListByAuthorityName(String testName) {
153         readItemList(null, READITEMS_SHORT_IDENTIFIER);
154     }
155
156     /**
157      * Read item list.
158      *
159      * @param vcsid the vcsid
160      * @param name the name
161      */
162     private void readItemList(String vcsid, String shortId) {
163
164         String testName = "readItemList";
165
166         // Perform setup.
167         setupReadList();
168
169         // Submit the request to the service and store the response.
170         CitationAuthorityClient client = new CitationAuthorityClient();
171         ClientResponse<AbstractCommonList> res = null;
172         if (vcsid != null) {
173             res = client.readItemList(vcsid, null, null);
174         } else if (shortId != null) {
175             res = client.readItemListForNamedAuthority(shortId, null, null);
176         } else {
177             Assert.fail("readItemList passed null csid and name!");
178         }
179         AbstractCommonList list = null;
180         try {
181             assertStatusCode(res, testName);
182             list = res.getEntity();
183         } finally {
184             res.releaseConnection();
185         }
186         List<AbstractCommonList.ListItem> items =
187                 list.getListItem();
188         int nItemsReturned = items.size();
189         // There will be 'nItemsToCreateInList'
190         // items created by the createItemList test,
191         // all associated with the same parent resource.
192         int nExpectedItems = nItemsToCreateInList;
193         if (logger.isDebugEnabled()) {
194             logger.debug(testName + ": Expected "
195                     + nExpectedItems + " items; got: " + nItemsReturned);
196         }
197         Assert.assertEquals(nItemsReturned, nExpectedItems);
198
199         for (AbstractCommonList.ListItem item : items) {
200             String value =
201                     AbstractCommonListUtils.ListItemGetElementValue(item, CitationJAXBSchema.REF_NAME);
202             Assert.assertTrue((null != value), "Item refName is null!");
203             value =
204                     AbstractCommonListUtils.ListItemGetElementValue(item, CitationJAXBSchema.TERM_DISPLAY_NAME);
205             Assert.assertTrue((null != value), "Item termDisplayName is null!");
206         }
207         if (logger.isTraceEnabled()) {
208             AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
209         }
210     }
211
212     @Override
213     public void delete(String testName) throws Exception {
214         // Do nothing.  See localDelete().  This ensure proper test order.
215     }
216
217     @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})
218     public void localDelete(String testName) throws Exception {
219         super.delete(testName);
220     }
221
222     @Override
223     public void deleteItem(String testName) throws Exception {
224         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
225         // its dependencies will get run first and then we can call the base class' delete method.
226     }
227
228     @Test(dataProvider = "testName", groups = {"delete"},
229             dependsOnMethods = {"readItem", "updateItem"})
230     public void localDeleteItem(String testName) throws Exception {
231         super.deleteItem(testName);
232     }
233
234     // ---------------------------------------------------------------
235     // Cleanup of resources created during testing
236     // ---------------------------------------------------------------
237     /**
238      * Deletes all resources created by tests, after all tests have been run.
239      *
240      * This cleanup method will always be run, even if one or more tests fail.
241      * For this reason, it attempts to remove all resources created at any point
242      * during testing, even if some of those resources may be expected to be
243      * deleted by certain tests.
244      */
245     @AfterClass(alwaysRun = true)
246     public void cleanUp() {
247         String noTest = System.getProperty("noTestCleanup");
248         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
249             if (logger.isDebugEnabled()) {
250                 logger.debug("Skipping Cleanup phase ...");
251             }
252             return;
253         }
254         if (logger.isDebugEnabled()) {
255             logger.debug("Cleaning up temporary resources created for testing ...");
256         }
257         String parentResourceId;
258         String itemResourceId;
259         // Clean up contact resources.
260         CitationAuthorityClient client = new CitationAuthorityClient();
261         parentResourceId = knownResourceId;
262         // Clean up item resources.
263         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
264             itemResourceId = entry.getKey();
265             parentResourceId = entry.getValue();
266             // Note: Any non-success responses from the delete operation
267             // below are ignored and not reported.
268             client.deleteItem(parentResourceId, itemResourceId).close();
269         }
270         // Clean up parent resources.
271         for (String resourceId : allResourceIdsCreated) {
272             // Note: Any non-success responses from the delete operation
273             // below are ignored and not reported.
274             client.delete(resourceId).close();
275         }
276     }
277
278     // ---------------------------------------------------------------
279     // Utility methods used by tests above
280     // ---------------------------------------------------------------
281    /* (non-Javadoc)
282      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
283      */
284     /**
285      * Returns the root URL for the item service.
286      *
287      * This URL consists of a base URL for all services, followed by a path
288      * component for the owning parent, followed by the path component for the
289      * items.
290      *
291      * @param parentResourceIdentifier An identifier (such as a UUID) for the
292      * parent authority resource of the relevant item resource.
293      *
294      * @return The root URL for the item service.
295      */
296     protected String getItemServiceRootURL(String parentResourceIdentifier) {
297         return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
298     }
299
300     /**
301      * Returns the URL of a specific item resource managed by a service, and
302      * designated by an identifier (such as a universally unique ID, or UUID).
303      *
304      * @param parentResourceIdentifier An identifier (such as a UUID) for the
305      * parent authority resource of the relevant item resource.
306      *
307      * @param itemResourceIdentifier An identifier (such as a UUID) for an item
308      * resource.
309      *
310      * @return The URL of a specific item resource managed by a service.
311      */
312     protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
313         return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
314     }
315
316     @Override
317     public void authorityTests(String testName) {
318         // TODO Auto-generated method stub
319     }
320
321     //
322     // Concept specific overrides
323     //
324     @Override
325     protected PoxPayloadOut createInstance(String commonPartName,
326             String identifier) {
327         CitationAuthorityClient client = new CitationAuthorityClient();
328         String shortId = identifier;
329         String displayName = "displayName-" + shortId;
330         PoxPayloadOut multipart =
331                 CitationAuthorityClientUtils.createCitationAuthorityInstance(
332                 displayName, shortId, commonPartName);
333         return multipart;
334     }
335
336     private String createCommonPartXMLForItem(String shortId, String name) {
337
338         StringBuilder commonPartXML = new StringBuilder("");
339         commonPartXML.append("<ns2:citations_common xmlns:ns2=\"http://collectionspace.org/services/citation\">");
340         commonPartXML.append("    <shortIdentifier>" + shortId + "</shortIdentifier>");
341         commonPartXML.append("    <citationTermGroupList>");
342         commonPartXML.append("        <citationTermGroup>");
343         commonPartXML.append("            <termDisplayName>" + name + "</termDisplayName>");
344         commonPartXML.append("            <termName>" + name + "</termName>");
345         commonPartXML.append("            <termStatus>" + name + "</termStatus>");
346         commonPartXML.append("        </citationTermGroup>");
347         commonPartXML.append("    </citationTermGroupList>");
348         commonPartXML.append("</ns2:citations_common>");
349         return commonPartXML.toString();
350     }
351
352     @Override
353     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
354         String displayName = "displayName-NON_EXISTENT_ID";
355         PoxPayloadOut result = CitationAuthorityClientUtils.createCitationAuthorityInstance(
356                 displayName, "nonEx", commonPartName);
357         return result;
358     }
359
360     @Override
361     protected CitationauthoritiesCommon updateInstance(CitationauthoritiesCommon citationauthoritiesCommon) {
362         CitationauthoritiesCommon result = new CitationauthoritiesCommon();
363
364         result.setDisplayName("updated-" + citationauthoritiesCommon.getDisplayName());
365         result.setVocabType("updated-" + citationauthoritiesCommon.getVocabType());
366
367         return result;
368     }
369
370     @Override
371     protected void compareUpdatedInstances(CitationauthoritiesCommon original,
372             CitationauthoritiesCommon updated) throws Exception {
373         Assert.assertEquals(updated.getDisplayName(),
374                 original.getDisplayName(),
375                 "Display name in updated object did not match submitted data.");
376     }
377
378     @Override
379     protected void compareReadInstances(CitationauthoritiesCommon original,
380             CitationauthoritiesCommon fromRead) throws Exception {
381         Assert.assertNotNull(fromRead.getDisplayName());
382         Assert.assertNotNull(fromRead.getShortIdentifier());
383         Assert.assertNotNull(fromRead.getRefName());
384     }
385
386     @Override
387     protected CitationsCommon updateItemInstance(CitationsCommon citationsCommon) {
388         CitationsCommon result = citationsCommon;
389         CitationTermGroupList termList = citationsCommon.getCitationTermGroupList();
390         Assert.assertNotNull(termList);
391         List<CitationTermGroup> terms = termList.getCitationTermGroup();
392         Assert.assertNotNull(terms);
393         Assert.assertTrue(terms.size() > 0);
394         terms.get(0).setTermDisplayName("updated-" + terms.get(0).getTermDisplayName());
395         terms.get(0).setTermName("updated-" + terms.get(0).getTermName());
396         terms.get(0).setTermStatus("updated-" + terms.get(0).getTermStatus());
397         result.setCitationTermGroupList(termList);
398         return result;
399     }
400
401     @Override
402     protected void compareUpdatedItemInstances(CitationsCommon original,
403             CitationsCommon updated) throws Exception {
404         CitationTermGroupList originalTermList = original.getCitationTermGroupList();
405         Assert.assertNotNull(originalTermList);
406         List<CitationTermGroup> originalTerms = originalTermList.getCitationTermGroup();
407         Assert.assertNotNull(originalTerms);
408         Assert.assertTrue(originalTerms.size() > 0);
409
410         CitationTermGroupList updatedTermList = updated.getCitationTermGroupList();
411         Assert.assertNotNull(updatedTermList);
412         List<CitationTermGroup> updatedTerms = updatedTermList.getCitationTermGroup();
413         Assert.assertNotNull(updatedTerms);
414         Assert.assertTrue(updatedTerms.size() > 0);
415
416         Assert.assertEquals(updatedTerms.get(0).getTermDisplayName(),
417                 originalTerms.get(0).getTermDisplayName(),
418                 "Value in updated record did not match submitted data.");
419         Assert.assertEquals(updatedTerms.get(0).getTermStatus(),
420                 originalTerms.get(0).getTermDisplayName(),
421                 "Value in updated record did not match submitted data.");
422     }
423
424     @Override
425     protected void verifyReadItemInstance(CitationsCommon item)
426             throws Exception {
427         // TODO Auto-generated method stub
428     }
429
430     @Override
431     protected PoxPayloadOut createNonExistenceItemInstance(
432             String commonPartName, String identifier) {
433
434         String commonPartXML = createCommonPartXMLForItem("nonExShortId", "nonExItem");
435
436         try {
437             PoxPayloadOut result =
438                     CitationAuthorityClientUtils.createCitationInstance(
439                     commonPartXML, commonPartName);
440             return result;
441         } catch (DocumentException de) {
442             logger.error("Problem creating item from XML: " + de.getLocalizedMessage());
443             logger.debug("commonPartXML: " + commonPartXML);
444         }
445         return null;
446     }
447 }