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