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