]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
16f071a9f38ce61326880962c6e47c87517a7839
[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         assertStatusCode(res, testName);
214
215         // Extract and return the common part of the record.
216         PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
217         PayloadInputPart payloadInputPart = input.getPart(movementClient.getCommonPartName());
218         MovementsCommon movementCommon = null;
219         if (payloadInputPart != null) {
220                 movementCommon = (MovementsCommon) payloadInputPart.getBody();
221         }
222         Assert.assertNotNull(movementCommon);
223         if(logger.isDebugEnabled()){
224             logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
225         }
226         // Check a couple of fields
227         // FIXME
228         Assert.assertEquals(movementCommon.getMovementContact(), movementContactRefName);
229         
230         // Get the auth refs and check them
231         ClientResponse<AuthorityRefList> res2 =
232            movementClient.getAuthorityRefs(knownResourceId);
233         assertStatusCode(res2, testName);
234
235         AuthorityRefList list = res2.getEntity();
236         
237         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
238         int numAuthRefsFound = items.size();
239         if(logger.isDebugEnabled()){
240             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
241                 " authority references, found " + numAuthRefsFound);
242         }
243         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
244             "Did not find all expected authority references! " +
245             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
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
265
266     // ---------------------------------------------------------------
267     // Cleanup of resources created during testing
268     // ---------------------------------------------------------------
269
270     /**
271      * Deletes all resources created by tests, after all tests have been run.
272      *
273      * This cleanup method will always be run, even if one or more tests fail.
274      * For this reason, it attempts to remove all resources created
275      * at any point during testing, even if some of those resources
276      * may be expected to be deleted by certain tests.
277      */
278     @AfterClass(alwaysRun=true)
279     public void cleanUp() {
280         String noTest = System.getProperty("noTestCleanup");
281         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
282             if (logger.isDebugEnabled()) {
283                 logger.debug("Skipping Cleanup phase ...");
284             }
285             return;
286         }
287         if (logger.isDebugEnabled()) {
288             logger.debug("Cleaning up temporary resources created for testing ...");
289         }
290         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
291         // Delete Person resource(s) (before PersonAuthority resources).
292         for (String resourceId : personIdsCreated) {
293             // Note: Any non-success responses are ignored and not reported.
294             personAuthClient.deleteItem(personAuthCSID, resourceId);
295         }
296         // Delete PersonAuthority resource(s).
297         // Note: Any non-success response is ignored and not reported.
298         if (personAuthCSID != null) {
299                 personAuthClient.delete(personAuthCSID);
300         }
301         // Delete Movement resource(s).
302         MovementClient movementClient = new MovementClient();
303         for (String resourceId : movementIdsCreated) {
304             // Note: Any non-success responses are ignored and not reported.
305             movementClient.delete(resourceId);
306         }
307     }
308
309     // ---------------------------------------------------------------
310     // Utility methods used by tests above
311     // ---------------------------------------------------------------
312
313     @Override
314     protected String getServiceName() {
315         return SERVICE_NAME;
316     }
317
318     @Override
319     public String getServicePathComponent() {
320         return SERVICE_PATH_COMPONENT;
321     }
322
323    private PoxPayloadOut createMovementInstance(String movementReferenceNumber,
324             String locationDate,
325             String movementContact) {
326         MovementsCommon movementCommon = new MovementsCommon();
327         movementCommon.setMovementReferenceNumber(movementReferenceNumber);
328         movementCommon.setLocationDate(locationDate);
329         movementCommon.setMovementContact(movementContact);
330         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
331         PayloadOutputPart commonPart =
332             multipart.addPart(movementCommon, MediaType.APPLICATION_XML_TYPE);
333         commonPart.setLabel(new MovementClient().getCommonPartName());
334
335         if(logger.isDebugEnabled()){
336             logger.debug("to be created, movement common");
337             logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
338         }
339
340         return multipart;
341     }
342 }