]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
6c60884fba84825919a48f715cb0a38716faeb18
[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(Response response) {
106         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
107     }
108
109     // ---------------------------------------------------------------
110     // CRUD tests : CREATE tests
111     // ---------------------------------------------------------------
112     // Success outcomes
113     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
114     public void createWithAuthRefs(String testName) throws Exception {
115         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
116
117         // Submit the request to the service and store the response.
118         String identifier = createIdentifier();
119         
120         // Create all the person refs and entities
121         createPersonRefs();
122         
123         // Submit the request to the service and store the response.
124         IntakeClient intakeClient = new IntakeClient();
125         PoxPayloadOut multipart = createIntakeInstance(
126                 "entryNumber-" + identifier,
127                 CURRENT_DATE_UTC,
128                 currentOwnerRefName,
129                 depositorRefName,
130                 conditionCheckerOrAssessorRefName,
131                 insurerRefName,
132                 valuerRefName );
133
134         String newId = null;
135         Response res = intakeClient.create(multipart);
136         try {
137                 int statusCode = res.getStatus();
138                 // Check the status code of the response: does it match
139                 // the expected response(s)?
140                 //
141                 // Specifically:
142                 // Does it fall within the set of valid status codes?
143                 // Does it exactly match the expected status code?
144                 if(logger.isDebugEnabled()){
145                     logger.debug(testName + ": status = " + statusCode);
146                 }
147                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
148                         invalidStatusCodeMessage(testRequestType, statusCode));
149                 Assert.assertEquals(statusCode, testExpectedStatusCode);
150                 newId = extractId(res);
151         } finally {
152                 res.close();
153         }
154
155         // Store the ID returned from the first resource created
156         // for additional tests below.
157         if (knownResourceId == null){
158             knownResourceId = newId;
159             if (logger.isDebugEnabled()) {
160                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
161             }
162         }
163         
164         // Store the IDs from every resource created by tests,
165         // so they can be deleted after tests have been run.
166         intakeIdsCreated.add(newId);
167     }
168     
169     protected void createPersonRefs() {
170         //
171         // First, create a new person authority
172         //
173         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
174         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
175                         PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
176         Response res = personAuthClient.create(multipart);
177         try {
178                 int statusCode = res.getStatus();
179                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
180                         invalidStatusCodeMessage(testRequestType, statusCode));
181                 Assert.assertEquals(statusCode, STATUS_CREATED);
182                 personAuthCSID = extractId(res);
183         } finally {
184                 res.close();
185         }
186         
187         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
188         String csid = createPerson("Olivier", "Owner", "olivierOwner", authRefName);
189         currentOwnerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
190         personIdsCreated.add(csid);
191         
192         csid = createPerson("Debbie", "Depositor", "debbieDepositor", authRefName);
193         depositorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
194         personIdsCreated.add(csid);
195         
196         csid = createPerson("Andrew", "Assessor", "andrewAssessor", authRefName);
197         conditionCheckerOrAssessorRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
198         personIdsCreated.add(csid);
199         
200         csid = createPerson("Ingrid", "Insurer", "ingridInsurer", authRefName);
201         insurerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
202         personIdsCreated.add(csid);
203         
204         csid = createPerson("Vince", "Valuer", "vinceValuer", authRefName);
205         valuerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
206         personIdsCreated.add(csid);
207     }
208     
209     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
210         String result = null;
211         
212         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
213         Map<String, String> personInfo = new HashMap<String,String>();
214         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
215         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
216         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
217         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
218         PersonTermGroup term = new PersonTermGroup();
219         String termName = firstName + " " + surName;
220         term.setTermDisplayName(termName);
221         term.setTermName(termName);
222         personTerms.add(term);
223         PoxPayloadOut multipart = 
224                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
225                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
226         
227         Response res = personAuthClient.createItem(personAuthCSID, multipart);
228         try {
229                 int statusCode = res.getStatus();
230                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
231                         invalidStatusCodeMessage(testRequestType, statusCode));
232                 Assert.assertEquals(statusCode, STATUS_CREATED);
233                 result = extractId(res);
234         } finally {
235                 res.close();
236         }
237         
238         return result;
239     }
240
241     // Success outcomes
242     @Test(dataProvider="testName",
243         dependsOnMethods = {"createWithAuthRefs"})
244     public void readAndCheckAuthRefs(String testName) throws Exception {
245         // Perform setup.
246         testSetup(STATUS_OK, ServiceRequestType.READ);
247
248         // Submit the request to the service and store the response.
249         IntakeClient intakeClient = new IntakeClient();
250         Response res = intakeClient.read(knownResourceId);
251         try {
252                 assertStatusCode(res, testName);
253                 PoxPayloadIn input = new PoxPayloadIn((String)res.getEntity());
254                 IntakesCommon intake = (IntakesCommon) extractPart(input,
255                                 intakeClient.getCommonPartName(), IntakesCommon.class);
256                 Assert.assertNotNull(intake);
257                 // Check a couple of fields
258                 Assert.assertEquals(intake.getCurrentOwner(), currentOwnerRefName);
259                 Assert.assertEquals(intake.getConditionCheckersOrAssessors().getConditionCheckerOrAssessor().get(0), conditionCheckerOrAssessorRefName);
260                 Assert.assertEquals(intake.getInsurers().getInsurer().get(0), insurerRefName);
261         } finally {
262                 if (res != null) {
263                 res.close();
264             }
265         }
266         
267         // Get the auth refs and check them
268         res = intakeClient.getAuthorityRefs(knownResourceId);
269         AuthorityRefList list = null;
270         try {
271                 assertStatusCode(res, testName);
272                 list = (AuthorityRefList)res.getEntity();
273         } finally {
274                 if (res != null) {
275                         res.close();
276             }
277         }
278         
279         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
280         int numAuthRefsFound = items.size();
281         if(logger.isDebugEnabled()){
282             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
283                 " authority references, found " + numAuthRefsFound);
284         }
285         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
286             "Did not find all expected authority references! " +
287             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
288
289         // Optionally output additional data about list members for debugging.
290         boolean iterateThroughList = true;
291         if(iterateThroughList && logger.isDebugEnabled()){
292             int i = 0;
293             for(AuthorityRefList.AuthorityRefItem item : items){
294                 logger.debug(testName + ": list-item[" + i + "] Field:" +
295                                 item.getSourceField() + "= " +
296                         item.getAuthDisplayName() +
297                         item.getItemDisplayName());
298                 logger.debug(testName + ": list-item[" + i + "] refName=" +
299                         item.getRefName());
300                 logger.debug(testName + ": list-item[" + i + "] URI=" +
301                         item.getUri());
302                 i++;
303             }
304         }
305     }
306
307
308     // ---------------------------------------------------------------
309     // Cleanup of resources created during testing
310     // ---------------------------------------------------------------
311
312     /**
313      * Deletes all resources created by tests, after all tests have been run.
314      *
315      * This cleanup method will always be run, even if one or more tests fail.
316      * For this reason, it attempts to remove all resources created
317      * at any point during testing, even if some of those resources
318      * may be expected to be deleted by certain tests.
319      */
320     @AfterClass(alwaysRun=true)
321     public void cleanUp() {
322         String noTest = System.getProperty("noTestCleanup");
323         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
324             if (logger.isDebugEnabled()) {
325                 logger.debug("Skipping Cleanup phase ...");
326             }
327             return;
328         }
329         if (logger.isDebugEnabled()) {
330             logger.debug("Cleaning up temporary resources created for testing ...");
331         }
332         IntakeClient intakeClient = new IntakeClient();
333         // Note: Any non-success responses are ignored and not reported.
334         for (String resourceId : intakeIdsCreated) {
335             intakeClient.delete(resourceId).close();
336         }
337         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
338         // Delete persons before PersonAuth
339         for (String resourceId : personIdsCreated) {
340             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
341         }
342         personAuthClient.delete(personAuthCSID).close();
343     }
344
345     // ---------------------------------------------------------------
346     // Utility methods used by tests above
347     // ---------------------------------------------------------------
348     @Override
349     public String getServicePathComponent() {
350         return SERVICE_PATH_COMPONENT;
351     }
352
353    private PoxPayloadOut createIntakeInstance(String entryNumber,
354                 String entryDate,
355                                 String currentOwner,
356                                 String depositor,
357                                 String conditionCheckerAssessor,
358                                 String insurer,
359                                 String Valuer ) {
360         IntakesCommon intake = new IntakesCommon();
361         intake.setEntryNumber(entryNumber);
362         intake.setEntryDate(entryDate);
363         intake.setCurrentOwner(currentOwner);
364         intake.setDepositor(depositor);
365         intake.setValuer(Valuer);
366
367         ConditionCheckerOrAssessorList checkerOrAssessorList = new ConditionCheckerOrAssessorList();
368         List<String> checkersOrAssessors = checkerOrAssessorList.getConditionCheckerOrAssessor();
369         checkersOrAssessors.add(conditionCheckerAssessor);
370         intake.setConditionCheckersOrAssessors(checkerOrAssessorList);
371
372         InsurerList insurerList = new InsurerList();
373         List<String> insurers = insurerList.getInsurer();
374         insurers.add(insurer);
375         intake.setInsurers(insurerList);
376
377         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
378         PayloadOutputPart commonPart =
379             multipart.addPart(new IntakeClient().getCommonPartName(), intake);
380
381         if(logger.isDebugEnabled()){
382             logger.debug("to be created, intake common");
383             logger.debug(objectAsXmlString(intake, IntakesCommon.class));
384         }
385
386         return multipart;
387     }
388 }