]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
4d24ebd97e5aec94f64d1278329e91f5ddef2bec
[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 © 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.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.ws.rs.core.Response;
31
32 import org.collectionspace.services.PersonJAXBSchema;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.ConservationClient;
35 import org.collectionspace.services.client.PersonAuthorityClient;
36 import org.collectionspace.services.client.PersonAuthorityClientUtils;
37 import org.collectionspace.services.client.PayloadOutputPart;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.authorityref.AuthorityRefList;
41 import org.collectionspace.services.jaxb.AbstractCommonList;
42 import org.collectionspace.services.conservation.ConservationCommon;
43 import org.collectionspace.services.conservation.ConservatorsList;
44 import org.collectionspace.services.conservation.DestAnalysisGroup;
45 import org.collectionspace.services.conservation.DestAnalysisGroupList;
46 import org.collectionspace.services.conservation.ExaminationGroup;
47 import org.collectionspace.services.conservation.ExaminationGroupList;
48 import org.collectionspace.services.conservation.OtherPartyGroup;
49 import org.collectionspace.services.conservation.OtherPartyGroupList;
50 import org.collectionspace.services.person.PersonTermGroup;
51
52 import org.testng.Assert;
53 import org.testng.annotations.AfterClass;
54 import org.testng.annotations.Test;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * ConservationAuthRefsTest, carries out Authority References tests against a
60  * deployed and running Conservation Service.
61  *
62  * $LastChangedRevision$
63  * $LastChangedDate$
64  */
65 public class ConservationAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
66
67     private final String CLASS_NAME = ConservationAuthRefsTest.class.getName();
68     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
69     
70     // Instance variables specific to this test.
71     final String SERVICE_NAME = "conservation";
72     final String SERVICE_PATH_COMPONENT = "conservation";
73     final String PERSON_AUTHORITY_NAME = "TestPersonAuthForConservation";
74     private String knownResourceId = null;
75     private List<String> conservationIdsCreated = new ArrayList<String>();
76     private List<String> personIdsCreated = new ArrayList<String>();
77     private String personAuthCSID = null;
78     private String conservatorRefName = null;
79     private String otherPartyRefName = null;
80     private String examinationStaffRefName = null;
81     private String approvedByRefName = null;
82     private String researcherRefName = null;
83     private String sampleByRefName = null;
84     private final int NUM_AUTH_REFS_EXPECTED = 6;
85
86     /* (non-Javadoc)
87      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
88      */
89     @Override
90     protected CollectionSpaceClient getClientInstance() {
91         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
92     }
93
94         @Override
95         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
96         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
97         }
98         
99     /* (non-Javadoc)
100      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
101      */
102     @Override
103         protected AbstractCommonList getCommonList(Response response) {
104         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
105     }
106
107     // ---------------------------------------------------------------
108     // CRUD tests : CREATE tests
109     // ---------------------------------------------------------------
110     // Success outcomes
111     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
112     public void createWithAuthRefs(String testName) throws Exception {
113         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
114
115         // Submit the request to the service and store the response.
116         String identifier = createIdentifier();
117         
118         // Create all the person refs and entities
119         createPersonRefs();
120
121         // Create a new Conservation resource.
122         //
123         // One or more fields in this resource will be PersonAuthority
124         // references, and will refer to Person resources by their refNames.
125         ConservationClient conservationClient = new ConservationClient();
126         PoxPayloadOut multipart = createConservationInstance(
127                 "conservationNumber-" + identifier,
128                 conservatorRefName,
129                 otherPartyRefName,
130                 examinationStaffRefName,
131                 approvedByRefName,
132                 researcherRefName,
133                 sampleByRefName);
134         Response response = conservationClient.create(multipart);
135         int statusCode = response.getStatus();
136         try {
137             // Check the status code of the response: does it match
138             // the expected response(s)?
139             //
140             // Specifically:
141             // Does it fall within the set of valid status codes?
142             // Does it exactly match the expected status code?
143             if(logger.isDebugEnabled()){
144                 logger.debug(testName + ": status = " + statusCode);
145             }
146             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
147                     invalidStatusCodeMessage(testRequestType, statusCode));
148             Assert.assertEquals(statusCode, testExpectedStatusCode);
149
150             // Store the ID returned from the first resource created
151             // for additional tests below.
152             if (knownResourceId == null){
153                 knownResourceId = extractId(response);
154                 if (logger.isDebugEnabled()) {
155                     logger.debug(testName + ": knownResourceId=" + knownResourceId);
156                 }
157             }
158         
159             // Store the IDs from every resource created by tests,
160             // so they can be deleted after tests have been run.
161             conservationIdsCreated.add(extractId(response));
162         } finally {
163                 response.close();
164         }
165     }
166     
167     protected void createPersonRefs(){
168         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
169         // Create a temporary PersonAuthority resource, and its corresponding
170         // refName by which it can be identified.
171         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
172             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
173         Response res = personAuthClient.create(multipart);
174         try {
175                int statusCode = res.getStatus();
176                Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
177                    invalidStatusCodeMessage(testRequestType, statusCode));
178                Assert.assertEquals(statusCode, STATUS_CREATED);
179                personAuthCSID = extractId(res);
180         } finally {
181                res.close();
182         }
183
184         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
185         // Create temporary Person resources, and their corresponding refNames
186         // by which they can be identified.
187         String csid = createPerson("Connie", "Conservator", "connieConservator", authRefName);
188         personIdsCreated.add(csid);
189         conservatorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
190
191         csid = createPerson("Oliver", "Otherparty", "oliverOtherparty", authRefName);
192         personIdsCreated.add(csid);
193         otherPartyRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
194
195         csid = createPerson("Steven", "Staff", "stevenStaff", authRefName);
196         personIdsCreated.add(csid);
197         examinationStaffRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
198         
199         csid = createPerson("Allison", "Approver", "allisonApprover", authRefName);
200         personIdsCreated.add(csid);
201         approvedByRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
202
203         csid = createPerson("Rachel", "Researcher", "rachelResearcher", authRefName);
204         personIdsCreated.add(csid);
205         researcherRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
206
207         csid = createPerson("Sabrina", "Sampler", "sabrinaSampler", authRefName);
208         personIdsCreated.add(csid);
209         sampleByRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
210     }
211     
212     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
213         String result = null;
214        
215         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
216         Map<String, String> personInfo = new HashMap<String,String>();
217         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
218         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
219         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
220         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
221         PersonTermGroup term = new PersonTermGroup();
222         String termName = firstName + " " + surName;
223         term.setTermDisplayName(termName);
224         term.setTermName(termName);
225         personTerms.add(term);
226         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
227                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
228       
229         Response res = personAuthClient.createItem(personAuthCSID, multipart);
230         try {
231             int statusCode = res.getStatus();
232             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
233                 invalidStatusCodeMessage(testRequestType, statusCode));
234             Assert.assertEquals(statusCode, STATUS_CREATED);
235             result = extractId(res);
236         } finally {
237             res.close();
238         }
239
240         return result;
241     }
242
243     // Success outcomes
244     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
245         dependsOnMethods = {"createWithAuthRefs"})
246     public void readAndCheckAuthRefs(String testName) throws Exception {
247         // Perform setup.
248         testSetup(STATUS_OK, ServiceRequestType.READ);
249
250         // Submit the request to the service and store the response.
251         ConservationClient conservationClient = new ConservationClient();
252         Response res = conservationClient.read(knownResourceId);
253         ConservationCommon conservationCommon = null;
254         try {
255                 assertStatusCode(res, testName);
256                 // Extract the common part from the response.
257                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
258                 conservationCommon = (ConservationCommon) extractPart(input,
259                     conservationClient.getCommonPartName(), ConservationCommon.class);
260                 Assert.assertNotNull(conservationCommon);
261                 if(logger.isDebugEnabled()){
262                     logger.debug(objectAsXmlString(conservationCommon, ConservationCommon.class));
263                 }
264         } finally {
265                 if (res != null) {
266                 res.close();
267             }
268         }
269         //
270         // Check a couple of fields
271         //
272         Assert.assertEquals(conservationCommon.getApprovedBy(), approvedByRefName);
273         Assert.assertEquals(conservationCommon.getResearcher(), researcherRefName);
274         
275         // Get the auth refs and check them
276         Response res2 = conservationClient.getAuthorityRefs(knownResourceId);
277         AuthorityRefList list = null;
278         try {
279                 assertStatusCode(res2, testName);
280                 list = res2.readEntity(AuthorityRefList.class);
281                 Assert.assertNotNull(list);
282         } finally {
283                 if (res2 != null) {
284                         res2.close();
285             }
286         }
287         
288         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
289         int numAuthRefsFound = items.size();
290         if(logger.isDebugEnabled()){
291             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
292                 " authority references, found " + numAuthRefsFound);
293         }
294
295         // Optionally output additional data about list members for debugging.
296         boolean iterateThroughList = true;
297         if(iterateThroughList && logger.isDebugEnabled()){
298             int i = 0;
299             for(AuthorityRefList.AuthorityRefItem item : items){
300                 logger.debug(testName + ": list-item[" + i + "] Field:" +
301                                 item.getSourceField() + "= " +
302                         item.getAuthDisplayName() +
303                         item.getItemDisplayName());
304                 logger.debug(testName + ": list-item[" + i + "] refName=" +
305                         item.getRefName());
306                 logger.debug(testName + ": list-item[" + i + "] URI=" +
307                         item.getUri());
308                 i++;
309             }
310         }
311
312         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
313             "Did not find all expected authority references! " +
314             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
315
316     }
317
318
319     // ---------------------------------------------------------------
320     // Cleanup of resources created during testing
321     // ---------------------------------------------------------------
322
323     /**
324      * Deletes all resources created by tests, after all tests have been run.
325      *
326      * This cleanup method will always be run, even if one or more tests fail.
327      * For this reason, it attempts to remove all resources created
328      * at any point during testing, even if some of those resources
329      * may be expected to be deleted by certain tests.
330      */
331     @AfterClass(alwaysRun=true)
332     public void cleanUp() {
333         String noTest = System.getProperty("noTestCleanup");
334         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
335             if (logger.isDebugEnabled()) {
336                 logger.debug("Skipping Cleanup phase ...");
337             }
338             return;
339         }
340         if (logger.isDebugEnabled()) {
341             logger.debug("Cleaning up temporary resources created for testing ...");
342         }
343         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
344         // Delete Person resource(s) (before PersonAuthority resources).
345         
346         for (String resourceId : personIdsCreated) {
347             // Note: Any non-success responses are ignored and not reported.
348             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
349         }
350         
351         // Delete PersonAuthority resource(s).
352         // Note: Any non-success response is ignored and not reported.
353         if (personAuthCSID != null) {
354                 personAuthClient.delete(personAuthCSID);
355                 // Delete Conservation resource(s).
356                 ConservationClient conservationClient = new ConservationClient();
357                 for (String resourceId : conservationIdsCreated) {
358                     // Note: Any non-success responses are ignored and not reported.
359                 conservationClient.delete(resourceId).close(); 
360                 }
361         }
362     }
363
364     // ---------------------------------------------------------------
365     // Utility methods used by tests above
366     // ---------------------------------------------------------------
367     public String getServiceName() {
368         return SERVICE_NAME;
369     }
370
371     @Override
372     public String getServicePathComponent() {
373         return SERVICE_PATH_COMPONENT;
374     }
375
376     private PoxPayloadOut createConservationInstance(String conservationNumber,
377             String conservatorRefName,
378             String otherPartyRefName,
379             String examinationStaffRefName,
380             String approvedByRefName,
381             String researcherRefName,
382             String sampleByRefName) {
383         ConservationCommon conservationCommon = new ConservationCommon();
384         conservationCommon.setConservationNumber(conservationNumber);
385
386         ConservatorsList conservatorsList =  new ConservatorsList();
387         conservatorsList.getConservator().add(conservatorRefName);
388
389         OtherPartyGroupList otherPartyGroupList = new OtherPartyGroupList();
390         OtherPartyGroup otherPartyGroup = new OtherPartyGroup();
391         otherPartyGroup.setOtherParty(otherPartyRefName);
392         otherPartyGroupList.getOtherPartyGroup().add(otherPartyGroup);
393
394         ExaminationGroupList examinationGroupList = new ExaminationGroupList();
395         ExaminationGroup examinationGroup = new ExaminationGroup();
396         examinationGroup.setExaminationStaff(examinationStaffRefName);
397         examinationGroupList.getExaminationGroup().add(examinationGroup);
398         
399         DestAnalysisGroupList destAnalysisGroupList = new DestAnalysisGroupList();
400         DestAnalysisGroup destAnalysisGroup = new DestAnalysisGroup();
401         destAnalysisGroup.setSampleBy(sampleByRefName);
402         destAnalysisGroupList.getDestAnalysisGroup().add(destAnalysisGroup);
403         
404         conservationCommon.setConservators(conservatorsList);
405         conservationCommon.setOtherPartyGroupList(otherPartyGroupList);
406         conservationCommon.setExaminationGroupList(examinationGroupList);
407         conservationCommon.setApprovedBy(approvedByRefName);
408         conservationCommon.setResearcher(researcherRefName);
409         conservationCommon.setDestAnalysisGroupList(destAnalysisGroupList);
410         
411         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
412         PayloadOutputPart commonPart =
413             multipart.addPart(new ConservationClient().getCommonPartName(), conservationCommon);
414         
415         if(logger.isDebugEnabled()){
416             logger.debug("to be created, conservation common");
417             logger.debug(objectAsXmlString(conservationCommon, ConservationCommon.class));
418         }
419
420         return multipart;
421     }
422
423     @Override
424     protected Class<AbstractCommonList> getCommonListType() {
425         return AbstractCommonList.class;
426     }
427
428 }