]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
41933994248411cce94be1d58480978b994589f6
[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 Logger logger =
65        LoggerFactory.getLogger(OrgAuthorityAuthRefsTest.class);
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 CREATE d_ status. */
94     private int CREATED_STATUS = Response.Status.CREATED.getStatusCode();
95     
96     /** The O k_ status. */
97     private int OK_STATUS = Response.Status.OK.getStatusCode();
98     
99     /** The person auth csid. */
100     private String personAuthCSID = null;
101     
102     /** The organization contact person ref name. */
103     private String organizationContactPersonRefName = null;
104     
105     /** The NU m_ aut h_ ref s_ expected. */
106     private final int NUM_AUTH_REFS_EXPECTED = 1;
107
108     /* (non-Javadoc)
109      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
110      */
111     @Override
112     protected CollectionSpaceClient getClientInstance() {
113         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
114     }
115     
116     /* (non-Javadoc)
117      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
118      */
119     @Override
120         protected AbstractCommonList getAbstractCommonList(
121                         ClientResponse<AbstractCommonList> response) {
122         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
123     }
124
125     // ---------------------------------------------------------------
126     // CRUD tests : CREATE tests
127     // ---------------------------------------------------------------
128     // Success outcomes
129     /**
130      * Creates the with auth refs.
131      *
132      * @param testName the test name
133      * @throws Exception the exception
134      */
135     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
136     public void createWithAuthRefs(String testName) throws Exception {
137
138         testSetup(CREATED_STATUS, ServiceRequestType.CREATE,testName);
139
140         // Create a new Organization Authority resource.
141         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
142         String identifier = createIdentifier();
143         String displayName = "TestOrgAuth-" + identifier;
144         boolean createWithDisplayName = false;
145         knownResourceRefName =
146             OrgAuthorityClientUtils.createOrgAuthRefName(displayName, createWithDisplayName);
147         MultipartOutput multipart =
148             OrgAuthorityClientUtils.createOrgAuthorityInstance(
149                 displayName, knownResourceRefName, orgAuthClient.getCommonPartName());
150
151         // Submit the request to the service and store the response.
152         ClientResponse<Response> res = orgAuthClient.create(multipart);
153         try {
154                 int statusCode = res.getStatus();
155                 // Check the status code of the response: does it match
156                 // the expected response(s)?
157                 //
158                 // Specifically:
159                 // Does it fall within the set of valid status codes?
160                 // Does it exactly match the expected status code?
161                 if(logger.isDebugEnabled()){
162                     logger.debug(testName + ": status = " + statusCode);
163                 }
164                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
165                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
166                 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
167         
168                 // Store the IDs from every resource created by tests,
169                 // so they can be deleted after tests have been run.
170                 knownAuthResourceId = extractId(res);
171         } finally {
172                 res.releaseConnection();
173         }        
174         allResourceIdsCreated.add(knownAuthResourceId);
175
176         // Create all the person refs and entities
177         createPersonRefs();
178
179         // Initialize values for a new Organization item, to be created within
180         // the newly-created Organization Authority resource.
181         //
182         // One or more fields in the Organization item record will
183         // contain references to Persons, via their refNames, as
184         // per the initialization(s) below.
185         Map<String, String> testOrgMap = new HashMap<String,String>();
186         testOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
187             "Test Organization-" + identifier);
188         testOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Test Organization Name");
189         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
190         testOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, organizationContactPersonRefName);
191
192         // Finishing creating the new Organization item, then
193         // submit the request to the service and store the response.
194         knownItemId = OrgAuthorityClientUtils.createItemInAuthority(
195             knownAuthResourceId, knownResourceRefName, testOrgMap, orgAuthClient);
196
197         // Store the IDs from every item created by tests,
198         // so they can be deleted after tests have been run.
199         allItemResourceIdsCreated.put(knownItemId, knownAuthResourceId);
200     }
201     
202     /**
203      * Creates the person refs.
204      */
205     protected void createPersonRefs() {
206         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
207         // Create a temporary PersonAuthority resource, and its corresponding
208         // refName by which it can be identified.
209         String authRefName = 
210             PersonAuthorityClientUtils.createPersonAuthRefName(PERSON_AUTHORITY_NAME, false);
211         MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
212             PERSON_AUTHORITY_NAME, authRefName, personAuthClient.getCommonPartName());
213         
214         ClientResponse<Response> res = personAuthClient.create(multipart);
215         try {
216                 int statusCode = res.getStatus();       
217                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
218                     invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
219                 Assert.assertEquals(statusCode, CREATED_STATUS);
220                 personAuthCSID = extractId(res);
221         } finally {
222                 res.releaseConnection();
223         }
224
225         // Create a temporary Person resource, and its corresponding refName
226         // by which it can be identified.
227         organizationContactPersonRefName =
228             PersonAuthorityClientUtils.createPersonRefName(authRefName, "Charlie Orgcontact", true);
229         personIdsCreated.add(createPerson("Charlie", "Orgcontact", organizationContactPersonRefName));
230
231     }
232     
233     /**
234      * Creates the person.
235      *
236      * @param firstName the first name
237      * @param surName the sur name
238      * @param refName the ref name
239      * @return the string
240      */
241     protected String createPerson(String firstName, String surName, String refName ) {
242         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
243         Map<String, String> personInfo = new HashMap<String,String>();
244         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
245         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
246         MultipartOutput multipart = 
247             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
248                 refName, personInfo, personAuthClient.getItemCommonPartName());
249         
250         String result = null;
251         ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
252         try {
253                 int statusCode = res.getStatus();
254         
255                 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
256                         invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
257                 Assert.assertEquals(statusCode, CREATED_STATUS);
258                 result = extractId(res);
259         } finally {
260                 res.releaseConnection();
261         }
262         
263         return result;
264     }
265
266     // Success outcomes
267     /**
268      * Read and check auth refs.
269      *
270      * @param testName the test name
271      * @throws Exception the exception
272      */
273     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
274         dependsOnMethods = {"createWithAuthRefs"})
275     public void readAndCheckAuthRefs(String testName) throws Exception {
276
277         // Perform setup.
278         testSetup(OK_STATUS, ServiceRequestType.READ,testName);
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 }