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