]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
274c427fd0bc2a998da4cd4c408dc38b103ba4d0
[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.math.BigInteger;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
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.PropagationClient;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.client.PayloadOutputPart;
39 import org.collectionspace.services.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
43 import org.collectionspace.services.jaxb.AbstractCommonList;
44 import org.collectionspace.services.propagation.PropActivityGroup;
45 import org.collectionspace.services.propagation.PropActivityGroupList;
46 import org.collectionspace.services.propagation.PropagationsCommon;
47 import org.collectionspace.services.person.PersonTermGroup;
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  * PropagationAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Propagation (aka Loans In) Service.
59  *
60  * $LastChangedRevision$
61  * $LastChangedDate$
62  */
63 public class PropagationAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
64
65     private final String CLASS_NAME = PropagationAuthRefsTest.class.getName();
66     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67     
68     // Instance variables specific to this test.
69     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
70     private String knownResourceId = null;
71     private List<String> propagationIdsCreated = new ArrayList<String>();
72     private List<String> personIdsCreated = new ArrayList<String>();
73     private String personAuthCSID = null;
74         private String propagatedByRefName = null; // an authRef field
75     private final static String CURRENT_DATE_UTC = GregorianCalendarDateTimeUtils.currentDateUTC();
76
77     /* (non-Javadoc)
78      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
79      */
80     @Override
81     protected CollectionSpaceClient getClientInstance() {
82         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
83     }
84     
85     // ---------------------------------------------------------------
86     // CRUD tests : CREATE tests
87     // ---------------------------------------------------------------
88     // Success outcomes
89     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
90     public void createWithAuthRefs(String testName) throws Exception {
91         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
92
93         // Submit the request to the service and store the response.
94         String identifier = createIdentifier();
95         
96         // Create all the person refs and entities
97         createPersonRefs();
98
99         // Create a new Loans In resource.
100         //
101         // One or more fields in this resource will be PersonAuthority
102         // references, and will refer to Person resources by their refNames.
103         PropagationClient propagationClient = new PropagationClient();
104         PoxPayloadOut propagationInstance = createPropagationInstance(
105                 "propagationNumber-" + identifier,
106                 this.propagatedByRefName,
107                 CURRENT_DATE_UTC);
108         Response response = propagationClient.create(propagationInstance);
109         try {
110                 int statusCode = response.getStatus();
111                 if (logger.isDebugEnabled()) {
112                     logger.debug(testName + ": status = " + statusCode);
113                 }
114                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), invalidStatusCodeMessage(testRequestType, statusCode));
115                 Assert.assertEquals(statusCode, testExpectedStatusCode);
116         
117                 // Store the ID returned from the first resource created
118                 // for additional tests below.
119                 if (knownResourceId == null) {
120                     knownResourceId = extractId(response);
121                 }
122                 
123                 // Store the IDs from every resource created by tests,
124                 // so they can be deleted after tests have been run.
125                 propagationIdsCreated.add(extractId(response));
126         } finally {
127                 response.close();
128         }
129     }
130     
131     /**
132      * Create one or more Person records that will be used to create refNames (referenced terms) in our
133      * test propagation records.
134      * 
135      * @throws Exception
136      */
137     protected void createPersonRefs() throws Exception {
138         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
139         // Create a temporary PersonAuthority resource, and its corresponding
140         // refName by which it can be identified.
141         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
142             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
143         Response res = personAuthClient.create(multipart);
144         try {
145                 int statusCode = res.getStatus();
146                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
147                     invalidStatusCodeMessage(testRequestType, statusCode));
148                 Assert.assertEquals(statusCode, STATUS_CREATED);
149                 personAuthCSID = extractId(res);        
150         } finally {
151                 res.close();
152         }
153         
154         // Create temporary Person resources, and their corresponding refNames
155         // by which they can be identified.
156         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, personAuthClient);
157         String csid = createPerson("Propye", "ThePropagator", "proppy", authRefName);
158         personIdsCreated.add(csid);
159         
160         // Safe the refName for later use -see createWithAuthRefs() method
161         this.propagatedByRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, personAuthClient);
162     }
163     
164     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
165         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
166         Map<String, String> personInfo = new HashMap<String,String>();
167         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
168         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
169         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
170         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
171         PersonTermGroup term = new PersonTermGroup();
172         String termName = firstName + " " + surName;
173         term.setTermDisplayName(termName);
174         term.setTermName(termName);
175         personTerms.add(term);
176         PoxPayloadOut multipart =
177                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
178                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
179         
180         Response res = personAuthClient.createItem(personAuthCSID, multipart);
181         try {
182                 int statusCode = res.getStatus();
183         
184                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
185                         invalidStatusCodeMessage(testRequestType, statusCode));
186                 Assert.assertEquals(statusCode, STATUS_CREATED);
187                 return extractId(res);
188         } finally {
189                 res.close();
190         }
191     }
192
193     // Success outcomes
194     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
195         dependsOnMethods = {"createWithAuthRefs"})
196     public void readAndCheckAuthRefs(String testName) throws Exception {
197         // Perform setup.
198         testSetup(STATUS_OK, ServiceRequestType.READ);
199
200         PropagationClient propagationClient = new PropagationClient();
201         Response res = propagationClient.read(knownResourceId);
202         try {
203                 assertStatusCode(res, testName);
204                 // Extract the common part from the response.
205                 PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(String.class));
206                 PropagationsCommon propagationCommon = (PropagationsCommon) extractPart(input,
207                     propagationClient.getCommonPartName(), PropagationsCommon.class);
208                 Assert.assertNotNull(propagationCommon);
209                 if (logger.isDebugEnabled()){
210                     logger.debug(objectAsXmlString(propagationCommon, PropagationsCommon.class));
211                 }
212         } finally {
213                 if (res != null) {
214                 res.close();
215             }
216         }
217         
218         // Get the authority references
219         res = propagationClient.getAuthorityRefs(knownResourceId); // AuthorityRefList
220         AuthorityRefList list = null;
221         try {
222                 assertStatusCode(res, testName);
223                 list = (AuthorityRefList) res.getEntity();
224                 Assert.assertNotNull(list);
225         } finally {
226                 if (res != null) {
227                         res.close();
228             }
229         }
230         
231         int expectedAuthRefs = personIdsCreated.size();
232         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
233         int numAuthRefsFound = items.size();
234         if(logger.isDebugEnabled()){
235             logger.debug("Expected " + expectedAuthRefs + " authority references, found " + numAuthRefsFound);
236         }
237
238         // Optionally output additional data about list members for debugging.
239         boolean iterateThroughList = true;
240         if(iterateThroughList && logger.isDebugEnabled()){
241             int i = 0;
242             for(AuthorityRefList.AuthorityRefItem item : items){
243                 logger.debug(testName + ": list-item[" + i + "] Field:" +
244                                 item.getSourceField() + "= " +
245                         item.getAuthDisplayName() +
246                         item.getItemDisplayName());
247                 logger.debug(testName + ": list-item[" + i + "] refName=" +
248                         item.getRefName());
249                 logger.debug(testName + ": list-item[" + i + "] URI=" +
250                         item.getUri());
251                 i++;
252             }
253         }
254
255         Assert.assertEquals(numAuthRefsFound, expectedAuthRefs,
256             "Did not find all expected authority references! " + "Expected " + expectedAuthRefs + ", found " + numAuthRefsFound);
257     }
258
259
260     // ---------------------------------------------------------------
261     // Cleanup of resources created during testing
262     // ---------------------------------------------------------------
263
264     /**
265      * Deletes all resources created by tests, after all tests have been run.
266      *
267      * This cleanup method will always be run, even if one or more tests fail.
268      * For this reason, it attempts to remove all resources created
269      * at any point during testing, even if some of those resources
270      * may be expected to be deleted by certain tests.
271      * @throws Exception 
272      */
273     @AfterClass(alwaysRun=true)
274     public void cleanUp() throws Exception {
275         String noTest = System.getProperty("noTestCleanup");
276         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
277             if (logger.isDebugEnabled()) {
278                 logger.debug("Skipping Cleanup phase ...");
279             }
280             return;
281         }
282         if (logger.isDebugEnabled()) {
283             logger.debug("Cleaning up temporary resources created for testing ...");
284         }
285
286         //
287         // Delete all the propagation records we created
288         PropagationClient propagationClient = new PropagationClient();
289         for (String resourceId : propagationIdsCreated) {
290             // Note: Any non-success responses are ignored and not reported.
291             propagationClient.delete(resourceId).close(); // alternative to propagationClient.delete(resourceId).releaseConnection();
292         }
293
294         //
295         // Delete Person resource(s) (before PersonAuthority resources). 
296         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
297         for (String resourceId : personIdsCreated) {
298             // Note: Any non-success responses are ignored and not reported.
299                 personAuthClient.deleteItem(personAuthCSID, resourceId).close();
300         }
301         if (personAuthCSID != null) {
302                 personAuthClient.delete(personAuthCSID).close();
303         }
304     }
305
306     // ---------------------------------------------------------------
307     // Utility methods used by tests above
308     // ---------------------------------------------------------------
309     public String getServiceName() {
310         return PropagationClient.SERVICE_NAME;
311     }
312
313     @Override
314     public String getServicePathComponent() {
315         return PropagationClient.SERVICE_PATH_COMPONENT;
316     }
317
318     private PoxPayloadOut createPropagationInstance(String propagationNumber,
319                 String propagatedBy,
320                 String returnDate) throws Exception {
321         PropagationsCommon propagationCommon = new PropagationsCommon();
322         propagationCommon.setPropNumber(propagationNumber);
323         propagationCommon.setPropBy(propagatedBy);
324         propagationCommon.setPropNumber(returnDate);
325         
326         PropActivityGroupList propActivityGroupList =  new PropActivityGroupList();
327         PropActivityGroup propActivityGroup = new PropActivityGroup();
328         propActivityGroup.setOrder(BigInteger.valueOf(42));
329         propActivityGroupList.getPropActivityGroup().add(propActivityGroup);
330         propagationCommon.setPropActivityGroupList(propActivityGroupList);
331
332         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
333         PayloadOutputPart commonPart = multipart.addPart(new PropagationClient().getCommonPartName(), propagationCommon);
334
335         if (logger.isDebugEnabled()) {
336                 logger.debug("to be created, propagation common");
337                 logger.debug(objectAsXmlString(propagationCommon, PropagationsCommon.class));
338         }
339
340         return multipart;
341     }
342
343     @Override
344     protected Class<AbstractCommonList> getCommonListType() {
345         return AbstractCommonList.class;
346     }
347
348         @Override
349         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) throws Exception {
350                 // TODO Auto-generated method stub
351                 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
352         }
353 }