]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d9404fd9bb0b1a878cc42b06937f11e828a2babc
[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.Response;
31
32 import org.collectionspace.services.OrganizationJAXBSchema;
33 import org.collectionspace.services.PersonJAXBSchema;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.OrgAuthorityClient;
36 import org.collectionspace.services.client.OrgAuthorityClientUtils;
37 import org.collectionspace.services.client.PersonAuthorityClient;
38 import org.collectionspace.services.client.PersonAuthorityClientUtils;
39 import org.collectionspace.services.common.authorityref.AuthorityRefList;
40 import org.collectionspace.services.jaxb.AbstractCommonList;
41 import org.collectionspace.services.organization.OrganizationsCommon;
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.testng.Assert;
48 import org.testng.annotations.AfterClass;
49 import org.testng.annotations.Test;
50
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * LoaninAuthRefsTest, carries out Authority References tests against a
56  * deployed and running Loanin (aka Loans In) Service.
57  *
58  * $LastChangedRevision: 1327 $
59  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
60  */
61 public class OrgAuthorityAuthRefsTest extends BaseServiceTest {
62
63    /** The logger. */
64     private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
65     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
66
67     // Instance variables specific to this test.
68     /** The SERVIC e_ pat h_ component. */
69     final String SERVICE_PATH_COMPONENT = "orgauthorities";
70     
71     /** The PERSO n_ authorit y_ name. */
72     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
73     
74     /** The known resource ref name. */
75     private String knownResourceRefName = null;
76     
77     /** The known auth resource id. */
78     private String knownAuthResourceId = null;
79     
80     /** The known item id. */
81     private String knownItemId = null;
82     
83     /** The all resource ids created. */
84     private List<String> allResourceIdsCreated = new ArrayList<String>();
85     
86     /** The all item resource ids created. */
87     private Map<String, String> allItemResourceIdsCreated =
88         new HashMap<String, String>();
89     
90     /** The person ids created. */
91     private List<String> personIdsCreated = new ArrayList<String>();
92     
93     /** The person auth csid. */
94     private String personAuthCSID = null;
95     
96     /** The organization contact person ref name. */
97     private String organizationContactPersonRefName = null;
98     
99     /** The number of authorityreferences expected. */
100     private final int NUM_AUTH_REFS_EXPECTED = 1;
101
102     /* (non-Javadoc)
103      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
104      */
105     @Override
106     protected CollectionSpaceClient getClientInstance() {
107         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
108     }
109     
110     /* (non-Javadoc)
111      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
112      */
113     @Override
114         protected AbstractCommonList getAbstractCommonList(
115                         ClientResponse<AbstractCommonList> response) {
116         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
117     }
118
119     // ---------------------------------------------------------------
120     // CRUD tests : CREATE tests
121     // ---------------------------------------------------------------
122     // Success outcomes
123     /**
124      * Creates the with auth refs.
125      *
126      * @param testName the test name
127      * @throws Exception the exception
128      */
129     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
130     public void createWithAuthRefs(String testName) throws Exception {
131
132         if (logger.isDebugEnabled()) {
133             logger.debug(testBanner(testName, CLASS_NAME));
134         }
135         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
136
137         // Create a new Organization Authority resource.
138         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
139         String identifier = createIdentifier();
140         String displayName = "TestOrgAuth-" + identifier;
141         boolean createWithDisplayName = false;
142         knownResourceRefName =
143             OrgAuthorityClientUtils.createOrgAuthRefName(displayName, createWithDisplayName);
144         MultipartOutput multipart =
145             OrgAuthorityClientUtils.createOrgAuthorityInstance(
146                 displayName, knownResourceRefName, orgAuthClient.getCommonPartName());
147
148         // Submit the request to the service and store the response.
149         ClientResponse<Response> res = orgAuthClient.create(multipart);
150         try {
151                 int statusCode = res.getStatus();
152                 // Check the status code of the response: does it match
153                 // the expected response(s)?
154                 //
155                 // Specifically:
156                 // Does it fall within the set of valid status codes?
157                 // Does it exactly match the expected status code?
158                 if(logger.isDebugEnabled()){
159                     logger.debug(testName + ": status = " + statusCode);
160                 }
161                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
162                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
163                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
164         
165                 // Store the IDs from every resource created by tests,
166                 // so they can be deleted after tests have been run.
167                 knownAuthResourceId = extractId(res);
168         } finally {
169                 res.releaseConnection();
170         }        
171         allResourceIdsCreated.add(knownAuthResourceId);
172
173         // Create all the person refs and entities
174         createPersonRefs();
175
176         // Initialize values for a new Organization item, to be created within
177         // the newly-created Organization Authority resource.
178         //
179         // One or more fields in the Organization item record will
180         // contain references to Persons, via their refNames, as
181         // per the initialization(s) below.
182         Map<String, String> testOrgMap = new HashMap<String,String>();
183         testOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
184             "Test Organization-" + identifier);
185         testOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Test Organization Name");
186         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
187         testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
188
189         // Finishing creating the new Organization item, then
190         // submit the request to the service and store the response.
191         knownItemId = OrgAuthorityClientUtils.createItemInAuthority(
192             knownAuthResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
193
194         // Store the IDs from every item created by tests,
195         // so they can be deleted after tests have been run.
196         allItemResourceIdsCreated.put(knownItemId, knownAuthResourceId);
197     }
198     
199     /**
200      * Creates the person refs.
201      */
202     protected void createPersonRefs() {
203         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
204         // Create a temporary PersonAuthority resource, and its corresponding
205         // refName by which it can be identified.
206         String authRefName = 
207             PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
208         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
209             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
210         
211         ClientResponse<Response> res = personAuthClient.create(multipart);
212         try {
213                 int statusCode = res.getStatus();       
214                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
215                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
216                 Assert.assertEquals(statusCode, STATUS_CREATED);
217                 personAuthCSID = extractId(res);
218         } finally {
219                 res.releaseConnection();
220         }
221
222         // Create a temporary Person resource, and its corresponding refName
223         // by which it can be identified.
224         organizationContactPersonRefName =
225             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Charlie Orgcontact", true);
226         personIdsCreated.add(createPerson("Charlie", "Orgcontact", organizationContactPersonRefName));
227
228     }
229     
230     /**
231      * Creates the person.
232      *
233      * @param firstName the first name
234      * @param surName the sur name
235      * @param refName the ref name
236      * @return the string
237      */
238     protected String createPerson(String firstName, String surName, String refName ) {
239         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
240         Map<String, String> personInfo = new HashMap<String,String>();
241         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
242         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
243         MultipartOutput multipart = 
244             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
245                 refName, personInfo, personAuthClient.getItemCommonPartName());
246         
247         String result = null;
248         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
249         try {
250                 int statusCode = res.getStatus();
251         
252                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
253                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
254                 Assert.assertEquals(statusCode, STATUS_CREATED);
255                 result = extractId(res);
256         } finally {
257                 res.releaseConnection();
258         }
259         
260         return result;
261     }
262
263     // Success outcomes
264     /**
265      * Read and check auth refs.
266      *
267      * @param testName the test name
268      * @throws Exception the exception
269      */
270     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
271         dependsOnMethods = {"createWithAuthRefs"})
272     public void readAndCheckAuthRefs(String testName) throws Exception {
273
274         if (logger.isDebugEnabled()) {
275             logger.debug(testBanner(testName, CLASS_NAME));
276         }
277         // Perform setup.
278         testSetup(STATUS_OK, ServiceRequestType.READ);
279
280         // Submit the request to the service and store the response.
281         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
282         ClientResponse<MultipartInput> res =
283             orgAuthClient.readItem(knownAuthResourceId, knownItemId);
284         int statusCode = res.getStatus();
285
286         // Check the status code of the response: does it match
287         // the expected response(s)?
288         if(logger.isDebugEnabled()){
289             logger.debug(testName + ".read: status = " + statusCode);
290         }
291         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
292             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
293         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
294
295         MultipartInput input = (MultipartInput) res.getEntity();
296         OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
297             orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
298         Assert.assertNotNull(organization);
299         if(logger.isDebugEnabled()){
300             logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
301         }
302         // Check one or more of the authority fields in the Organization item
303         Assert.assertEquals(organization.getContactName(), organizationContactPersonRefName);
304         
305         // Get the auth refs and check them
306         // FIXME - need to create this method in the client
307         // and get the ID for the organization item
308         ClientResponse<AuthorityRefList> res2 =
309            orgAuthClient.getItemAuthorityRefs(knownAuthResourceId, knownItemId);
310         statusCode = res2.getStatus();
311
312         if(logger.isDebugEnabled()){
313             logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
314         }
315         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
316             invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
317         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
318         AuthorityRefList list = res2.getEntity();
319
320         // Optionally output additional data about list members for debugging.
321         boolean iterateThroughList = true;
322         if(iterateThroughList && logger.isDebugEnabled()){
323             List<AuthorityRefList.AuthorityRefItem> items =
324                 list.getAuthorityRefItem();
325             int i = 0;
326             for(AuthorityRefList.AuthorityRefItem item : items){
327                 logger.debug(testName + ": list-item[" + i + "] Field:" +
328                     item.getSourceField() + "=" +
329                     item.getItemDisplayName());
330                 logger.debug(testName + ": list-item[" + i + "] refName=" +
331                     item.getRefName());
332                 logger.debug(testName + ": list-item[" + i + "] URI=" +
333                     item.getUri());
334                 i++;
335             }
336             Assert.assertEquals(i, NUM_AUTH_REFS_EXPECTED, "Did not find all authrefs!");
337         }
338     }
339
340     // ---------------------------------------------------------------
341     // Cleanup of resources created during testing
342     // ---------------------------------------------------------------
343
344     /**
345      * Deletes all resources created by tests, after all tests have been run.
346      *
347      * This cleanup method will always be run, even if one or more tests fail.
348      * For this reason, it attempts to remove all resources created
349      * at any point during testing, even if some of those resources
350      * may be expected to be deleted by certain tests.
351      */
352     @AfterClass(alwaysRun=true)
353     public void cleanUp() {
354         String noTest = System.getProperty("noTestCleanup");
355         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
356             if (logger.isDebugEnabled()) {
357                 logger.debug("Skipping Cleanup phase ...");
358             }
359             return;
360         }
361         if (logger.isDebugEnabled()) {
362             logger.debug("Cleaning up temporary resources created for testing ...");
363         }
364         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
365         // Delete Person resource(s) (before PersonAuthority resources).
366         for (String resourceId : personIdsCreated) {
367             // Note: Any non-success responses are ignored and not reported.
368             personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
369         }
370         // Delete PersonAuthority resource(s).
371         // Note: Any non-success response is ignored and not reported.
372         personAuthClient.delete(personAuthCSID).releaseConnection();
373         
374         String parentResourceId;
375         String itemResourceId;
376         OrgAuthorityClient client = new OrgAuthorityClient();
377         // Clean up item resources.
378         for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
379             itemResourceId = entry.getKey();
380             parentResourceId = entry.getValue();
381             // Note: Any non-success responses from the delete operation
382             // below are ignored and not reported.
383             client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
384         }
385         
386         // Clean up parent resources.
387         for (String resourceId : allResourceIdsCreated) {
388             // Note: Any non-success responses from the delete operation
389             // below are ignored and not reported.
390             client.delete(resourceId).releaseConnection();
391         }
392     }
393
394     // ---------------------------------------------------------------
395     // Utility methods used by tests above
396     // ---------------------------------------------------------------
397     /* (non-Javadoc)
398      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
399      */
400     @Override
401     public String getServicePathComponent() {
402         return SERVICE_PATH_COMPONENT;
403     }
404
405     /**
406      * Creates the org authority instance.
407      *
408      * @param identifier the identifier
409      * @return the multipart output
410      */
411     private MultipartOutput createOrgAuthorityInstance(String identifier) {
412         String displayName = "displayName-" + identifier;
413         String refName = OrgAuthorityClientUtils.createOrgAuthRefName(displayName, true);
414         return OrgAuthorityClientUtils.createOrgAuthorityInstance(
415                                 displayName, refName,
416                                 new OrgAuthorityClient().getCommonPartName());
417     }
418
419 }