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