]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
58ea504116701c12699cffc8c802d45f3409e74f
[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.IntakeClient;
35 import org.collectionspace.services.client.PayloadOutputPart;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PoxPayloadOut;
39 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
40 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.intake.ConditionCheckerOrAssessorList;
42 import org.collectionspace.services.intake.IntakesCommon;
43 import org.collectionspace.services.intake.InsurerList;
44 import org.collectionspace.services.jaxb.AbstractCommonList;
45 import org.collectionspace.services.person.PersonTermGroup;
46
47 import org.jboss.resteasy.client.ClientResponse;
48
49 //import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
50 //import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
51 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
52 import org.testng.Assert;
53 import org.testng.annotations.AfterClass;
54 import org.testng.annotations.Test;
55
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * PersonAuthRefDocsTest, carries out tests against a
61  * deployed and running Person Service.
62  *
63  * $LastChangedRevision: 1327 $
64  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
65  */
66 public class PersonAuthRefDocsTest extends BaseServiceTest<AbstractCommonList> {
67
68     private final String CLASS_NAME = PersonAuthRefDocsTest.class.getName();
69     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
70     // Instance variables specific to this test.
71     final String SERVICE_PATH_COMPONENT = "intakes";
72     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
73     private String knownIntakeId = null;
74     private List<String> intakeIdsCreated = new ArrayList<String>();
75     private List<String> personIdsCreated = new ArrayList<String>();
76     private String personAuthCSID = null;
77     private String personShortId = PERSON_AUTHORITY_NAME;
78     private String currentOwnerPersonCSID = null;
79     private String depositorPersonCSID = null;
80     private String insurerPersonCSID = null;
81     private String currentOwnerRefName = null;
82     private String depositorRefName = null;
83     private String conditionCheckerAssessorRefName = null;
84     private String insurerRefName = null;
85     private String valuerRefName = null;
86     private String valuerShortId = null;
87     private final int NUM_AUTH_REF_DOCS_EXPECTED = 1;
88     private final static String CURRENT_DATE_UTC =
89             GregorianCalendarDateTimeUtils.currentDateUTC();
90
91     @Override
92     public String getServiceName() { 
93         throw new UnsupportedOperationException(); //FIXME: REM - http://issues.collectionspace.org/browse/CSPACE-3498   
94     }
95     
96     /* (non-Javadoc)
97      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
98      */
99     @Override
100     protected CollectionSpaceClient getClientInstance() {
101         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
102     }
103
104     /* (non-Javadoc)
105      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
106      */
107     @Override
108     protected AbstractCommonList getCommonList(
109             ClientResponse<AbstractCommonList> response) {
110         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
111     }
112
113     // ---------------------------------------------------------------
114     // CRUD tests : CREATE tests
115     // ---------------------------------------------------------------
116     // Success outcomes
117     @Test(dataProvider = "testName")
118     public void createIntakeWithAuthRefs(String testName) throws Exception {
119         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
120
121         // Submit the request to the service and store the response.
122         String identifier = createIdentifier();
123
124         // Create all the person refs and entities
125         createPersonRefs();
126
127         IntakeClient intakeClient = new IntakeClient();
128         PoxPayloadOut multipart = createIntakeInstance(
129                 "entryNumber-" + identifier,
130                 CURRENT_DATE_UTC,
131                 currentOwnerRefName,
132                 depositorRefName,
133                 conditionCheckerAssessorRefName,
134                 insurerRefName,
135                 valuerRefName);
136
137         ClientResponse<Response> res = intakeClient.create(multipart);
138         try {
139             int statusCode = res.getStatus();
140
141             // Check the status code of the response: does it match
142             // the expected response(s)?
143             //
144             // Specifically:
145             // Does it fall within the set of valid status codes?
146             // Does it exactly match the expected status code?
147             if (logger.isDebugEnabled()) {
148                 logger.debug(testName + ": status = " + statusCode);
149             }
150             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
151                     invalidStatusCodeMessage(testRequestType, statusCode));
152             Assert.assertEquals(statusCode, testExpectedStatusCode);
153         } finally {
154             res.releaseConnection();
155         }
156
157         // Store the ID returned from the first resource created
158         // for additional tests below.
159         if (knownIntakeId == null) {
160             knownIntakeId = extractId(res);
161             if (logger.isDebugEnabled()) {
162                 logger.debug(testName + ": knownIntakeId=" + knownIntakeId);
163             }
164         }
165
166         // Store the IDs from every resource created by tests,
167         // so they can be deleted after tests have been run.
168         intakeIdsCreated.add(extractId(res));
169     }
170
171     /**
172      * Creates the person refs.
173      */
174     protected void createPersonRefs() {
175         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
176         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
177                 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
178         ClientResponse<Response> res = personAuthClient.create(multipart);
179         int statusCode = res.getStatus();
180
181         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
182                 invalidStatusCodeMessage(testRequestType, statusCode));
183         Assert.assertEquals(statusCode, STATUS_CREATED);
184         personAuthCSID = extractId(res);
185
186         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
187
188         String csid = createPerson("Olivier", "Owner", "olivierOwner", authRefName);
189         Assert.assertNotNull(csid);
190         currentOwnerPersonCSID = csid;
191         currentOwnerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
192         Assert.assertNotNull(currentOwnerRefName);
193         personIdsCreated.add(csid);
194
195         csid = createPerson("Debbie", "Depositor", "debbieDepositor", authRefName);
196         Assert.assertNotNull(csid);
197         depositorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
198         depositorPersonCSID = csid;
199         Assert.assertNotNull(depositorRefName);
200         personIdsCreated.add(csid);
201
202         csid = createPerson("Andrew", "Assessor", "andrewAssessor", authRefName);
203         Assert.assertNotNull(csid);
204         conditionCheckerAssessorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
205         Assert.assertNotNull(conditionCheckerAssessorRefName);
206         personIdsCreated.add(csid);
207
208         csid = createPerson("Ingrid", "Insurer", "ingridInsurer", authRefName);
209         Assert.assertNotNull(csid);
210         insurerPersonCSID = csid;
211         insurerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
212         Assert.assertNotNull(insurerRefName);
213         personIdsCreated.add(csid);
214
215         csid = createPerson("Vince", "Valuer", "vinceValuer", authRefName);
216         Assert.assertNotNull(csid);
217         valuerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
218         if (logger.isDebugEnabled()) {
219             logger.debug("valuerShortId=" + valuerShortId);
220         }
221         Assert.assertNotNull(valuerRefName);
222         personIdsCreated.add(csid);
223
224     }
225
226     protected String createPerson(String firstName, String surName, String shortId, String authRefName) {
227         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
228         Map<String, String> personInfo = new HashMap<String, String>();
229         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
230         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
231         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
232         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
233         PersonTermGroup term = new PersonTermGroup();
234         String termName = firstName + " " + surName;
235         term.setTermDisplayName(termName);
236         term.setTermName(termName);
237         personTerms.add(term);
238         PoxPayloadOut multipart =
239                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
240                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
241         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
242         int statusCode = res.getStatus();
243
244         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
245                 invalidStatusCodeMessage(testRequestType, statusCode));
246         Assert.assertEquals(statusCode, STATUS_CREATED);
247         return extractId(res);
248     }
249
250     // Success outcomes
251     @Test(dataProvider = "testName", dependsOnMethods = {"createIntakeWithAuthRefs"})
252     public void readAndCheckAuthRefDocs(String testName) throws Exception {
253         // Perform setup.
254         testSetup(STATUS_OK, ServiceRequestType.READ);
255
256         // Get the auth ref docs and check them
257
258         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
259         ClientResponse<AuthorityRefDocList> res =
260                 personAuthClient.getReferencingObjects(personAuthCSID, currentOwnerPersonCSID);
261         AuthorityRefDocList list = null;
262         try {
263                 assertStatusCode(res, testName);
264                 list = res.getEntity();
265         } finally {
266                 if (res != null) {
267                 res.releaseConnection();
268             }
269         }
270         
271         List<AuthorityRefDocList.AuthorityRefDocItem> items =
272                 list.getAuthorityRefDocItem();
273         Assert.assertTrue(items != null);
274         Assert.assertTrue(items.size() > 0);
275
276         // Optionally output additional data about list members for debugging.
277         boolean iterateThroughList = true;
278         boolean fFoundIntake = false;
279         if (iterateThroughList && logger.isDebugEnabled()) {
280             int i = 0;
281             logger.debug(testName + ": Docs that use: " + currentOwnerRefName);
282             for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
283                 logger.debug(testName + ": list-item[" + i + "] "
284                         + item.getDocType() + "("
285                         + item.getDocId() + ") Name:["
286                         + item.getDocName() + "] Number:["
287                         + item.getDocNumber() + "] in field:["
288                         + item.getSourceField() + "]");
289                 if (!fFoundIntake && knownIntakeId.equalsIgnoreCase(item.getDocId())) {
290                     fFoundIntake = true;
291                 }
292                 i++;
293             }
294             Assert.assertTrue(fFoundIntake, "Did not find Intake with authref!");
295         }
296         //
297         // Get the referencing objects
298         //
299         personAuthClient = new PersonAuthorityClient();
300         res = personAuthClient.getReferencingObjects(personAuthCSID, depositorPersonCSID);
301         try {
302                 assertStatusCode(res, testName);
303                 list = res.getEntity();
304         } finally {
305                 if (res != null) {
306                 res.releaseConnection();
307             }
308         }
309         
310         items = list.getAuthorityRefDocItem();
311         Assert.assertTrue(items != null);
312         Assert.assertTrue(items.size() > 0);
313         Assert.assertTrue(items.get(0) != null);
314         
315         // Optionally output additional data about list members for debugging.
316         iterateThroughList = true;
317         fFoundIntake = false;
318         if (iterateThroughList && logger.isDebugEnabled()) {
319             int i = 0;
320             logger.debug(testName + ": Docs that use: " + depositorRefName);
321             for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
322                 logger.debug(testName + ": list-item[" + i + "] "
323                         + item.getDocType() + "("
324                         + item.getDocId() + ") Name:["
325                         + item.getDocName() + "] Number:["
326                         + item.getDocNumber() + "] in field:["
327                         + item.getSourceField() + "]");
328                 if (!fFoundIntake && knownIntakeId.equalsIgnoreCase(item.getDocId())) {
329                     fFoundIntake = true;
330                 }
331                 i++;
332             }
333             Assert.assertTrue(fFoundIntake, "Did not find Intake with authref!");
334         }
335     }
336
337     /*
338      * Read and check the list of referencing objects, where the authRef field
339      * is a value instance of a repeatable scalar field.
340      */
341     @Test(dataProvider = "testName", dependsOnMethods = {"createIntakeWithAuthRefs"},
342                 groups = {"repeatableScalar"})
343     public void readAndCheckAuthRefDocsRepeatableScalar(String testName) throws Exception {
344         // Perform setup.
345         testSetup(STATUS_OK, ServiceRequestType.READ);
346
347         // Get the auth ref docs and check them
348
349         // Single scalar field
350         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
351         ClientResponse<AuthorityRefDocList> res =
352                 personAuthClient.getReferencingObjects(personAuthCSID, insurerPersonCSID);
353         AuthorityRefDocList list = null;
354         try {
355                 assertStatusCode(res, testName);
356                 list = res.getEntity();
357         } finally {
358                 if (res != null) {
359                 res.releaseConnection();
360             }
361         }
362         
363         List<AuthorityRefDocList.AuthorityRefDocItem> items =
364                 list.getAuthorityRefDocItem();
365         Assert.assertTrue(items != null);
366         Assert.assertTrue(items.size() > 0);
367         Assert.assertTrue(items.get(0) != null);
368
369         // Optionally output additional data about list members for debugging.
370         boolean iterateThroughList = true;
371         boolean fFoundIntake = false;
372         if (iterateThroughList && logger.isDebugEnabled()) {
373             int i = 0;
374             logger.debug(testName + ": Docs that use: " + insurerRefName);
375             for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
376                 logger.debug(testName + ": list-item[" + i + "] "
377                         + item.getDocType() + "("
378                         + item.getDocId() + ") Name:["
379                         + item.getDocName() + "] Number:["
380                         + item.getDocNumber() + "] in field:["
381                         + item.getSourceField() + "]");
382                 if (!fFoundIntake && knownIntakeId.equalsIgnoreCase(item.getDocId())) {
383                     fFoundIntake = true;
384                 }
385                 i++;
386             }
387             Assert.assertTrue(fFoundIntake, "Did not find Intake with authref!");
388         }
389     }
390
391
392     // ---------------------------------------------------------------
393     // Cleanup of resources created during testing
394     // ---------------------------------------------------------------
395     /**
396      * Deletes all resources created by tests, after all tests have been run.
397      *
398      * This cleanup method will always be run, even if one or more tests fail.
399      * For this reason, it attempts to remove all resources created
400      * at any point during testing, even if some of those resources
401      * may be expected to be deleted by certain tests.
402      */
403     @AfterClass(alwaysRun = true)
404     public void cleanUp() {
405         String noTest = System.getProperty("noTestCleanup");
406         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
407             if (logger.isDebugEnabled()) {
408                 logger.debug("Skipping Cleanup phase ...");
409             }
410             return;
411         }
412         if (logger.isDebugEnabled()) {
413             logger.debug("Cleaning up temporary resources created for testing ...");
414         }
415         IntakeClient intakeClient = new IntakeClient();
416         // Note: Any non-success responses are ignored and not reported.
417         for (String resourceId : intakeIdsCreated) {
418             ClientResponse<Response> res = intakeClient.delete(resourceId);
419             res.releaseConnection();
420         }
421         // Delete persons before PersonAuth
422         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
423         for (String resourceId : personIdsCreated) {
424             ClientResponse<Response> res = personAuthClient.deleteItem(personAuthCSID, resourceId);
425             res.releaseConnection();
426         }
427         if (personAuthCSID != null) {
428             personAuthClient.delete(personAuthCSID).releaseConnection();
429         }
430     }
431
432     // ---------------------------------------------------------------
433     // Utility methods used by tests above
434     // ---------------------------------------------------------------
435     @Override
436     public String getServicePathComponent() {
437         return SERVICE_PATH_COMPONENT;
438     }
439
440     private PoxPayloadOut createIntakeInstance(String entryNumber,
441             String entryDate,
442             String currentOwner,
443             String depositor,
444             String conditionCheckerAssessor,
445             String insurer,
446             String Valuer) {
447         IntakesCommon intake = new IntakesCommon();
448         intake.setEntryNumber(entryNumber);
449         intake.setEntryDate(entryDate);
450         intake.setCurrentOwner(currentOwner);
451         intake.setDepositor(depositor);
452         intake.setValuer(Valuer);
453
454         ConditionCheckerOrAssessorList checkerOrAssessorList = new ConditionCheckerOrAssessorList();
455         List<String> checkersOrAssessors = checkerOrAssessorList.getConditionCheckerOrAssessor();
456         checkersOrAssessors.add(conditionCheckerAssessor);
457         intake.setConditionCheckersOrAssessors(checkerOrAssessorList);
458
459         InsurerList insurerList = new InsurerList();
460         List<String> insurers = insurerList.getInsurer();
461         insurers.add(insurer);
462         intake.setInsurers(insurerList);
463
464         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
465         PayloadOutputPart commonPart =
466                 multipart.addPart(new IntakeClient().getCommonPartName(), intake);
467
468         if (logger.isDebugEnabled()) {
469             logger.debug("to be created, intake common");
470             logger.debug(objectAsXmlString(intake, IntakesCommon.class));
471         }
472
473         return multipart;
474     }
475 }