]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
a1b38a63be5e94de32f9ea394cd767519531c3f5
[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<AbstractCommonList> {
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 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 getCommonList(
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")
104     public void createWithAuthRefs(String testName) throws Exception {
105         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
106
107         // Submit the request to the service and store the response.
108         String identifier = createIdentifier();
109
110         // Create all the person refs and entities
111         createPersonRefs();
112
113         // Create a new Movement resource.
114         //
115         // One or more fields in this resource will be PersonAuthority
116         // references, and will refer to Person resources by their refNames.
117         MovementClient movementClient = new MovementClient();
118         PoxPayloadOut multipart = createMovementInstance(
119                 "movementReferenceNumber-" + identifier,
120                 GregorianCalendarDateTimeUtils.timestampUTC(),
121                 movementContactRefName);
122         ClientResponse<Response> res = movementClient.create(multipart);
123         int statusCode = res.getStatus();
124
125         // Check the status code of the response: does it match
126         // the expected response(s)?
127         //
128         // Specifically:
129         // Does it fall within the set of valid status codes?
130         // Does it exactly match the expected status code?
131         if(logger.isDebugEnabled()){
132             logger.debug(testName + ": status = " + statusCode);
133         }
134         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
135                 invalidStatusCodeMessage(testRequestType, statusCode));
136         Assert.assertEquals(statusCode, testExpectedStatusCode);
137
138         // Store the ID returned from the first resource created
139         // for additional tests below.
140         if (knownResourceId == null){
141             knownResourceId = extractId(res);
142             if (logger.isDebugEnabled()) {
143                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
144             }
145         }
146         
147         // Store the IDs from every resource created by tests,
148         // so they can be deleted after tests have been run.
149         movementIdsCreated.add(extractId(res));
150     }
151
152     protected void createPersonRefs(){
153
154         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
155         // Create a temporary PersonAuthority resource, and its corresponding
156         // refName by which it can be identified.
157         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
158             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
159         ClientResponse<Response> res = personAuthClient.create(multipart);
160         int statusCode = res.getStatus();
161
162         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
163             invalidStatusCodeMessage(testRequestType, statusCode));
164         Assert.assertEquals(statusCode, STATUS_CREATED);
165         personAuthCSID = extractId(res);
166
167         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
168         
169         // Create temporary Person resources, and their corresponding refNames
170         // by which they can be identified.
171         String csid = createPerson("Melvin", "MovementContact", "melvinMovementContact", authRefName);
172         personIdsCreated.add(csid);
173         movementContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
174     }
175     
176     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
177         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
178         Map<String, String> personInfo = new HashMap<String,String>();
179         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
180         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
181         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
182         PoxPayloadOut multipart =
183                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
184                                 authRefName, personInfo, null, personAuthClient.getItemCommonPartName());
185         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
186         int statusCode = res.getStatus();
187
188         Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
189                 invalidStatusCodeMessage(testRequestType, statusCode));
190         Assert.assertEquals(statusCode, STATUS_CREATED);
191         return extractId(res);
192     }
193
194     // Success outcomes
195     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
196         dependsOnMethods = {"createWithAuthRefs"})
197     public void readAndCheckAuthRefs(String testName) throws Exception {
198         // Perform setup.
199         testSetup(STATUS_OK, ServiceRequestType.READ);
200
201         // Submit the request to the service and store the response.
202         MovementClient movementClient = new MovementClient();
203         ClientResponse<String> res = movementClient.read(knownResourceId);
204         MovementsCommon movementCommon = null;
205         try {
206                 assertStatusCode(res, testName);
207                 // Extract and return the common part of the record.
208                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
209                 PayloadInputPart payloadInputPart = input.getPart(movementClient.getCommonPartName());
210                 if (payloadInputPart != null) {
211                         movementCommon = (MovementsCommon) payloadInputPart.getBody();
212                 }
213                 Assert.assertNotNull(movementCommon);
214                 if(logger.isDebugEnabled()){
215                     logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
216                 }
217         } finally {
218                 if (res != null) {
219                 res.releaseConnection();
220             }
221         }
222         // Check a couple of fields
223         // FIXME
224         Assert.assertEquals(movementCommon.getMovementContact(), movementContactRefName);
225         
226         // Get the auth refs and check them
227         ClientResponse<AuthorityRefList> res2 = movementClient.getAuthorityRefs(knownResourceId);
228         AuthorityRefList list = null;
229         try {
230             assertStatusCode(res2, testName);
231                 list = res2.getEntity();
232         } finally {
233                 if (res2 != null) {
234                         res2.releaseConnection();
235             }
236         }
237         
238         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
239         int numAuthRefsFound = items.size();
240         if(logger.isDebugEnabled()){
241             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
242                 " authority references, found " + numAuthRefsFound);
243         }
244         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
245             "Did not find all expected authority references! " +
246             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
247
248         // Optionally output additional data about list members for debugging.
249         boolean iterateThroughList = true;
250         if(iterateThroughList && logger.isDebugEnabled()){
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         }
264     }
265
266
267     // ---------------------------------------------------------------
268     // Cleanup of resources created during testing
269     // ---------------------------------------------------------------
270
271     /**
272      * Deletes all resources created by tests, after all tests have been run.
273      *
274      * This cleanup method will always be run, even if one or more tests fail.
275      * For this reason, it attempts to remove all resources created
276      * at any point during testing, even if some of those resources
277      * may be expected to be deleted by certain tests.
278      */
279     @AfterClass(alwaysRun=true)
280     public void cleanUp() {
281         String noTest = System.getProperty("noTestCleanup");
282         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
283             if (logger.isDebugEnabled()) {
284                 logger.debug("Skipping Cleanup phase ...");
285             }
286             return;
287         }
288         if (logger.isDebugEnabled()) {
289             logger.debug("Cleaning up temporary resources created for testing ...");
290         }
291         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
292         // Delete Person resource(s) (before PersonAuthority resources).
293         for (String resourceId : personIdsCreated) {
294             // Note: Any non-success responses are ignored and not reported.
295             personAuthClient.deleteItem(personAuthCSID, resourceId);
296         }
297         // Delete PersonAuthority resource(s).
298         // Note: Any non-success response is ignored and not reported.
299         if (personAuthCSID != null) {
300                 personAuthClient.delete(personAuthCSID);
301         }
302         // Delete Movement resource(s).
303         MovementClient movementClient = new MovementClient();
304         for (String resourceId : movementIdsCreated) {
305             // Note: Any non-success responses are ignored and not reported.
306             movementClient.delete(resourceId);
307         }
308     }
309
310     // ---------------------------------------------------------------
311     // Utility methods used by tests above
312     // ---------------------------------------------------------------
313
314     @Override
315     protected String getServiceName() {
316         return SERVICE_NAME;
317     }
318
319     @Override
320     public String getServicePathComponent() {
321         return SERVICE_PATH_COMPONENT;
322     }
323
324    private PoxPayloadOut createMovementInstance(String movementReferenceNumber,
325             String locationDate,
326             String movementContact) {
327         MovementsCommon movementCommon = new MovementsCommon();
328         movementCommon.setMovementReferenceNumber(movementReferenceNumber);
329         movementCommon.setLocationDate(locationDate);
330         movementCommon.setMovementContact(movementContact);
331         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
332         PayloadOutputPart commonPart =
333             multipart.addPart(movementCommon, MediaType.APPLICATION_XML_TYPE);
334         commonPart.setLabel(new MovementClient().getCommonPartName());
335
336         if(logger.isDebugEnabled()){
337             logger.debug("to be created, movement common");
338             logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
339         }
340
341         return multipart;
342     }
343 }