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