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