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