]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
72962d01d2981c2778ceb41b155f210906be0782
[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.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import org.collectionspace.services.ConceptJAXBSchema;
30 import org.collectionspace.services.client.AbstractCommonListUtils;
31 import org.collectionspace.services.client.AuthorityClient;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.PayloadOutputPart;
34 import org.collectionspace.services.client.PoxPayloadIn;
35 import org.collectionspace.services.client.PoxPayloadOut;
36 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
37 import org.collectionspace.services.client.ConceptAuthorityClient;
38 import org.collectionspace.services.client.ConceptAuthorityClientUtils;
39 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.collectionspace.services.concept.ConceptauthoritiesCommon;
41 import org.collectionspace.services.concept.ConceptsCommon;
42 import org.dom4j.DocumentException;
43
44 import org.jboss.resteasy.client.ClientResponse;
45
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 /**
54  * ConceptAuthorityServiceTest, carries out tests against a
55  * deployed and running ConceptAuthority Service.
56  *
57  * $LastChangedRevision: 753 $
58  * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $
59  */
60 public class ConceptAuthorityServiceTest extends AbstractAuthorityServiceTest<ConceptauthoritiesCommon, ConceptsCommon> {
61
62         /** The logger. */
63     private final String CLASS_NAME = ConceptAuthorityServiceTest.class.getName();
64     private final Logger logger = LoggerFactory.getLogger(ConceptAuthorityServiceTest.class);
65     private final String REFNAME = "refName";
66     private final String DISPLAYNAME = "displayName";
67     private final static String CURRENT_DATE_UTC =
68         GregorianCalendarDateTimeUtils.currentDateUTC();
69
70         @Override
71         public String getServicePathComponent() {
72                 return ConceptAuthorityClient.SERVICE_PATH_COMPONENT;
73         }
74
75         @Override
76         protected String getServiceName() {
77                 return ConceptAuthorityClient.SERVICE_NAME;
78         }
79     
80     public String getItemServicePathComponent() {
81         return AuthorityClient.ITEMS;
82     }   
83     
84     // Instance variables specific to this test.
85     
86     final String TEST_NAME = "Concept 1";
87     final String TEST_SHORTID = "concept1";
88     final String TEST_SCOPE_NOTE = "Covers quite a bit";
89     // TODO Make status type be a controlled vocab term.
90     final String TEST_STATUS = "Approved";
91     
92     private String knownConceptTypeRefName = null;
93     
94     /* (non-Javadoc)
95      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
96      */
97     @Override
98     protected CollectionSpaceClient getClientInstance() {
99         return new ConceptAuthorityClient();
100     }
101     
102     /**
103      * Creates the item in authority.
104      *
105      * @param vcsid the vcsid
106      * @param authRefName the auth ref name
107      * @return the string
108      */
109         @Override
110         protected String createItemInAuthority(String authorityId) {
111
112         final String testName = "createItemInAuthority("+authorityId+")";
113         if(logger.isDebugEnabled()){
114             logger.debug(testName);
115         }
116
117         // Submit the request to the service and store the response.
118         ConceptAuthorityClient client = new ConceptAuthorityClient();
119         
120         String commonPartXML = createCommonPartXMLForItem(TEST_SHORTID, TEST_NAME);
121
122         String newID = null;
123         try {
124                 newID = ConceptAuthorityClientUtils.createItemInAuthority(authorityId,
125                         commonPartXML, client );
126         } catch( DocumentException de ) {
127             logger.error("Problem creating item from XML: "+de.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, TEST_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         ClientResponse<AbstractCommonList> 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.getEntity();
194             } finally {
195                 res.releaseConnection();
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, REFNAME);
213             Assert.assertTrue((null != value), "Item refName is null!");
214                 value = 
215                         AbstractCommonListUtils.ListItemGetElementValue(item, DISPLAYNAME);
216             Assert.assertTrue((null != value), "Item displayName 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).releaseConnection();
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).releaseConnection();
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         String commonPartXML = 
359                         "<ns2:concepts_common xmlns:ns2=\"http://collectionspace.org/services/concept\">" + 
360                 " <shortIdentifier>"+shortId+"</shortIdentifier>"+
361                 " <displayName>"+name+"</displayName>"+
362                 " <displayNameComputed>false</displayNameComputed>"+
363                 " <termStatus>Imagined</termStatus>"+
364                 /*
365                 " <conceptTermGroupList>"+
366                 "  <conceptTermGroup>"+
367                 "   <term>Another term</term>"+
368                 "   <termType>alternate</termType>"+
369                 "   <source>My Imagination</source>"+
370                 "  </conceptTermGroup>"+
371                 " </conceptTermGroupList>"+
372                 */
373                 "</ns2:concepts_common>";
374         return commonPartXML;
375     }
376
377         @Override
378     protected PoxPayloadOut createNonExistenceInstance(String commonPartName, String identifier) {
379         String displayName = "displayName-NON_EXISTENT_ID";
380         PoxPayloadOut result = ConceptAuthorityClientUtils.createConceptAuthorityInstance(
381                                 displayName, "nonEx", commonPartName);
382         return result;
383     }
384
385         @Override
386         protected ConceptauthoritiesCommon updateInstance(ConceptauthoritiesCommon conceptauthoritiesCommon) {
387                 ConceptauthoritiesCommon result = new ConceptauthoritiesCommon();
388                 
389                 result.setDisplayName("updated-" + conceptauthoritiesCommon.getDisplayName());
390                 result.setVocabType("updated-" + conceptauthoritiesCommon.getVocabType());
391                 
392                 return result;
393         }
394
395         @Override
396         protected void compareUpdatedInstances(ConceptauthoritiesCommon original,
397                         ConceptauthoritiesCommon updated) throws Exception {
398         Assert.assertEquals(updated.getDisplayName(),
399                         original.getDisplayName(),
400                 "Display name in updated object did not match submitted data.");
401         }
402
403         protected void compareReadInstances(ConceptauthoritiesCommon original,
404                         ConceptauthoritiesCommon fromRead) throws Exception {
405         Assert.assertNotNull(fromRead.getDisplayName());
406         Assert.assertNotNull(fromRead.getShortIdentifier());
407         Assert.assertNotNull(fromRead.getRefName());
408         }
409         
410         @Override
411         protected ConceptsCommon updateItemInstance(ConceptsCommon conceptsCommon) {
412                 ConceptsCommon result = new ConceptsCommon();
413                 
414         result.setTermStatus("updated-" + conceptsCommon.getTermStatus());
415                 result.setDisplayName("updated-" + conceptsCommon.getDisplayName());
416                 
417                 return result;
418         }
419
420         @Override
421         protected void compareUpdatedItemInstances(ConceptsCommon original,
422                         ConceptsCommon updated) throws Exception {
423         Assert.assertEquals(updated.getTermStatus(), original.getTermStatus(),
424                 "Data in updated Concept did not match submitted data.");
425         Assert.assertEquals(updated.getDisplayName(), original.getDisplayName(),
426                 "Data in updated Concept did not match submitted data.");
427         }
428
429         @Override
430         protected void verifyReadItemInstance(ConceptsCommon item)
431                         throws Exception {
432                 // TODO Auto-generated method stub
433                 
434         }
435
436
437         @Override
438         protected PoxPayloadOut createNonExistenceItemInstance(
439                         String commonPartName, String identifier) {
440
441                 String commonPartXML = createCommonPartXMLForItem("nonExShortId", "nonExItem");
442
443                 try {
444                 PoxPayloadOut result = 
445                         ConceptAuthorityClientUtils.createConceptInstance( 
446                                         commonPartXML, commonPartName);
447                         return result;
448         } catch( DocumentException de ) {
449             logger.error("Problem creating item from XML: "+de.getLocalizedMessage());
450             logger.debug("commonPartXML: "+commonPartXML);
451         }
452         return null;
453         }
454
455 }