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