]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
5eb255909d2dce87fa85921f1a6fc0ce70b20a8a
[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, GregorianCalendarDateTimeUtils.timestampUTC(),
122                 movementContactRefName);
123         String newId = null;
124         Response res = movementClient.create(multipart);
125         int statusCode = res.getStatus();
126         try {
127                 // Check the status code of the response: does it match
128                 // the expected response(s)?
129                 //
130                 // Specifically:
131                 // Does it fall within the set of valid status codes?
132                 // Does it exactly match the expected status code?
133                 if(logger.isDebugEnabled()){
134                     logger.debug(testName + ": status = " + statusCode);
135                 }
136                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
137                         invalidStatusCodeMessage(testRequestType, statusCode));
138                 Assert.assertEquals(statusCode, testExpectedStatusCode);
139                 newId = extractId(res);
140         } finally {
141                 res.close();
142         }
143
144         // Store the ID returned from the first resource created
145         // for additional tests below.
146         if (knownResourceId == null){
147             knownResourceId = newId;
148             if (logger.isDebugEnabled()) {
149                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
150             }
151         }
152         
153         // Store the IDs from every resource created by tests,
154         // so they can be deleted after tests have been run.
155         movementIdsCreated.add(newId);
156     }
157
158     protected void createPersonRefs(){
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         Response res = personAuthClient.create(multipart);
165         try {
166                 int statusCode = res.getStatus();
167         
168                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
169                     invalidStatusCodeMessage(testRequestType, statusCode));
170                 Assert.assertEquals(statusCode, STATUS_CREATED);
171                 personAuthCSID = extractId(res);
172         } finally {
173                 res.close();
174         }
175
176         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
177         
178         // Create temporary Person resources, and their corresponding refNames
179         // by which they can be identified.
180         String csid = createPerson("Melvin", "MovementContact", "melvinMovementContact", authRefName);
181         personIdsCreated.add(csid);
182         movementContactRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
183     }
184     
185     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
186         String result = null;
187         
188         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
189         Map<String, String> personInfo = new HashMap<String,String>();
190         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
191         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
192         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId + Math.abs(random.nextInt()));
193         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
194         PersonTermGroup term = new PersonTermGroup();
195         String termName = firstName + " " + surName;
196         term.setTermDisplayName(termName);
197         term.setTermName(termName);
198         personTerms.add(term);
199         PoxPayloadOut multipart =
200                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
201                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
202         Response res = personAuthClient.createItem(personAuthCSID, multipart);
203         try {
204                 int statusCode = res.getStatus();
205                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
206                         invalidStatusCodeMessage(testRequestType, statusCode));
207                 Assert.assertEquals(statusCode, STATUS_CREATED);
208                 result = extractId(res);
209         } finally {
210                 res.close();
211         }
212         
213         return result;
214     }
215
216     // Success outcomes
217     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
218         dependsOnMethods = {"createWithAuthRefs"})
219     public void readAndCheckAuthRefs(String testName) throws Exception {
220         // Perform setup.
221         testSetup(STATUS_OK, ServiceRequestType.READ);
222
223         // Submit the request to the service and store the response.
224         MovementClient movementClient = new MovementClient();
225         Response res = movementClient.read(knownResourceId);
226         MovementsCommon movementCommon = null;
227         try {
228                 assertStatusCode(res, testName);
229                 // Extract and return the common part of the record.
230                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
231                 PayloadInputPart payloadInputPart = input.getPart(movementClient.getCommonPartName());
232                 if (payloadInputPart != null) {
233                         movementCommon = (MovementsCommon) payloadInputPart.getBody();
234                 }
235                 Assert.assertNotNull(movementCommon);
236                 if(logger.isDebugEnabled()){
237                     logger.debug(objectAsXmlString(movementCommon, MovementsCommon.class));
238                 }
239         } finally {
240                 if (res != null) {
241                 res.close();
242             }
243         }
244         // Check a couple of fields
245         // FIXME
246         Assert.assertEquals(movementCommon.getMovementContact(), movementContactRefName);
247         
248         // Get the auth refs and check them
249         Response res2 = movementClient.getAuthorityRefs(knownResourceId);
250         AuthorityRefList list = null;
251         try {
252             assertStatusCode(res2, testName);
253                 list = res2.readEntity(AuthorityRefList.class);
254         } finally {
255                 if (res2 != null) {
256                         res2.close();
257             }
258         }
259         
260         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
261         int numAuthRefsFound = items.size();
262         if(logger.isDebugEnabled()){
263             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
264                 " authority references, found " + numAuthRefsFound);
265         }
266         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
267             "Did not find all expected authority references! " +
268             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
269
270         // Optionally output additional data about list members for debugging.
271         boolean iterateThroughList = true;
272         if(iterateThroughList && logger.isDebugEnabled()){
273             int i = 0;
274             for(AuthorityRefList.AuthorityRefItem item : items){
275                 logger.debug(testName + ": list-item[" + i + "] Field:" +
276                                 item.getSourceField() + "= " +
277                         item.getAuthDisplayName() +
278                         item.getItemDisplayName());
279                 logger.debug(testName + ": list-item[" + i + "] refName=" +
280                         item.getRefName());
281                 logger.debug(testName + ": list-item[" + i + "] URI=" +
282                         item.getUri());
283                 i++;
284             }
285         }
286     }
287
288
289     // ---------------------------------------------------------------
290     // Cleanup of resources created during testing
291     // ---------------------------------------------------------------
292
293     /**
294      * Deletes all resources created by tests, after all tests have been run.
295      *
296      * This cleanup method will always be run, even if one or more tests fail.
297      * For this reason, it attempts to remove all resources created
298      * at any point during testing, even if some of those resources
299      * may be expected to be deleted by certain tests.
300      */
301     @AfterClass(alwaysRun=true)
302     public void cleanUp() {
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) {
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 }