]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
cf5c8675efd2122c42d6c512c1de7dbeac5b4417
[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.CollectionObjectClient;
35 import org.collectionspace.services.client.CollectionSpaceClient;
36 import org.collectionspace.services.client.PersonAuthorityClient;
37 import org.collectionspace.services.client.PersonAuthorityClientUtils;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList;
39 import org.collectionspace.services.collectionobject.CollectionobjectsCommon;
40 import org.collectionspace.services.collectionobject.CollectionobjectsCommonList;
41 import org.collectionspace.services.jaxb.AbstractCommonList;
42
43 import org.jboss.resteasy.client.ClientResponse;
44
45 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
47 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
48 import org.testng.Assert;
49 import org.testng.annotations.AfterClass;
50 import org.testng.annotations.Test;
51
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * CollectionObjectAuthRefsTest, carries out tests against a
57  * deployed and running CollectionObject Service.
58  *
59  * $LastChangedRevision: 1327 $
60  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
61  */
62 public class CollectionObjectAuthRefsTest extends BaseServiceTest {
63
64    /** The logger. */
65     private final String CLASS_NAME = CollectionObjectAuthRefsTest.class.getName();
66     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
67
68     // Instance variables specific to this test.
69     /** The service path component. */
70     final String SERVICE_PATH_COMPONENT = "collectionobjects";
71     
72     /** The person authority name. */
73     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
74     
75     /** The known resource id. */
76     private String knownResourceId = null;
77     
78     /** The collection object ids created. */
79     private List<String> collectionObjectIdsCreated = new ArrayList<String>();
80     
81     /** The person ids created. */
82     private List<String> personIdsCreated = new ArrayList<String>();
83     
84     /** The person auth csid. */
85     private String personAuthCSID = null; 
86     private String personAuthRefName = null;
87     
88     /** The content organization ref name. */
89     private String contentOrganizationRefName = null;
90     
91     /** The content people ref name. */
92     private String contentPeopleRefName = null;
93     
94     /** The content person ref name. */
95     private String contentPersonRefName = null;
96     
97     /** The inscriber ref name. */
98     private String contentInscriberRefName = null;
99     
100     /** The number of authority references expected. */
101     private final int NUM_AUTH_REFS_EXPECTED = 4;
102
103     /* (non-Javadoc)
104      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
105      */
106     @Override
107     protected CollectionSpaceClient getClientInstance() {
108         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
109     }
110     
111     /* (non-Javadoc)
112      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
113      */
114     @Override
115         protected AbstractCommonList getAbstractCommonList(
116                         ClientResponse<AbstractCommonList> response) {
117         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
118     }
119
120     // ---------------------------------------------------------------
121     // CRUD tests : CREATE tests
122     // ---------------------------------------------------------------
123     // Success outcomes
124     /**
125      * Creates the with auth refs.
126      *
127      * @param testName the test name
128      * @throws Exception the exception
129      */
130     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
131     public void createWithAuthRefs(String testName) throws Exception {
132
133         if (logger.isDebugEnabled()) {
134             logger.debug(testBanner(testName, CLASS_NAME));
135         }
136         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
137
138         // Submit the request to the service and store the response.
139         String identifier = createIdentifier();
140         
141         // Create all the person refs and entities
142         createPersonRefs();
143         
144         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
145         MultipartOutput multipart = createCollectionObjectInstance(
146                                                         "Obj Title",
147                                                         "ObjNum-1234",
148                                                                 contentOrganizationRefName,
149                                                                 contentPeopleRefName,
150                                                                 contentPersonRefName,
151                                                                 contentInscriberRefName );
152
153         ClientResponse<Response> res = collectionObjectClient.create(multipart);
154
155         int statusCode = res.getStatus();
156
157         // Check the status code of the response: does it match
158         // the expected response(s)?
159         //
160         // Specifically:
161         // Does it fall within the set of valid status codes?
162         // Does it exactly match the expected status code?
163         if(logger.isDebugEnabled()){
164             logger.debug(testName + ": status = " + statusCode);
165         }
166         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
167                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
168         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
169
170         // Store the ID returned from the first resource created
171         // for additional tests below.
172         if (knownResourceId == null){
173             knownResourceId = extractId(res);
174             if (logger.isDebugEnabled()) {
175                 logger.debug(testName + ": knownResourceId=" + knownResourceId);
176             }
177         }
178         
179         // Store the IDs from every resource created by tests,
180         // so they can be deleted after tests have been run.
181         collectionObjectIdsCreated.add(extractId(res));
182     }
183     
184     /**
185      * Creates the person refs.
186      */
187     protected void createPersonRefs(){
188         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
189         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
190                         PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
191         ClientResponse<Response> res = personAuthClient.create(multipart);
192         int statusCode = res.getStatus();
193
194         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
195                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
196         Assert.assertEquals(statusCode, STATUS_CREATED);
197         personAuthCSID = extractId(res);
198         // TODO Test that we can reuse the client above.
199         personAuthRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
200         
201         String csid = createPerson("Omni", "Org", "omniOrg");
202         contentOrganizationRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
203         personIdsCreated.add(csid);
204         
205         csid = createPerson("Pushy", "People", "pushyPeople");
206         contentPeopleRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
207         personIdsCreated.add(csid);
208         
209         csid = createPerson("Connie", "ContactPerson", "connieContactPerson");
210         contentPersonRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
211         personIdsCreated.add(csid);
212         
213         csid = createPerson("Ingrid", "Inscriber", "ingridInscriber");
214         contentInscriberRefName = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
215         personIdsCreated.add(csid);
216     }
217     
218     /**
219      * Creates the person.
220      *
221      * @param firstName the first name
222      * @param surName the sur name
223      * @param refName the ref name
224      * @return the string
225      */
226     protected String createPerson(String firstName, String surName, String shortIdentifier ) {
227         Map<String, String> personInfo = new HashMap<String,String>();
228         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
229         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
230         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
231         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
232         MultipartOutput multipart = 
233                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
234                                 personAuthRefName, personInfo, personAuthClient.getItemCommonPartName());
235         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
236         int statusCode = res.getStatus();
237
238         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
239                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
240         Assert.assertEquals(statusCode, STATUS_CREATED);
241         return extractId(res);
242     }
243
244     // Success outcomes
245     /**
246      * Read and check auth refs.
247      *
248      * @param testName the test name
249      * @throws Exception the exception
250      */
251     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
252         dependsOnMethods = {"createWithAuthRefs"})
253     public void readAndCheckAuthRefs(String testName) throws Exception {
254
255         if (logger.isDebugEnabled()) {
256             logger.debug(testBanner(testName, CLASS_NAME));
257         }
258         // Perform setup.
259         testSetup(STATUS_OK, ServiceRequestType.READ);
260
261         // Submit the request to the service and store the response.
262         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
263         ClientResponse<MultipartInput> res = collectionObjectClient.read(knownResourceId);
264         int statusCode = res.getStatus();
265
266         // Check the status code of the response: does it match
267         // the expected response(s)?
268         if(logger.isDebugEnabled()){
269             logger.debug(testName + ".read: status = " + statusCode);
270         }
271         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
272                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
273         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
274
275         MultipartInput input = (MultipartInput) res.getEntity();
276         CollectionobjectsCommon collectionObject = (CollectionobjectsCommon) extractPart(input,
277                         collectionObjectClient.getCommonPartName(), CollectionobjectsCommon.class);
278         Assert.assertNotNull(collectionObject);
279         // Check a couple of fields
280         Assert.assertEquals(collectionObject.getContentOrganization(), contentOrganizationRefName);
281         Assert.assertEquals(collectionObject.getInscriptionContentInscriber(), contentInscriberRefName);
282         
283         // Get the auth refs and check them
284         ClientResponse<AuthorityRefList> res2 = collectionObjectClient.getAuthorityRefs(knownResourceId);
285         statusCode = res2.getStatus();
286
287         if(logger.isDebugEnabled()){
288             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
289         }
290         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
291                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
292         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
293         AuthorityRefList list = res2.getEntity();
294         
295         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
296         int numAuthRefsFound = items.size();
297         if(logger.isDebugEnabled()){
298             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
299                 " authority references, found " + numAuthRefsFound);
300         }
301         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
302             "Did not find all expected authority references! " +
303             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
304
305         // Optionally output additional data about list members for debugging.
306         boolean iterateThroughList = true;
307         if(iterateThroughList && logger.isDebugEnabled()){;
308             int i = 0;
309             for(AuthorityRefList.AuthorityRefItem item : items){
310                 logger.debug(testName + ": list-item[" + i + "] Field:" +
311                                 item.getSourceField() + "= " +
312                         item.getAuthDisplayName() +
313                         item.getItemDisplayName());
314                 logger.debug(testName + ": list-item[" + i + "] refName=" +
315                         item.getRefName());
316                 logger.debug(testName + ": list-item[" + i + "] URI=" +
317                         item.getUri());
318                 i++;
319             }
320         }
321     }
322
323
324     // ---------------------------------------------------------------
325     // Cleanup of resources created during testing
326     // ---------------------------------------------------------------
327
328     /**
329      * Deletes all resources created by tests, after all tests have been run.
330      *
331      * This cleanup method will always be run, even if one or more tests fail.
332      * For this reason, it attempts to remove all resources created
333      * at any point during testing, even if some of those resources
334      * may be expected to be deleted by certain tests.
335      */
336     @AfterClass(alwaysRun=true)
337     public void cleanUp() {
338         String noTest = System.getProperty("noTestCleanup");
339         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
340             if (logger.isDebugEnabled()) {
341                 logger.debug("Skipping Cleanup phase ...");
342             }
343             return;
344         }
345         if (logger.isDebugEnabled()) {
346             logger.debug("Cleaning up temporary resources created for testing ...");
347         }
348         CollectionObjectClient collectionObjectClient = new CollectionObjectClient();
349         for (String resourceId : collectionObjectIdsCreated) {
350             // Note: Any non-success responses are ignored and not reported.
351             collectionObjectClient.delete(resourceId).releaseConnection();
352         }
353         // Note: Any non-success response is ignored and not reported.
354         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
355         // Delete persons before PersonAuth
356         for (String resourceId : personIdsCreated) {
357             // Note: Any non-success responses are ignored and not reported.
358             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
359         }
360         personAuthClient.delete(personAuthCSID).releaseConnection();
361     }
362
363     // ---------------------------------------------------------------
364     // Utility methods used by tests above
365     // ---------------------------------------------------------------
366     /* (non-Javadoc)
367      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
368      */
369     @Override
370     public String getServicePathComponent() {
371         return SERVICE_PATH_COMPONENT;
372     }
373
374    /**
375     * Creates the collection object instance.
376     *
377     * @param title the title
378     * @param objNum the obj num
379     * @param contentOrganization the content organization
380     * @param contentPeople the content people
381     * @param contentPerson the content person
382     * @param inscriber the inscriber
383     * @return the multipart output
384     */
385    private MultipartOutput createCollectionObjectInstance(
386                                 String title,
387                                 String objNum,
388                                 String contentOrganization,
389                                 String contentPeople,
390                                 String contentPerson,
391                                 String inscriber ) {
392         CollectionobjectsCommon collectionObject = new CollectionobjectsCommon();
393         collectionObject.setTitle(title);
394         collectionObject.setObjectNumber(objNum);
395         collectionObject.setContentOrganization(contentOrganization);
396         collectionObject.setContentPeople(contentPeople);
397         collectionObject.setContentPerson(contentPerson);
398         collectionObject.setInscriptionContentInscriber(inscriber);
399         MultipartOutput multipart = new MultipartOutput();
400         OutputPart commonPart =
401             multipart.addPart(collectionObject, MediaType.APPLICATION_XML_TYPE);
402         commonPart.getHeaders().add("label", new CollectionObjectClient().getCommonPartName());
403
404         if(logger.isDebugEnabled()){
405             logger.debug("to be created, collectionObject common");
406             logger.debug(objectAsXmlString(collectionObject, CollectionobjectsCommon.class));
407         }
408
409         return multipart;
410     }
411 }