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