]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
fa3e9a1a51616539ed6fc83e30624be93c88d4fd
[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.api.GregorianCalendarDateTimeUtils;
43 import org.collectionspace.services.common.authorityref.AuthorityRefList;
44 import org.collectionspace.services.jaxb.AbstractCommonList;
45 import org.collectionspace.services.movement.MovementsCommon;
46 import org.collectionspace.services.person.PersonTermGroup;
47
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * MovementAuthRefsTest, carries out Authority References tests against a
56  * deployed and running Movement Service.
57  *
58  * $LastChangedRevision$
59  * $LastChangedDate$
60  */
61 public class MovementAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
62
63     private final String CLASS_NAME = MovementAuthRefsTest.class.getName();
64     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
65     final String SERVICE_NAME = "movements";
66     final String SERVICE_PATH_COMPONENT = "movements";
67
68     // Instance variables specific to this test.
69     final String PERSON_AUTHORITY_NAME = "TestPersonAuthForMovementTest";
70     private List<String> movementIdsCreated = new ArrayList<String>();
71     private List<String> personIdsCreated = new ArrayList<String>();
72     private String personAuthCSID = null;
73     private String movementContactRefName = null;
74
75     // FIXME: Can add 'current location' and 'normal location'
76     // as authRefs to tests below, and increase the
77     // number of expected authRefs to 3.
78     private final int NUM_AUTH_REFS_EXPECTED = 1;
79
80     /* (non-Javadoc)
81      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
82      */
83     @Override
84     protected CollectionSpaceClient getClientInstance() {
85         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
86     }
87     
88         @Override
89         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
90         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
91         }
92
93         /* (non-Javadoc)
94      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
95      */
96     @Override
97         protected AbstractCommonList getCommonList(Response 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")
106     public void createWithAuthRefs(String testName) throws Exception {
107         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
108
109         // Submit the request to the service and store the response.
110         String identifier = createIdentifier();
111
112         // Create all the person refs and entities
113         createPersonRefs();
114
115         // Create a new Movement resource.
116         //
117         // One or more fields in this resource will be PersonAuthority
118         // references, and will refer to Person resources by their refNames.
119         MovementClient movementClient = new MovementClient();
120         PoxPayloadOut multipart = createMovementInstance(
121                 "movementReferenceNumber-" + identifier,
122                 GregorianCalendarDateTimeUtils.timestampUTC(),
123                 movementContactRefName);
124         String newId = null;
125         Response res = movementClient.create(multipart);
126         int statusCode = res.getStatus();
127         try {
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(testRequestType.isValidStatusCode(statusCode),
138                         invalidStatusCodeMessage(testRequestType, statusCode));
139                 Assert.assertEquals(statusCode, testExpectedStatusCode);
140                 newId = extractId(res);
141         } finally {
142                 res.close();
143         }
144
145         // Store the ID returned from the first resource created
146         // for additional tests below.
147         if (knownResourceId == null){
148             knownResourceId = newId;
149             if (logger.isDebugEnabled()) {
150                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
151             }
152         }
153         
154         // Store the IDs from every resource created by tests,
155         // so they can be deleted after tests have been run.
156         movementIdsCreated.add(newId);
157     }
158
159     protected void createPersonRefs(){
160         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
161         // Create a temporary PersonAuthority resource, and its corresponding
162         // refName by which it can be identified.
163         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
164             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
165         Response res = personAuthClient.create(multipart);
166         try {
167                 int statusCode = res.getStatus();
168         
169                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
170                     invalidStatusCodeMessage(testRequestType, statusCode));
171                 Assert.assertEquals(statusCode, STATUS_CREATED);
172                 personAuthCSID = extractId(res);
173         } finally {
174                 res.close();
175         }
176
177         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
178         
179         // Create temporary Person resources, and their corresponding refNames
180         // by which they can be identified.
181         String csid = createPerson("Melvin", "MovementContact", "melvinMovementContact", authRefName);
182         personIdsCreated.add(csid);
183         movementContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
184     }
185     
186     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
187         String result = null;
188         
189         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
190         Map<String, String> personInfo = new HashMap<String,String>();
191         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
192         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
193         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
194         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
195         PersonTermGroup term = new PersonTermGroup();
196         String termName = firstName + " " + surName;
197         term.setTermDisplayName(termName);
198         term.setTermName(termName);
199         personTerms.add(term);
200         PoxPayloadOut multipart =
201                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
202                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
203         Response res = personAuthClient.createItem(personAuthCSID, multipart);
204         try {
205                 int statusCode = res.getStatus();
206                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
207                         invalidStatusCodeMessage(testRequestType, statusCode));
208                 Assert.assertEquals(statusCode, STATUS_CREATED);
209                 result = extractId(res);
210         } finally {
211                 res.close();
212         }
213         
214         return result;
215     }
216
217     // Success outcomes
218     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
219         dependsOnMethods = {"createWithAuthRefs"})
220     public void readAndCheckAuthRefs(String testName) throws Exception {
221         // Perform setup.
222         testSetup(STATUS_OK, ServiceRequestType.READ);
223
224         // Submit the request to the service and store the response.
225         MovementClient movementClient = new MovementClient();
226         Response res = movementClient.read(knownResourceId);
227         MovementsCommon movementCommon = null;
228         try {
229                 assertStatusCode(res, testName);
230                 // Extract and return the common part of the record.
231                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
232                 PayloadInputPart payloadInputPart = input.getPart(movementClient.getCommonPartName());
233                 if (payloadInputPart != null) {
234                         movementCommon = (MovementsCommon) payloadInputPart.getBody();
235                 }
236                 Assert.assertNotNull(movementCommon);
237                 if(logger.isDebugEnabled()){
238                     logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
239                 }
240         } finally {
241                 if (res != null) {
242                 res.close();
243             }
244         }
245         // Check a couple of fields
246         // FIXME
247         Assert.assertEquals(movementCommon.getMovementContact(), movementContactRefName);
248         
249         // Get the auth refs and check them
250         Response res2 = movementClient.getAuthorityRefs(knownResourceId);
251         AuthorityRefList list = null;
252         try {
253             assertStatusCode(res2, testName);
254                 list = res2.readEntity(AuthorityRefList.class);
255         } finally {
256                 if (res2 != null) {
257                         res2.close();
258             }
259         }
260         
261         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
262         int numAuthRefsFound = items.size();
263         if(logger.isDebugEnabled()){
264             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
265                 " authority references, found " + numAuthRefsFound);
266         }
267         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
268             "Did not find all expected authority references! " +
269             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
270
271         // Optionally output additional data about list members for debugging.
272         boolean iterateThroughList = true;
273         if(iterateThroughList && logger.isDebugEnabled()){
274             int i = 0;
275             for(AuthorityRefList.AuthorityRefItem item : items){
276                 logger.debug(testName + ": list-item[" + i + "] Field:" +
277                                 item.getSourceField() + "= " +
278                         item.getAuthDisplayName() +
279                         item.getItemDisplayName());
280                 logger.debug(testName + ": list-item[" + i + "] refName=" +
281                         item.getRefName());
282                 logger.debug(testName + ": list-item[" + i + "] URI=" +
283                         item.getUri());
284                 i++;
285             }
286         }
287     }
288
289
290     // ---------------------------------------------------------------
291     // Cleanup of resources created during testing
292     // ---------------------------------------------------------------
293
294     /**
295      * Deletes all resources created by tests, after all tests have been run.
296      *
297      * This cleanup method will always be run, even if one or more tests fail.
298      * For this reason, it attempts to remove all resources created
299      * at any point during testing, even if some of those resources
300      * may be expected to be deleted by certain tests.
301      */
302     @AfterClass(alwaysRun=true)
303     public void cleanUp() {
304         String noTest = System.getProperty("noTestCleanup");
305         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
306             if (logger.isDebugEnabled()) {
307                 logger.debug("Skipping Cleanup phase ...");
308             }
309             return;
310         }
311         if (logger.isDebugEnabled()) {
312             logger.debug("Cleaning up temporary resources created for testing ...");
313         }
314         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
315         // Delete Person resource(s) (before PersonAuthority resources).
316         for (String resourceId : personIdsCreated) {
317             // Note: Any non-success responses are ignored and not reported.
318             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
319         }
320         // Delete PersonAuthority resource(s).
321         // Note: Any non-success response is ignored and not reported.
322         if (personAuthCSID != null) {
323                 personAuthClient.delete(personAuthCSID).close();
324         }
325         // Delete Movement resource(s).
326         MovementClient movementClient = new MovementClient();
327         for (String resourceId : movementIdsCreated) {
328             // Note: Any non-success responses are ignored and not reported.
329             movementClient.delete(resourceId).close();
330         }
331     }
332
333     // ---------------------------------------------------------------
334     // Utility methods used by tests above
335     // ---------------------------------------------------------------
336
337     @Override
338     protected String getServiceName() {
339         return SERVICE_NAME;
340     }
341
342     @Override
343     public String getServicePathComponent() {
344         return SERVICE_PATH_COMPONENT;
345     }
346
347    private PoxPayloadOut createMovementInstance(String movementReferenceNumber,
348             String locationDate,
349             String movementContact) {
350         MovementsCommon movementCommon = new MovementsCommon();
351         movementCommon.setMovementReferenceNumber(movementReferenceNumber);
352         movementCommon.setLocationDate(locationDate);
353         movementCommon.setMovementContact(movementContact);
354         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
355         PayloadOutputPart commonPart =
356             multipart.addPart(movementCommon, MediaType.APPLICATION_XML_TYPE);
357         commonPart.setLabel(new MovementClient().getCommonPartName());
358
359         if(logger.isDebugEnabled()){
360             logger.debug("to be created, movement common");
361             logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
362         }
363
364         return multipart;
365     }
366 }