]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
83f154f7e4c7784877f918819e0bb5d7f65381f8
[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.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
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 import org.collectionspace.services.person.PersonTermGroup;
47
48 import org.jboss.resteasy.client.ClientResponse;
49
50 //import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
51 //import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
52 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
53 import org.testng.Assert;
54 import org.testng.annotations.AfterClass;
55 import org.testng.annotations.Test;
56
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * IntakeAuthRefsTest, carries out tests against a
62  * deployed and running Intake Service.
63  *
64  * $LastChangedRevision: 1327 $
65  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
66  */
67 public class IntakeAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
68
69     private final String CLASS_NAME = IntakeAuthRefsTest.class.getName();
70     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
71
72     // Instance variables specific to this test.
73     final String SERVICE_PATH_COMPONENT = IntakeClient.SERVICE_PATH_COMPONENT;//"intakes";
74     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
75     private String knownResourceId = null;
76     private List<String> intakeIdsCreated = new ArrayList<String>();
77     private List<String> personIdsCreated = new ArrayList<String>();
78     private String personAuthCSID = null; 
79     private String currentOwnerRefName = null;
80     private String depositorRefName = null;
81     private String conditionCheckerOrAssessorRefName = null;
82     private String insurerRefName = null;
83     private String valuerRefName = null;
84     private final int NUM_AUTH_REFS_EXPECTED = 5;
85     private final static String CURRENT_DATE_UTC =
86             GregorianCalendarDateTimeUtils.currentDateUTC();
87
88         @Override
89         protected String getServiceName() {
90                 throw new UnsupportedOperationException(); //FIXME: REM - See http://issues.collectionspace.org/browse/CSPACE-3498
91         }
92     
93     /* (non-Javadoc)
94      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
95      */
96     @Override
97     protected CollectionSpaceClient getClientInstance() {
98         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
99     }
100     
101     /* (non-Javadoc)
102      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
103      */
104     @Override
105         protected AbstractCommonList getCommonList(
106                         ClientResponse<AbstractCommonList> response) {
107         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
108     }
109
110     // ---------------------------------------------------------------
111     // CRUD tests : CREATE tests
112     // ---------------------------------------------------------------
113     // Success outcomes
114     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
115     public void createWithAuthRefs(String testName) throws Exception {
116         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
117
118         // Submit the request to the service and store the response.
119         String identifier = createIdentifier();
120         
121         // Create all the person refs and entities
122         createPersonRefs();
123         
124         // Submit the request to the service and store the response.
125         IntakeClient intakeClient = new IntakeClient();
126         PoxPayloadOut multipart = createIntakeInstance(
127                 "entryNumber-" + identifier,
128                 CURRENT_DATE_UTC,
129                 currentOwnerRefName,
130                 depositorRefName,
131                 conditionCheckerOrAssessorRefName,
132                 insurerRefName,
133                 valuerRefName );
134
135         String newId = null;
136         Response res = intakeClient.create(multipart);
137         try {
138                 int statusCode = res.getStatus();
139                 // Check the status code of the response: does it match
140                 // the expected response(s)?
141                 //
142                 // Specifically:
143                 // Does it fall within the set of valid status codes?
144                 // Does it exactly match the expected status code?
145                 if(logger.isDebugEnabled()){
146                     logger.debug(testName + ": status = " + statusCode);
147                 }
148                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
149                         invalidStatusCodeMessage(testRequestType, statusCode));
150                 Assert.assertEquals(statusCode, testExpectedStatusCode);
151                 newId = extractId(res);
152         } finally {
153                 res.close();
154         }
155
156         // Store the ID returned from the first resource created
157         // for additional tests below.
158         if (knownResourceId == null){
159             knownResourceId = newId;
160             if (logger.isDebugEnabled()) {
161                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
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(newId);
168     }
169     
170     protected void createPersonRefs() {
171         //
172         // First, create a new person authority
173         //
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         String csid = createPerson("Olivier", "Owner", "olivierOwner", authRefName);
190         currentOwnerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
191         personIdsCreated.add(csid);
192         
193         csid = createPerson("Debbie", "Depositor", "debbieDepositor", authRefName);
194         depositorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
195         personIdsCreated.add(csid);
196         
197         csid = createPerson("Andrew", "Assessor", "andrewAssessor", authRefName);
198         conditionCheckerOrAssessorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
199         personIdsCreated.add(csid);
200         
201         csid = createPerson("Ingrid", "Insurer", "ingridInsurer", authRefName);
202         insurerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
203         personIdsCreated.add(csid);
204         
205         csid = createPerson("Vince", "Valuer", "vinceValuer", authRefName);
206         valuerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
207         personIdsCreated.add(csid);
208     }
209     
210     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
211         String result = null;
212         
213         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
214         Map<String, String> personInfo = new HashMap<String,String>();
215         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
216         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
217         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
218         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
219         PersonTermGroup term = new PersonTermGroup();
220         String termName = firstName + " " + surName;
221         term.setTermDisplayName(termName);
222         term.setTermName(termName);
223         personTerms.add(term);
224         PoxPayloadOut multipart = 
225                 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",
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         IntakeClient intakeClient = new IntakeClient();
251         Response res = intakeClient.read(knownResourceId);
252         try {
253                 assertStatusCode(res, testName);
254                 PoxPayloadIn input = new PoxPayloadIn((String)res.getEntity());
255                 IntakesCommon intake = (IntakesCommon) extractPart(input,
256                                 intakeClient.getCommonPartName(), IntakesCommon.class);
257                 Assert.assertNotNull(intake);
258                 // Check a couple of fields
259                 Assert.assertEquals(intake.getCurrentOwner(), currentOwnerRefName);
260                 Assert.assertEquals(intake.getConditionCheckersOrAssessors().getConditionCheckerOrAssessor().get(0), conditionCheckerOrAssessorRefName);
261                 Assert.assertEquals(intake.getInsurers().getInsurer().get(0), insurerRefName);
262         } finally {
263                 if (res != null) {
264                 res.close();
265             }
266         }
267         
268         // Get the auth refs and check them
269         res = intakeClient.getAuthorityRefs(knownResourceId);
270         AuthorityRefList list = null;
271         try {
272                 assertStatusCode(res, testName);
273                 list = (AuthorityRefList)res.getEntity();
274         } finally {
275                 if (res != null) {
276                         res.close();
277             }
278         }
279         
280         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
281         int numAuthRefsFound = items.size();
282         if(logger.isDebugEnabled()){
283             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
284                 " authority references, found " + numAuthRefsFound);
285         }
286         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
287             "Did not find all expected authority references! " +
288             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
289
290         // Optionally output additional data about list members for debugging.
291         boolean iterateThroughList = true;
292         if(iterateThroughList && logger.isDebugEnabled()){
293             int i = 0;
294             for(AuthorityRefList.AuthorityRefItem item : items){
295                 logger.debug(testName + ": list-item[" + i + "] Field:" +
296                                 item.getSourceField() + "= " +
297                         item.getAuthDisplayName() +
298                         item.getItemDisplayName());
299                 logger.debug(testName + ": list-item[" + i + "] refName=" +
300                         item.getRefName());
301                 logger.debug(testName + ": list-item[" + i + "] URI=" +
302                         item.getUri());
303                 i++;
304             }
305         }
306     }
307
308
309     // ---------------------------------------------------------------
310     // Cleanup of resources created during testing
311     // ---------------------------------------------------------------
312
313     /**
314      * Deletes all resources created by tests, after all tests have been run.
315      *
316      * This cleanup method will always be run, even if one or more tests fail.
317      * For this reason, it attempts to remove all resources created
318      * at any point during testing, even if some of those resources
319      * may be expected to be deleted by certain tests.
320      */
321     @AfterClass(alwaysRun=true)
322     public void cleanUp() {
323         String noTest = System.getProperty("noTestCleanup");
324         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
325             if (logger.isDebugEnabled()) {
326                 logger.debug("Skipping Cleanup phase ...");
327             }
328             return;
329         }
330         if (logger.isDebugEnabled()) {
331             logger.debug("Cleaning up temporary resources created for testing ...");
332         }
333         IntakeClient intakeClient = new IntakeClient();
334         // Note: Any non-success responses are ignored and not reported.
335         for (String resourceId : intakeIdsCreated) {
336             intakeClient.delete(resourceId).close();
337         }
338         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
339         // Delete persons before PersonAuth
340         for (String resourceId : personIdsCreated) {
341             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
342         }
343         personAuthClient.delete(personAuthCSID).close();
344     }
345
346     // ---------------------------------------------------------------
347     // Utility methods used by tests above
348     // ---------------------------------------------------------------
349     @Override
350     public String getServicePathComponent() {
351         return SERVICE_PATH_COMPONENT;
352     }
353
354    private PoxPayloadOut createIntakeInstance(String entryNumber,
355                 String entryDate,
356                                 String currentOwner,
357                                 String depositor,
358                                 String conditionCheckerAssessor,
359                                 String insurer,
360                                 String Valuer ) {
361         IntakesCommon intake = new IntakesCommon();
362         intake.setEntryNumber(entryNumber);
363         intake.setEntryDate(entryDate);
364         intake.setCurrentOwner(currentOwner);
365         intake.setDepositor(depositor);
366         intake.setValuer(Valuer);
367
368         ConditionCheckerOrAssessorList checkerOrAssessorList = new ConditionCheckerOrAssessorList();
369         List<String> checkersOrAssessors = checkerOrAssessorList.getConditionCheckerOrAssessor();
370         checkersOrAssessors.add(conditionCheckerAssessor);
371         intake.setConditionCheckersOrAssessors(checkerOrAssessorList);
372
373         InsurerList insurerList = new InsurerList();
374         List<String> insurers = insurerList.getInsurer();
375         insurers.add(insurer);
376         intake.setInsurers(insurerList);
377
378         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
379         PayloadOutputPart commonPart =
380             multipart.addPart(new IntakeClient().getCommonPartName(), intake);
381
382         if(logger.isDebugEnabled()){
383             logger.debug("to be created, intake common");
384             logger.debug(objectAsXmlString(intake, IntakesCommon.class));
385         }
386
387         return multipart;
388     }
389 }