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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright © 2009 Regents of the University of California
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
23 package org.collectionspace.services.client.test;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
30 import javax.ws.rs.core.Response;
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.MainBodyGroup;
42 import org.collectionspace.services.organization.MainBodyGroupList;
43 import org.collectionspace.services.organization.OrganizationsCommon;
45 import org.jboss.resteasy.client.ClientResponse;
47 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
48 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * LoaninAuthRefsTest, carries out Authority References tests against a
58 * deployed and running Loanin (aka Loans In) Service.
60 * $LastChangedRevision$
63 public class OrgAuthorityAuthRefsTest extends BaseServiceTest {
66 private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
67 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
69 // Instance variables specific to this test.
70 final String SERVICE_PATH_COMPONENT = "orgauthorities";
71 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
72 final String ORG_AUTHORITY_NAME = "TestOrgAuth";
75 private String knownResourceId = null;
76 private String knownResourceRefName = null;
78 /** The known item id. */
79 private String knownItemResourceId = null;
81 /** The all resource ids created. */
82 private List<String> allResourceIdsCreated = new ArrayList<String>();
84 /** The all item resource ids created. */
85 private Map<String, String> allItemResourceIdsCreated =
86 new HashMap<String, String>();
88 /** The person ids created. */
89 private List<String> personIdsCreated = new ArrayList<String>();
91 // CSID for the instance of the test Person authority
92 // created during testing.
93 private String personAuthCSID = null;
95 /** The organization contact person refNames. */
96 private String organizationContactPersonRefName1 = null;
97 private String organizationContactPersonRefName2 = null;
99 // The refName of an Organization item that represents
100 // the sub-body organization of a second Organization item.
101 private String subBodyRefName = null;
103 /** The number of authorityreferences expected. */
104 private final int NUM_AUTH_REFS_EXPECTED = 3;
106 protected void setKnownResource( String id, String refName ) {
107 knownResourceId = id;
108 knownResourceRefName = refName;
112 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
115 protected CollectionSpaceClient getClientInstance() {
116 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
120 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
123 protected AbstractCommonList getAbstractCommonList(
124 ClientResponse<AbstractCommonList> response) {
125 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
128 // ---------------------------------------------------------------
129 // CRUD tests : CREATE tests
130 // ---------------------------------------------------------------
133 * Creates the with auth refs.
135 * @param testName the test name
136 * @throws Exception the exception
138 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
139 public void createWithAuthRefs(String testName) throws Exception {
141 if (logger.isDebugEnabled()) {
142 logger.debug(testBanner(testName, CLASS_NAME));
144 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
146 // Create a new Organization Authority resource.
147 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
148 String shortId = createIdentifier();
149 String displayName = "TestOrgAuth-" + shortId;
150 String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
151 MultipartOutput multipart =
152 OrgAuthorityClientUtils.createOrgAuthorityInstance(
153 displayName, shortId, orgAuthClient.getCommonPartName());
155 // Submit the request to the service and store the response.
156 ClientResponse<Response> res = orgAuthClient.create(multipart);
158 int statusCode = res.getStatus();
159 // Check the status code of the response: does it match
160 // the expected response(s)?
163 // Does it fall within the set of valid status codes?
164 // Does it exactly match the expected status code?
165 if(logger.isDebugEnabled()){
166 logger.debug(testName + ": status = " + statusCode);
168 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
169 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
170 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
172 // Store the IDs from every resource created by tests,
173 // so they can be deleted after tests have been run.
174 String newId = extractId(res);
175 if (knownResourceId == null){
176 setKnownResource( newId, baseRefName );
178 allResourceIdsCreated.add(newId);
180 res.releaseConnection();
183 // Create all the person refs and entities
186 // Create all the organization sub-body refs and entities
187 createSubBodyOrgRefs();
189 // Initialize values for a new Organization item, to be created within
190 // the newly-created Organization Authority resource.
192 // One or more fields in the Organization item record will
193 // contain references to Persons, via their refNames, as
194 // per the initialization(s) below.
195 Map<String, String> testOrgMap = new HashMap<String,String>();
196 testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
197 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
199 Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
200 List<String> testOrgContactNames = new ArrayList<String>();
201 testOrgContactNames.add(organizationContactPersonRefName1);
202 testOrgContactNames.add(organizationContactPersonRefName2);
203 testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
204 List<String> testOrgSubBodies = new ArrayList<String>();
205 testOrgSubBodies.add(subBodyRefName);
206 testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
208 MainBodyGroupList mainBodyList = new MainBodyGroupList();
209 List<MainBodyGroup> mainBodyGroups = mainBodyList.getMainBodyGroup();
210 MainBodyGroup mainBodyGroup = new MainBodyGroup();
211 mainBodyGroup.setShortName("Test Organization-" + shortId);
212 mainBodyGroup.setLongName("Test Organization Name");
213 mainBodyGroups.add(mainBodyGroup);
215 // Finishing creating the new Organization item, then
216 // submit the request to the service and store the response.
217 knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
218 knownResourceId, knownResourceRefName, testOrgMap,
219 testOrgRepeatablesMap, mainBodyList, orgAuthClient);
221 // Store the IDs from every item created by tests,
222 // so they can be deleted after tests have been run.
223 allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
227 * Creates the person refs.
229 protected void createPersonRefs() {
230 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
231 // Create a temporary PersonAuthority resource, and its corresponding
232 // refName by which it can be identified.
233 MultipartOutput multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
234 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
236 ClientResponse<Response> res = personAuthClient.create(multipart);
238 int statusCode = res.getStatus();
239 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
240 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
241 Assert.assertEquals(statusCode, STATUS_CREATED);
242 personAuthCSID = extractId(res);
244 res.releaseConnection();
247 String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
249 // Create temporary Person resources, and their corresponding refNames
250 // by which they can be identified.
251 String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", authRefName);
252 personIdsCreated.add(csid);
253 organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
255 // Create temporary Person resources, and their corresponding refNames
256 // by which they can be identified.
257 csid = createPerson("Chelsie", "Contact", "chelsieContact", authRefName);
258 personIdsCreated.add(csid);
259 organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
263 * Creates the person.
265 * @param firstName the first name
266 * @param surName the sur name
271 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
272 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
273 Map<String, String> personInfo = new HashMap<String,String>();
274 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
275 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
276 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
277 MultipartOutput multipart =
278 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
279 authRefName, personInfo, personAuthClient.getItemCommonPartName());
281 String result = null;
282 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
284 int statusCode = res.getStatus();
286 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
287 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
288 Assert.assertEquals(statusCode, STATUS_CREATED);
289 result = extractId(res);
291 res.releaseConnection();
297 private void createSubBodyOrgRefs() {
298 // Create a temporary sub-body Organization resource, and its corresponding refName
299 // by which it can be identified.
301 // This sub-body Organization resource will be created in the same
302 // Organization authority as its parent Organization resource.
304 String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
305 allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
306 subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
309 protected String createSubBodyOrganization(String subBodyName) {
310 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
311 Map<String, String> subBodyOrgMap = new HashMap<String,String>();
312 String shortId = createIdentifier();
313 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
314 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
315 subBodyName + "-" + shortId);
316 subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
317 subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
318 MultipartOutput multipart =
319 OrgAuthorityClientUtils.createOrganizationInstance(
320 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
322 String result = null;
323 ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
325 int statusCode = res.getStatus();
326 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
327 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
328 Assert.assertEquals(statusCode, STATUS_CREATED);
329 result = extractId(res);
331 res.releaseConnection();
339 * Read and check auth refs.
341 * @param testName the test name
342 * @throws Exception the exception
344 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
345 dependsOnMethods = {"createWithAuthRefs"})
346 public void readAndCheckAuthRefs(String testName) throws Exception {
348 if (logger.isDebugEnabled()) {
349 logger.debug(testBanner(testName, CLASS_NAME));
352 testSetup(STATUS_OK, ServiceRequestType.READ);
354 // Submit the request to the service and store the response.
355 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
356 ClientResponse<MultipartInput> res =
357 orgAuthClient.readItem(knownResourceId, knownItemResourceId);
358 int statusCode = res.getStatus();
360 // Check the status code of the response: does it match
361 // the expected response(s)?
362 if(logger.isDebugEnabled()){
363 logger.debug(testName + ".read: status = " + statusCode);
365 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
366 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
367 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
369 MultipartInput input = (MultipartInput) res.getEntity();
370 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
371 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
372 Assert.assertNotNull(organization);
373 if(logger.isDebugEnabled()){
374 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
376 // Check one or more of the authority fields in the Organization item
377 Assert.assertEquals(organization.getContactNames().getContactName().get(0),
378 organizationContactPersonRefName1);
379 Assert.assertEquals(organization.getContactNames().getContactName().get(1),
380 organizationContactPersonRefName2);
381 Assert.assertEquals(organization.getSubBodies().getSubBody().get(0),
384 // Get the auth refs and check them
385 // FIXME - need to create this method in the client
386 // and get the ID for the organization item
387 ClientResponse<AuthorityRefList> res2 =
388 orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
389 statusCode = res2.getStatus();
391 if(logger.isDebugEnabled()){
392 logger.debug(testName + ".getAuthorityRefs: status = " + statusCode);
394 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
395 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
396 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
397 AuthorityRefList list = res2.getEntity();
399 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
400 int numAuthRefsFound = items.size();
401 if(logger.isDebugEnabled()){
402 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
403 " authority references, found " + numAuthRefsFound);
405 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
406 "Did not find all expected authority references! " +
407 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
409 // Optionally output additional data about list members for debugging.
410 boolean iterateThroughList = true;
411 if(iterateThroughList && logger.isDebugEnabled()){
413 for(AuthorityRefList.AuthorityRefItem item : items){
414 logger.debug(testName + ": list-item[" + i + "] Field:" +
415 item.getSourceField() + "=" +
416 item.getItemDisplayName());
417 logger.debug(testName + ": list-item[" + i + "] refName=" +
419 logger.debug(testName + ": list-item[" + i + "] URI=" +
426 // ---------------------------------------------------------------
427 // Cleanup of resources created during testing
428 // ---------------------------------------------------------------
431 * Deletes all resources created by tests, after all tests have been run.
433 * This cleanup method will always be run, even if one or more tests fail.
434 * For this reason, it attempts to remove all resources created
435 * at any point during testing, even if some of those resources
436 * may be expected to be deleted by certain tests.
438 @AfterClass(alwaysRun=true)
439 public void cleanUp() {
440 String noTest = System.getProperty("noTestCleanup");
441 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
442 if (logger.isDebugEnabled()) {
443 logger.debug("Skipping Cleanup phase ...");
447 if (logger.isDebugEnabled()) {
448 logger.debug("Cleaning up temporary resources created for testing ...");
450 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
451 // Delete Person resource(s) (before PersonAuthority resources).
452 for (String resourceId : personIdsCreated) {
453 // Note: Any non-success responses are ignored and not reported.
454 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
456 // Delete PersonAuthority resource(s).
457 // Note: Any non-success response is ignored and not reported.
458 if(personAuthCSID!=null) {
459 personAuthClient.delete(personAuthCSID).releaseConnection();
462 String parentResourceId;
463 String itemResourceId;
464 OrgAuthorityClient client = new OrgAuthorityClient();
465 // Clean up item resources.
466 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
467 itemResourceId = entry.getKey();
468 parentResourceId = entry.getValue();
469 // Note: Any non-success responses from the delete operation
470 // below are ignored and not reported.
471 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
474 // Clean up parent resources.
475 for (String resourceId : allResourceIdsCreated) {
476 // Note: Any non-success responses from the delete operation
477 // below are ignored and not reported.
478 client.delete(resourceId).releaseConnection();
482 // ---------------------------------------------------------------
483 // Utility methods used by tests above
484 // ---------------------------------------------------------------
486 * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
489 public String getServicePathComponent() {
490 return SERVICE_PATH_COMPONENT;