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