]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9071f3534e8aab9f3bdaf4b09f5f772c9b795efe
[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.ConditioncheckClient;
35 import org.collectionspace.services.client.PersonAuthorityClient;
36 import org.collectionspace.services.client.PersonAuthorityClientUtils;
37 import org.collectionspace.services.client.PayloadOutputPart;
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.jaxb.AbstractCommonList;
43 import org.collectionspace.services.conditioncheck.ConditionchecksCommon;
44 import org.collectionspace.services.person.PersonTermGroup;
45
46 import org.jboss.resteasy.client.ClientResponse;
47
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * ConditioncheckAuthRefsTest, carries out Authority References tests against a
57  * deployed and running Conditioncheck (aka Condition Checks) Service.
58  */
59 public class ConditioncheckAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
60
61     private final String CLASS_NAME = ConditioncheckAuthRefsTest.class.getName();
62     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
63     
64     // Instance variables specific to this test.
65     final String SERVICE_NAME = "conditionchecks";
66     final String SERVICE_PATH_COMPONENT = "conditionchecks";
67     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
68     private String knownResourceId = null;
69     private List<String> conditioncheckIdsCreated = new ArrayList<String>();
70     private List<String> personIdsCreated = new ArrayList<String>();
71     private String personAuthCSID = null;
72     private String conditionCheckerRefName = null;
73
74     private final int NUM_AUTH_REFS_EXPECTED = 1;
75
76
77     /* (non-Javadoc)
78      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
79      */
80     @Override
81     protected CollectionSpaceClient getClientInstance() {
82         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
83     }
84     
85     /* (non-Javadoc)
86      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
87      */
88     @Override
89     protected AbstractCommonList getCommonList(
90             ClientResponse<AbstractCommonList> response) {
91         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
92     }
93
94     // ---------------------------------------------------------------
95     // CRUD tests : CREATE tests
96     // ---------------------------------------------------------------
97     // Success outcomes
98     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
99     public void createWithAuthRefs(String testName) throws Exception {
100         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
101
102         // Submit the request to the service and store the response.
103         String identifier = createIdentifier();
104         
105         // Create all the person refs and entities
106         createPersonRefs();
107
108         // Create a new Condition Check resource.
109         //
110         // One or more fields in this resource will be PersonAuthority
111         // references, and will refer to Person resources by their refNames.
112         ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
113         PoxPayloadOut multipart = createConditioncheckInstance(
114                 "conditionCheckRefNumber-" + identifier,
115                 conditionCheckerRefName);
116         ClientResponse<Response> response = conditioncheckClient.create(multipart);
117         int statusCode = response.getStatus();
118         try {
119             // Check the status code of the response: does it match
120             // the expected response(s)?
121             //
122             // Specifically:
123             // Does it fall within the set of valid status codes?
124             // Does it exactly match the expected status code?
125             if(logger.isDebugEnabled()){
126                 logger.debug(testName + ": status = " + statusCode);
127             }
128             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
129                     invalidStatusCodeMessage(testRequestType, statusCode));
130             Assert.assertEquals(statusCode, testExpectedStatusCode);
131     
132             // Store the ID returned from the first resource created
133             // for additional tests below.
134             if (knownResourceId == null){
135                 knownResourceId = extractId(response);
136                 if (logger.isDebugEnabled()) {
137                     logger.debug(testName + ": knownResourceId=" + knownResourceId);
138                 }
139             }
140             
141             // Store the IDs from every resource created by tests,
142             // so they can be deleted after tests have been run.
143             conditioncheckIdsCreated.add(extractId(response));
144         } finally {
145             response.releaseConnection();
146         }
147     }
148     
149     protected void createPersonRefs(){
150
151         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
152         // Create a temporary PersonAuthority resource, and its corresponding
153         // refName by which it can be identified.
154         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
155             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
156         ClientResponse<Response> res = personAuthClient.create(multipart);
157         int statusCode = res.getStatus();
158
159         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
160             invalidStatusCodeMessage(testRequestType, statusCode));
161         Assert.assertEquals(statusCode, STATUS_CREATED);
162         personAuthCSID = extractId(res);
163
164         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
165         
166         // Create temporary Person resources, and their corresponding refNames
167         // by which they can be identified.
168         String csid = createPerson("Carrie", "ConditionChecker1", "carrieConditionChecker", authRefName);
169         personIdsCreated.add(csid);
170         conditionCheckerRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
171     }
172     
173     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
174         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
175         Map<String, String> personInfo = new HashMap<String,String>();
176         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
177         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
178         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
179         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
180         PersonTermGroup term = new PersonTermGroup();
181         String termName = firstName + " " + surName;
182         term.setTermDisplayName(termName);
183         term.setTermName(termName);
184         personTerms.add(term);
185         PoxPayloadOut multipart =
186             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
187                     authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
188         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
189         int statusCode = res.getStatus();
190
191         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
192                 invalidStatusCodeMessage(testRequestType, statusCode));
193         Assert.assertEquals(statusCode, STATUS_CREATED);
194         return extractId(res);
195     }
196
197     // Success outcomes
198     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
199         dependsOnMethods = {"createWithAuthRefs"})
200     public void readAndCheckAuthRefs(String testName) throws Exception {
201         // Perform setup.
202         testSetup(STATUS_OK, ServiceRequestType.READ);
203
204         // Submit the request to the service and store the response.
205         ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
206         ClientResponse<String> res = conditioncheckClient.read(knownResourceId);
207         ConditionchecksCommon conditioncheckCommon = null;
208         try {
209             assertStatusCode(res, testName);
210             // Extract the common part from the response.
211             PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
212             conditioncheckCommon = (ConditionchecksCommon) extractPart(input,
213                 conditioncheckClient.getCommonPartName(), ConditionchecksCommon.class);
214             Assert.assertNotNull(conditioncheckCommon);
215             if(logger.isDebugEnabled()){
216                 logger.debug(objectAsXmlString(conditioncheckCommon, ConditionchecksCommon.class));
217             }
218         } finally {
219             if (res != null) {
220                 res.releaseConnection();
221             }
222         }
223         //
224         // Check a couple of fields
225         Assert.assertEquals(conditioncheckCommon.getConditionChecker(), conditionCheckerRefName);
226         
227         // Get the auth refs and check them
228         ClientResponse<AuthorityRefList> res2 = conditioncheckClient.getAuthorityRefs(knownResourceId);
229         AuthorityRefList list = null;
230         try {
231             assertStatusCode(res2, testName);
232             list = res2.getEntity();
233             Assert.assertNotNull(list);
234         } finally {
235             if (res2 != null) {
236                 res2.releaseConnection();
237             }
238         }
239         
240         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
241         int numAuthRefsFound = items.size();
242         if(logger.isDebugEnabled()){
243             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
244                 " authority references, found " + numAuthRefsFound);
245         }
246
247         // Optionally output additional data about list members for debugging.
248         boolean iterateThroughList = true;
249         if(iterateThroughList && logger.isDebugEnabled()){
250             int i = 0;
251             for(AuthorityRefList.AuthorityRefItem item : items){
252                 logger.debug(testName + ": list-item[" + i + "] Field:" +
253                         item.getSourceField() + "= " +
254                         item.getAuthDisplayName() +
255                         item.getItemDisplayName());
256                 logger.debug(testName + ": list-item[" + i + "] refName=" +
257                         item.getRefName());
258                 logger.debug(testName + ": list-item[" + i + "] URI=" +
259                         item.getUri());
260                 i++;
261             }
262         }
263
264         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
265             "Did not find all expected authority references! " +
266             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
267
268     }
269
270
271     // ---------------------------------------------------------------
272     // Cleanup of resources created during testing
273     // ---------------------------------------------------------------
274
275     /**
276      * Deletes all resources created by tests, after all tests have been run.
277      *
278      * This cleanup method will always be run, even if one or more tests fail.
279      * For this reason, it attempts to remove all resources created
280      * at any point during testing, even if some of those resources
281      * may be expected to be deleted by certain tests.
282      */
283     @AfterClass(alwaysRun=true)
284     public void cleanUp() {
285         String noTest = System.getProperty("noTestCleanup");
286         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
287             if (logger.isDebugEnabled()) {
288                 logger.debug("Skipping Cleanup phase ...");
289             }
290             return;
291         }
292         if (logger.isDebugEnabled()) {
293             logger.debug("Cleaning up temporary resources created for testing ...");
294         }
295         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
296         // Delete Person resource(s) (before PersonAuthority resources).
297         
298         for (String resourceId : personIdsCreated) {
299             // Note: Any non-success responses are ignored and not reported.
300             ClientResponse<Response> response = 
301                 personAuthClient.deleteItem(personAuthCSID, resourceId); // alternative to personAuthClient.deleteItem().releaseConnection();
302             response.releaseConnection();
303         }
304         
305         // Delete PersonAuthority resource(s).
306         // Note: Any non-success response is ignored and not reported.
307         if (personAuthCSID != null) {
308             personAuthClient.delete(personAuthCSID);
309             // Delete Condition Checks resource(s).
310             ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
311             ClientResponse<Response> response = null;
312             for (String resourceId : conditioncheckIdsCreated) {
313                 // Note: Any non-success responses are ignored and not reported.
314                 response = conditioncheckClient.delete(resourceId); // alternative to conditioncheckClient.delete(resourceId).releaseConnection();
315                 response.releaseConnection();
316             }
317         }
318     }
319
320     // ---------------------------------------------------------------
321     // Utility methods used by tests above
322     // ---------------------------------------------------------------
323     public String getServiceName() {
324         return SERVICE_NAME;
325     }
326
327     @Override
328     public String getServicePathComponent() {
329         return SERVICE_PATH_COMPONENT;
330     }
331
332     private PoxPayloadOut createConditioncheckInstance(String conditionCheckRefNumber,
333             String conditionChecker) {
334         ConditionchecksCommon conditioncheckCommon = new ConditionchecksCommon();
335
336         conditioncheckCommon.setConditionCheckRefNumber(conditionCheckRefNumber);
337         conditioncheckCommon.setConditionChecker(conditionChecker);
338
339         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
340         PayloadOutputPart commonPart =
341                 multipart.addPart(new ConditioncheckClient().getCommonPartName(), conditioncheckCommon);
342
343         if(logger.isDebugEnabled()){
344             logger.debug("to be created, conditioncheck common");
345             logger.debug(objectAsXmlString(conditioncheckCommon, ConditionchecksCommon.class));
346         }
347
348         return multipart;
349     }
350
351     @Override
352     protected Class<AbstractCommonList> getCommonListType() {
353         return AbstractCommonList.class;
354     }
355 }