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