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