]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7fb6ad7f9b0a7559d03d6080651bcb973c79ae42
[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         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
247         int numAuthRefsFound = items.size();
248         if(logger.isDebugEnabled()){
249             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
250                 " authority references, found " + numAuthRefsFound);
251         }
252         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
253             "Did not find all expected authority references! " +
254             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
255
256         // Optionally output additional data about list members for debugging.
257         boolean iterateThroughList = true;
258         if(iterateThroughList && logger.isDebugEnabled()){
259             int i = 0;
260             for(AuthorityRefList.AuthorityRefItem item : items){
261                 logger.debug(testName + ": list-item[" + i + "] Field:" +
262                                 item.getSourceField() + "= " +
263                         item.getAuthDisplayName() +
264                         item.getItemDisplayName());
265                 logger.debug(testName + ": list-item[" + i + "] refName=" +
266                         item.getRefName());
267                 logger.debug(testName + ": list-item[" + i + "] URI=" +
268                         item.getUri());
269                 i++;
270             }
271         }
272     }
273
274
275     // ---------------------------------------------------------------
276     // Cleanup of resources created during testing
277     // ---------------------------------------------------------------
278
279     /**
280      * Deletes all resources created by tests, after all tests have been run.
281      *
282      * This cleanup method will always be run, even if one or more tests fail.
283      * For this reason, it attempts to remove all resources created
284      * at any point during testing, even if some of those resources
285      * may be expected to be deleted by certain tests.
286      */
287     @AfterClass(alwaysRun=true)
288     public void cleanUp() {
289         String noTest = System.getProperty("noTestCleanup");
290         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
291             if (logger.isDebugEnabled()) {
292                 logger.debug("Skipping Cleanup phase ...");
293             }
294             return;
295         }
296         if (logger.isDebugEnabled()) {
297             logger.debug("Cleaning up temporary resources created for testing ...");
298         }
299         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
300         // Delete Person resource(s) (before PersonAuthority resources).
301         for (String resourceId : personIdsCreated) {
302             // Note: Any non-success responses are ignored and not reported.
303             personAuthClient.deleteItem(personAuthCSID, resourceId);
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         }
310         // Delete Movement resource(s).
311         MovementClient movementClient = new MovementClient();
312         for (String resourceId : movementIdsCreated) {
313             // Note: Any non-success responses are ignored and not reported.
314             movementClient.delete(resourceId);
315         }
316     }
317
318     // ---------------------------------------------------------------
319     // Utility methods used by tests above
320     // ---------------------------------------------------------------
321     @Override
322     public String getServicePathComponent() {
323         return SERVICE_PATH_COMPONENT;
324     }
325
326    private MultipartOutput createMovementInstance(String movementReferenceNumber,
327             String locationDate,
328             String movementContact) {
329         MovementsCommon movement = new MovementsCommon();
330         movement.setMovementReferenceNumber(movementReferenceNumber);
331         movement.setLocationDate(locationDate);
332         movement.setMovementContact(movementContact);
333         MultipartOutput multipart = new MultipartOutput();
334         OutputPart commonPart =
335             multipart.addPart(movement, MediaType.APPLICATION_XML_TYPE);
336         commonPart.getHeaders().add("label", new MovementClient().getCommonPartName());
337
338         if(logger.isDebugEnabled()){
339             logger.debug("to be created, movement common");
340             logger.debug(objectAsXmlString(movement, MovementsCommon.class));
341         }
342
343         return multipart;
344     }
345 }