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