]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9892a8c3de92f678826cb7298dd3bee82f7de377
[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 import org.testng.Assert;
52 import org.testng.annotations.AfterClass;
53 import org.testng.annotations.Test;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * ConservationAuthRefsTest, carries out Authority References tests against a
59  * deployed and running Conservation Service.
60  *
61  * $LastChangedRevision$
62  * $LastChangedDate$
63  */
64 public class ConservationAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
65
66     private final String CLASS_NAME = ConservationAuthRefsTest.class.getName();
67     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
68     
69     // Instance variables specific to this test.
70     final String SERVICE_NAME = "conservation";
71     final String SERVICE_PATH_COMPONENT = "conservation";
72     final String PERSON_AUTHORITY_NAME = "TestPersonAuthForConservation";
73     private String knownResourceId = null;
74     private List<String> conservationIdsCreated = new ArrayList<String>();
75     private List<String> personIdsCreated = new ArrayList<String>();
76     private String personAuthCSID = null;
77     private String conservatorRefName = null;
78     private String otherPartyRefName = null;
79     private String examinationStaffRefName = null;
80     private String approvedByRefName = null;
81     private String researcherRefName = null;
82     private String sampleByRefName = null;
83     private final int NUM_AUTH_REFS_EXPECTED = 6;
84
85     /* (non-Javadoc)
86      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
87      */
88     @Override
89     protected CollectionSpaceClient getClientInstance() {
90         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
91     }
92
93         @Override
94         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
95         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
96         }
97         
98     /* (non-Javadoc)
99      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
100      */
101     @Override
102         protected AbstractCommonList getCommonList(Response response) {
103         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
104     }
105
106     // ---------------------------------------------------------------
107     // CRUD tests : CREATE tests
108     // ---------------------------------------------------------------
109     // Success outcomes
110     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
111     public void createWithAuthRefs(String testName) throws Exception {
112         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
113
114         // Submit the request to the service and store the response.
115         String identifier = createIdentifier();
116         
117         // Create all the person refs and entities
118         createPersonRefs();
119
120         // Create a new Conservation resource.
121         //
122         // One or more fields in this resource will be PersonAuthority
123         // references, and will refer to Person resources by their refNames.
124         ConservationClient conservationClient = new ConservationClient();
125         PoxPayloadOut multipart = createConservationInstance(
126                 "conservationNumber-" + identifier,
127                 conservatorRefName,
128                 otherPartyRefName,
129                 examinationStaffRefName,
130                 approvedByRefName,
131                 researcherRefName,
132                 sampleByRefName);
133         Response response = conservationClient.create(multipart);
134         int statusCode = response.getStatus();
135         try {
136             // Check the status code of the response: does it match
137             // the expected response(s)?
138             //
139             // Specifically:
140             // Does it fall within the set of valid status codes?
141             // Does it exactly match the expected status code?
142             if(logger.isDebugEnabled()){
143                 logger.debug(testName + ": status = " + statusCode);
144             }
145             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
146                     invalidStatusCodeMessage(testRequestType, statusCode));
147             Assert.assertEquals(statusCode, testExpectedStatusCode);
148
149             // Store the ID returned from the first resource created
150             // for additional tests below.
151             if (knownResourceId == null){
152                 knownResourceId = extractId(response);
153                 if (logger.isDebugEnabled()) {
154                     logger.debug(testName + ": knownResourceId=" + knownResourceId);
155                 }
156             }
157         
158             // Store the IDs from every resource created by tests,
159             // so they can be deleted after tests have been run.
160             conservationIdsCreated.add(extractId(response));
161         } finally {
162                 response.close();
163         }
164     }
165     
166     protected void createPersonRefs() throws Exception{
167         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
168         // Create a temporary PersonAuthority resource, and its corresponding
169         // refName by which it can be identified.
170         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
171             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
172         Response res = personAuthClient.create(multipart);
173         try {
174                int statusCode = res.getStatus();
175                Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
176                    invalidStatusCodeMessage(testRequestType, statusCode));
177                Assert.assertEquals(statusCode, STATUS_CREATED);
178                personAuthCSID = extractId(res);
179         } finally {
180                res.close();
181         }
182
183         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
184         // Create temporary Person resources, and their corresponding refNames
185         // by which they can be identified.
186         String csid = createPerson("Connie", "Conservator", "connieConservator", authRefName);
187         personIdsCreated.add(csid);
188         conservatorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
189
190         csid = createPerson("Oliver", "Otherparty", "oliverOtherparty", authRefName);
191         personIdsCreated.add(csid);
192         otherPartyRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
193
194         csid = createPerson("Steven", "Staff", "stevenStaff", authRefName);
195         personIdsCreated.add(csid);
196         examinationStaffRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
197         
198         csid = createPerson("Allison", "Approver", "allisonApprover", authRefName);
199         personIdsCreated.add(csid);
200         approvedByRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
201
202         csid = createPerson("Rachel", "Researcher", "rachelResearcher", authRefName);
203         personIdsCreated.add(csid);
204         researcherRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
205
206         csid = createPerson("Sabrina", "Sampler", "sabrinaSampler", authRefName);
207         personIdsCreated.add(csid);
208         sampleByRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
209     }
210     
211     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
212         String result = null;
213        
214         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
215         Map<String, String> personInfo = new HashMap<String,String>();
216         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
217         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
218         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
219         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
220         PersonTermGroup term = new PersonTermGroup();
221         String termName = firstName + " " + surName;
222         term.setTermDisplayName(termName);
223         term.setTermName(termName);
224         personTerms.add(term);
225         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
226                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
227       
228         Response res = personAuthClient.createItem(personAuthCSID, multipart);
229         try {
230             int statusCode = res.getStatus();
231             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
232                 invalidStatusCodeMessage(testRequestType, statusCode));
233             Assert.assertEquals(statusCode, STATUS_CREATED);
234             result = extractId(res);
235         } finally {
236             res.close();
237         }
238
239         return result;
240     }
241
242     // Success outcomes
243     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
244         dependsOnMethods = {"createWithAuthRefs"})
245     public void readAndCheckAuthRefs(String testName) throws Exception {
246         // Perform setup.
247         testSetup(STATUS_OK, ServiceRequestType.READ);
248
249         // Submit the request to the service and store the response.
250         ConservationClient conservationClient = new ConservationClient();
251         Response res = conservationClient.read(knownResourceId);
252         ConservationCommon conservationCommon = null;
253         try {
254                 assertStatusCode(res, testName);
255                 // Extract the common part from the response.
256                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
257                 conservationCommon = (ConservationCommon) extractPart(input,
258                     conservationClient.getCommonPartName(), ConservationCommon.class);
259                 Assert.assertNotNull(conservationCommon);
260                 if(logger.isDebugEnabled()){
261                     logger.debug(objectAsXmlString(conservationCommon, ConservationCommon.class));
262                 }
263         } finally {
264                 if (res != null) {
265                 res.close();
266             }
267         }
268         //
269         // Check a couple of fields
270         //
271         Assert.assertEquals(conservationCommon.getApprovedBy(), approvedByRefName);
272         Assert.assertEquals(conservationCommon.getResearcher(), researcherRefName);
273         
274         // Get the auth refs and check them
275         Response res2 = conservationClient.getAuthorityRefs(knownResourceId);
276         AuthorityRefList list = null;
277         try {
278                 assertStatusCode(res2, testName);
279                 list = res2.readEntity(AuthorityRefList.class);
280                 Assert.assertNotNull(list);
281         } finally {
282                 if (res2 != null) {
283                         res2.close();
284             }
285         }
286         
287         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
288         int numAuthRefsFound = items.size();
289         if(logger.isDebugEnabled()){
290             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
291                 " authority references, found " + numAuthRefsFound);
292         }
293
294         // Optionally output additional data about list members for debugging.
295         boolean iterateThroughList = true;
296         if(iterateThroughList && logger.isDebugEnabled()){
297             int i = 0;
298             for(AuthorityRefList.AuthorityRefItem item : items){
299                 logger.debug(testName + ": list-item[" + i + "] Field:" +
300                                 item.getSourceField() + "= " +
301                         item.getAuthDisplayName() +
302                         item.getItemDisplayName());
303                 logger.debug(testName + ": list-item[" + i + "] refName=" +
304                         item.getRefName());
305                 logger.debug(testName + ": list-item[" + i + "] URI=" +
306                         item.getUri());
307                 i++;
308             }
309         }
310
311         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
312             "Did not find all expected authority references! " +
313             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
314
315     }
316
317
318     // ---------------------------------------------------------------
319     // Cleanup of resources created during testing
320     // ---------------------------------------------------------------
321
322     /**
323      * Deletes all resources created by tests, after all tests have been run.
324      *
325      * This cleanup method will always be run, even if one or more tests fail.
326      * For this reason, it attempts to remove all resources created
327      * at any point during testing, even if some of those resources
328      * may be expected to be deleted by certain tests.
329      * @throws Exception 
330      */
331     @AfterClass(alwaysRun=true)
332     public void cleanUp() throws Exception {
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) throws Exception {
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 }