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