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