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