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