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