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