]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b9afc75e60a1b1a6a397f005c9766c9c02bb94da
[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 import org.collectionspace.services.ConceptJAXBSchema;
28 import org.collectionspace.services.client.AbstractCommonListUtils;
29 import org.collectionspace.services.client.AuthorityClient;
30 import org.collectionspace.services.client.CollectionSpaceClient;
31 import org.collectionspace.services.client.ConceptAuthorityClient;
32 import org.collectionspace.services.client.ConceptAuthorityClientUtils;
33 import org.collectionspace.services.client.PoxPayloadOut;
34 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
35 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
36 import org.collectionspace.services.concept.ConceptTermGroup;
37 import org.collectionspace.services.concept.ConceptTermGroupList;
38 import org.collectionspace.services.concept.ConceptauthoritiesCommon;
39 import org.collectionspace.services.concept.ConceptsCommon;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.dom4j.DocumentException;
42 import org.jboss.resteasy.client.ClientResponse;
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
51  * deployed and running ConceptAuthority Service.
52  *
53  * $LastChangedRevision: 753 $
54  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
55  */
56 public class ConceptAuthorityServiceTest extends AbstractAuthorityServiceTest<ConceptauthoritiesCommon, ConceptsCommon> {
57
58         /** The logger. */
59     private final String CLASS_NAME = ConceptAuthorityServiceTest.class.getName();
60     private final Logger logger = LoggerFactory.getLogger(ConceptAuthorityServiceTest.class);
61     private final static String CURRENT_DATE_UTC =
62         GregorianCalendarDateTimeUtils.currentDateUTC();
63
64         @Override
65         public String getServicePathComponent() {
66                 return ConceptAuthorityClient.SERVICE_PATH_COMPONENT;
67         }
68
69         @Override
70         protected String getServiceName() {
71                 return ConceptAuthorityClient.SERVICE_NAME;
72         }
73     
74     public String getItemServicePathComponent() {
75         return AuthorityClient.ITEMS;
76     }   
77     
78     // Instance variables specific to this test.
79     
80     final String TEST_NAME = "Concept 1";
81     final String TEST_SHORTID = "concept1";
82     final String TEST_SCOPE_NOTE = "Covers quite a bit";
83     // TODO Make status type be a controlled vocab term.
84     final String TEST_STATUS = "Approved";
85     
86     private String knownRecordTypeRefName = null;
87     
88     /* (non-Javadoc)
89      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
90      */
91     @Override
92     protected CollectionSpaceClient getClientInstance() {
93         return new ConceptAuthorityClient();
94     }
95     
96     /**
97      * Creates the item in authority.
98      *
99      * @param vcsid the vcsid
100      * @param authRefName the auth ref name
101      * @return the string
102      */
103         @Override
104         protected String createItemInAuthority(String authorityId) {
105
106         final String testName = "createItemInAuthority("+authorityId+")";
107         if(logger.isDebugEnabled()){
108             logger.debug(testName);
109         }
110
111         // Submit the request to the service and store the response.
112         ConceptAuthorityClient client = new ConceptAuthorityClient();
113         
114         String commonPartXML = createCommonPartXMLForItem(TEST_SHORTID, TEST_NAME);
115
116         String newID = null;
117         try {
118                 newID = ConceptAuthorityClientUtils.createItemInAuthority(authorityId,
119                         commonPartXML, client );
120         } catch( Exception e ) {
121             logger.error("Problem creating item from XML: "+e.getLocalizedMessage());
122             logger.debug("commonPartXML: "+commonPartXML);
123             return null;
124         }
125
126         // Store the ID returned from the first item resource created
127         // for additional tests below.
128         if (knownItemResourceId == null){
129                 setKnownItemResource(newID, TEST_SHORTID);
130             if (logger.isDebugEnabled()) {
131                 logger.debug(testName + ": knownItemResourceId=" + newID);
132             }
133         }
134
135         // Store the IDs from any item resources created
136         // by tests, along with the IDs of their parents, so these items
137         // can be deleted after all tests have been run.
138         allResourceItemIdsCreated.put(newID, authorityId);
139
140         return newID;
141     }
142     
143     /**
144      * Read item list.
145      */
146     @Test(dataProvider = "testName", groups = {"readList"},
147                 dependsOnMethods = {"readList"})
148     public void readItemList(String testName) {
149         readItemList(knownAuthorityWithItems, null);
150     }
151
152     /**
153      * Read item list by authority name.
154      */
155     @Test(dataProvider = "testName", groups = {"readList"},
156                 dependsOnMethods = {"readItemList"})
157     public void readItemListByAuthorityName(String testName) {
158         readItemList(null, READITEMS_SHORT_IDENTIFIER);
159     }
160     
161     /**
162      * Read item list.
163      *
164      * @param vcsid the vcsid
165      * @param name the name
166      */
167     private void readItemList(String vcsid, String shortId) {
168
169         String testName = "readItemList";
170
171         // Perform setup.
172         setupReadList();
173         
174         // Submit the request to the service and store the response.
175         ConceptAuthorityClient client = new ConceptAuthorityClient();
176         ClientResponse<AbstractCommonList> res = null;
177         if(vcsid!= null) {
178                 res = client.readItemList(vcsid, null, null);
179         } else if(shortId!= null) {
180                 res = client.readItemListForNamedAuthority(shortId, null, null);
181         } else {
182                 Assert.fail("readItemList passed null csid and name!");
183         }
184                 AbstractCommonList list = null;
185         try {
186             assertStatusCode(res, testName);
187                 list = res.getEntity();
188             } finally {
189                 res.releaseConnection();
190             }
191         List<AbstractCommonList.ListItem> items =
192             list.getListItem();
193         int nItemsReturned = items.size();
194                 // There will be 'nItemsToCreateInList'
195                 // items created by the createItemList test,
196                 // all associated with the same parent resource.
197                 int nExpectedItems = nItemsToCreateInList;
198         if(logger.isDebugEnabled()){
199             logger.debug(testName + ": Expected "
200                         + nExpectedItems +" items; got: "+nItemsReturned);
201         }
202         Assert.assertEquals(nItemsReturned, nExpectedItems);
203
204         for (AbstractCommonList.ListItem item : items) {
205                 String value = 
206                         AbstractCommonListUtils.ListItemGetElementValue(item, ConceptJAXBSchema.REF_NAME);
207             Assert.assertTrue((null != value), "Item refName is null!");
208                 value = 
209                         AbstractCommonListUtils.ListItemGetElementValue(item, ConceptJAXBSchema.TERM_DISPLAY_NAME);
210             Assert.assertTrue((null != value), "Item termDisplayName is null!");
211         }
212         if(logger.isTraceEnabled()){
213                 AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName);
214         }
215     }
216
217    @Override
218    public void delete(String testName) throws Exception {
219         // Do nothing.  See localDelete().  This ensure proper test order.
220    }
221    
222    @Test(dataProvider = "testName", dependsOnMethods = {"localDeleteItem"})    
223    public void localDelete(String testName) throws Exception {
224         super.delete(testName);
225    }
226
227    @Override
228    public void deleteItem(String testName) throws Exception {
229         // Do nothing.  We need to wait until after the test "localDelete" gets run.  When it does,
230         // its dependencies will get run first and then we can call the base class' delete method.
231    }
232    
233    @Test(dataProvider = "testName", groups = {"delete"},
234                    dependsOnMethods = {"readItem", "updateItem"})
235    public void localDeleteItem(String testName) throws Exception {
236            super.deleteItem(testName);
237    }
238
239
240    
241    // ---------------------------------------------------------------
242    // Cleanup of resources created during testing
243    // ---------------------------------------------------------------
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
250     * at any point during testing, even if some of those resources
251     * may be expected to be deleted by certain tests.
252     */
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        ConceptAuthorityClient client = new ConceptAuthorityClient();
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).releaseConnection();
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).releaseConnection();
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    /**
295     * Returns the root URL for the item service.
296     *
297     * This URL consists of a base URL for all services, followed by
298     * a path component for the owning parent, followed by the
299     * path component for the items.
300     *
301     * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
302     * parent authority resource of the relevant item resource.
303     *
304     * @return The root URL for the item service.
305     */
306    protected String getItemServiceRootURL(String parentResourceIdentifier) {
307        return getResourceURL(parentResourceIdentifier) + "/" + getItemServicePathComponent();
308    }
309
310    /**
311     * Returns the URL of a specific item resource managed by a service, and
312     * designated by an identifier (such as a universally unique ID, or UUID).
313     *
314     * @param  parentResourceIdentifier  An identifier (such as a UUID) for the
315     * parent authority resource of the relevant item resource.
316     *
317     * @param  itemResourceIdentifier  An identifier (such as a UUID) for an
318     * item resource.
319     *
320     * @return The URL of a specific item resource managed by a service.
321     */
322    protected String getItemResourceURL(String parentResourceIdentifier, String itemResourceIdentifier) {
323        return getItemServiceRootURL(parentResourceIdentifier) + "/" + itemResourceIdentifier;
324    }
325
326         @Override
327         public void authorityTests(String testName) {
328                 // TODO Auto-generated method stub
329                 
330         }
331
332         //
333         // Concept specific overrides
334         //
335         
336     @Override
337         protected PoxPayloadOut createInstance(String commonPartName,
338                         String identifier) {
339         ConceptAuthorityClient client = new ConceptAuthorityClient();
340         String shortId = identifier;
341         String displayName = "displayName-" + shortId;
342         // String baseRefName = ConceptAuthorityClientUtils.createConceptAuthRefName(shortId, null);
343         PoxPayloadOut multipart = 
344             ConceptAuthorityClientUtils.createConceptAuthorityInstance(
345             displayName, shortId, commonPartName);
346         return multipart;
347     }
348         
349
350     private String createCommonPartXMLForItem(String shortId, String name ) {
351         
352         StringBuilder commonPartXML = new StringBuilder("");
353         commonPartXML.append("<ns2:concepts_common xmlns:ns2=\"http://collectionspace.org/services/concept\">");
354         commonPartXML.append("    <shortIdentifier>"+shortId+"</shortIdentifier>");
355         commonPartXML.append("    <conceptTermGroupList>");
356         commonPartXML.append("        <conceptTermGroup>");
357         commonPartXML.append("            <termDisplayName>"+name+"</termDisplayName>");
358         commonPartXML.append("            <termName>"+name+"</termName>");
359         commonPartXML.append("            <termStatus>"+name+"</termStatus>");
360         commonPartXML.append("        </conceptTermGroup>");
361         commonPartXML.append("    </conceptTermGroupList>");
362         commonPartXML.append("</ns2:concepts_common>");
363         return commonPartXML.toString();
364     }
365
366         @Override
367     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
368         String displayName = "displayName-NON_EXISTENT_ID";
369         PoxPayloadOut result = ConceptAuthorityClientUtils.createConceptAuthorityInstance(
370                                 displayName, "nonEx", commonPartName);
371         return result;
372     }
373
374         @Override
375         protected ConceptauthoritiesCommon updateInstance(ConceptauthoritiesCommon conceptauthoritiesCommon) {
376                 ConceptauthoritiesCommon result = new ConceptauthoritiesCommon();
377                 
378                 result.setDisplayName("updated-" + conceptauthoritiesCommon.getDisplayName());
379                 result.setVocabType("updated-" + conceptauthoritiesCommon.getVocabType());
380                 
381                 return result;
382         }
383
384         @Override
385         protected void compareUpdatedInstances(ConceptauthoritiesCommon original,
386                         ConceptauthoritiesCommon updated) throws Exception {
387         Assert.assertEquals(updated.getDisplayName(),
388                         original.getDisplayName(),
389                 "Display name in updated object did not match submitted data.");
390         }
391
392         @Override
393         protected void compareReadInstances(ConceptauthoritiesCommon original,
394                         ConceptauthoritiesCommon fromRead) throws Exception {
395         Assert.assertNotNull(fromRead.getDisplayName());
396         Assert.assertNotNull(fromRead.getShortIdentifier());
397         Assert.assertNotNull(fromRead.getRefName());
398         }
399         
400         @Override
401         protected ConceptsCommon updateItemInstance(ConceptsCommon conceptsCommon) {
402             ConceptsCommon result = conceptsCommon;
403             ConceptTermGroupList termList = conceptsCommon.getConceptTermGroupList();
404             Assert.assertNotNull(termList);
405             List<ConceptTermGroup> terms = termList.getConceptTermGroup();
406             Assert.assertNotNull(terms);
407             Assert.assertTrue(terms.size() > 0);
408             terms.get(0).setTermDisplayName("updated-" + terms.get(0).getTermDisplayName());
409             terms.get(0).setTermName("updated-" + terms.get(0).getTermName());
410             terms.get(0).setTermStatus("updated-" + terms.get(0).getTermStatus());
411             result.setConceptTermGroupList(termList);
412             return result;
413         }
414
415         @Override
416         protected void compareUpdatedItemInstances(ConceptsCommon original,
417                         ConceptsCommon updated) throws Exception {
418             ConceptTermGroupList originalTermList = original.getConceptTermGroupList();
419             Assert.assertNotNull(originalTermList);
420             List<ConceptTermGroup> originalTerms = originalTermList.getConceptTermGroup();
421             Assert.assertNotNull(originalTerms);
422             Assert.assertTrue(originalTerms.size() > 0);
423             
424             ConceptTermGroupList updatedTermList = updated.getConceptTermGroupList();
425             Assert.assertNotNull(updatedTermList);
426             List<ConceptTermGroup> updatedTerms = updatedTermList.getConceptTermGroup();
427             Assert.assertNotNull(updatedTerms);
428             Assert.assertTrue(updatedTerms.size() > 0);
429             
430             Assert.assertEquals(updatedTerms.get(0).getTermDisplayName(),
431                 originalTerms.get(0).getTermDisplayName(),
432                 "Value in updated record did not match submitted data.");
433             Assert.assertEquals(updatedTerms.get(0).getTermStatus(),
434                 originalTerms.get(0).getTermDisplayName(),
435                 "Value in updated record did not match submitted data.");
436         }
437
438         @Override
439         protected void verifyReadItemInstance(ConceptsCommon item)
440                         throws Exception {
441                 // TODO Auto-generated method stub
442                 
443         }
444
445
446         @Override
447         protected PoxPayloadOut createNonExistenceItemInstance(
448                         String commonPartName, String identifier) {
449
450                 String commonPartXML = createCommonPartXMLForItem("nonExShortId", "nonExItem");
451
452                 try {
453                 PoxPayloadOut result = 
454                         ConceptAuthorityClientUtils.createConceptInstance( 
455                                         commonPartXML, commonPartName);
456                         return result;
457         } catch( DocumentException de ) {
458             logger.error("Problem creating item from XML: "+de.getLocalizedMessage());
459             logger.debug("commonPartXML: "+commonPartXML);
460         }
461         return null;
462         }
463
464 }