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.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.jaxb.AbstractCommonList;
43 import org.collectionspace.services.organization.MainBodyGroup;
44 import org.collectionspace.services.organization.MainBodyGroupList;
45 import org.collectionspace.services.organization.OrganizationsCommon;
47 import org.jboss.resteasy.client.ClientResponse;
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 PERSON_AUTHORITY_NAME = "TestPersonAuth";
71 final String ORG_AUTHORITY_NAME = "TestOrgAuth";
74 public String getServicePathComponent() {
75 return OrgAuthorityClient.SERVICE_PATH_COMPONENT;
79 protected String getServiceName() {
80 return OrgAuthorityClient.SERVICE_NAME;
83 private String knownResourceId = null;
84 private String knownResourceRefName = null;
86 /** The known item id. */
87 private String knownItemResourceId = null;
89 /** The all resource ids created. */
90 private List<String> allResourceIdsCreated = new ArrayList<String>();
92 /** The all item resource ids created. */
93 private Map<String, String> allItemResourceIdsCreated =
94 new HashMap<String, String>();
96 /** The person ids created. */
97 private List<String> personIdsCreated = new ArrayList<String>();
99 // CSID for the instance of the test Person authority
100 // created during testing.
101 private String personAuthCSID = null;
103 /** The organization contact person refNames. */
104 private String organizationContactPersonRefName1 = null;
105 private String organizationContactPersonRefName2 = null;
107 // The refName of an Organization item that represents
108 // the sub-body organization of a second Organization item.
109 private String subBodyRefName = null;
111 /** The number of authorityreferences expected. */
112 private final int NUM_AUTH_REFS_EXPECTED = 2; // Place authRef not legal, should not be returned.
114 protected void setKnownResource( String id, String refName ) {
115 knownResourceId = id;
116 knownResourceRefName = refName;
120 * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
123 protected CollectionSpaceClient getClientInstance() {
124 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
128 * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
131 protected AbstractCommonList getAbstractCommonList(
132 ClientResponse<AbstractCommonList> response) {
133 throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
136 // ---------------------------------------------------------------
137 // CRUD tests : CREATE tests
138 // ---------------------------------------------------------------
141 * Creates the with auth refs.
143 * @param testName the test name
144 * @throws Exception the exception
146 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
147 public void createWithAuthRefs(String testName) throws Exception {
149 if (logger.isDebugEnabled()) {
150 logger.debug(testBanner(testName, CLASS_NAME));
152 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
154 // Create a new Organization Authority resource.
155 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
156 String shortId = createIdentifier();
157 String displayName = "TestOrgAuth-" + shortId;
158 //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
159 PoxPayloadOut multipart =
160 OrgAuthorityClientUtils.createOrgAuthorityInstance(
161 displayName, shortId, orgAuthClient.getCommonPartName());
163 // Submit the request to the service and store the response.
164 ClientResponse<Response> res = orgAuthClient.create(multipart);
166 int statusCode = res.getStatus();
167 // Check the status code of the response: does it match
168 // the expected response(s)?
171 // Does it fall within the set of valid status codes?
172 // Does it exactly match the expected status code?
173 if(logger.isDebugEnabled()){
174 logger.debug(testName + ": status = " + statusCode);
176 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
177 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
178 Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
180 // Store the IDs from every resource created by tests,
181 // so they can be deleted after tests have been run.
182 String newId = extractId(res);
183 if (knownResourceId == null){
184 setKnownResource( newId, null ); //baseRefName );
186 allResourceIdsCreated.add(newId);
188 res.releaseConnection();
191 // Create all the person refs and entities
194 // Create all the organization sub-body refs and entities
195 createSubBodyOrgRefs();
197 // Initialize values for a new Organization item, to be created within
198 // the newly-created Organization Authority resource.
200 // One or more fields in the Organization item record will
201 // contain references to Persons, via their refNames, as
202 // per the initialization(s) below.
203 Map<String, String> testOrgMap = new HashMap<String,String>();
204 testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
205 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
207 Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
208 List<String> testOrgContactNames = new ArrayList<String>();
209 testOrgContactNames.add(organizationContactPersonRefName1);
210 testOrgContactNames.add(organizationContactPersonRefName2);
211 testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
212 List<String> testOrgSubBodies = new ArrayList<String>();
213 testOrgSubBodies.add(subBodyRefName);
214 testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
216 MainBodyGroupList mainBodyList = new MainBodyGroupList();
217 List<MainBodyGroup> mainBodyGroups = mainBodyList.getMainBodyGroup();
218 MainBodyGroup mainBodyGroup = new MainBodyGroup();
219 mainBodyGroup.setShortName("Test Organization-" + shortId);
220 mainBodyGroup.setLongName("Test Organization Name");
221 mainBodyGroups.add(mainBodyGroup);
223 // Finishing creating the new Organization item, then
224 // submit the request to the service and store the response.
225 knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
226 knownResourceId, knownResourceRefName, testOrgMap,
227 testOrgRepeatablesMap, mainBodyList, orgAuthClient);
229 // Store the IDs from every item created by tests,
230 // so they can be deleted after tests have been run.
231 allItemResourceIdsCreated.put(knownItemResourceId, knownResourceId);
235 * Creates the person refs.
237 protected void createPersonRefs() {
238 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
239 // Create a temporary PersonAuthority resource, and its corresponding
240 // refName by which it can be identified.
241 PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
242 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
244 ClientResponse<Response> res = personAuthClient.create(multipart);
246 int statusCode = res.getStatus();
247 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
248 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
249 Assert.assertEquals(statusCode, STATUS_CREATED);
250 personAuthCSID = extractId(res);
252 res.releaseConnection();
255 //String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
257 // Create temporary Person resources, and their corresponding refNames
258 // by which they can be identified.
259 String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", null ); // authRefName);
260 personIdsCreated.add(csid);
261 organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
263 // Create temporary Person resources, and their corresponding refNames
264 // by which they can be identified.
265 csid = createPerson("Chelsie", "Contact", "chelsieContact", null ); // authRefName);
266 personIdsCreated.add(csid);
267 organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
271 * Creates the person.
273 * @param firstName the first name
274 * @param surName the sur name
279 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
280 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
281 Map<String, String> personInfo = new HashMap<String,String>();
282 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
283 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
284 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
285 PoxPayloadOut multipart =
286 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
287 authRefName, personInfo, personAuthClient.getItemCommonPartName());
289 String result = null;
290 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
292 int statusCode = res.getStatus();
294 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
295 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
296 Assert.assertEquals(statusCode, STATUS_CREATED);
297 result = extractId(res);
299 res.releaseConnection();
305 private void createSubBodyOrgRefs() {
306 // Create a temporary sub-body Organization resource, and its corresponding refName
307 // by which it can be identified.
309 // This sub-body Organization resource will be created in the same
310 // Organization authority as its parent Organization resource.
312 String subBodyResourceId = createSubBodyOrganization("Test SubBody Organization");
313 allItemResourceIdsCreated.put(subBodyResourceId, knownResourceId);
314 subBodyRefName = OrgAuthorityClientUtils.getOrgRefName(knownResourceId, subBodyResourceId, null);
317 protected String createSubBodyOrganization(String subBodyName) {
318 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
319 Map<String, String> subBodyOrgMap = new HashMap<String,String>();
320 String shortId = createIdentifier();
321 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId );
322 subBodyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME,
323 subBodyName + "-" + shortId);
324 subBodyOrgMap.put(OrganizationJAXBSchema.LONG_NAME, subBodyName + " Long Name");
325 subBodyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, subBodyName + " Founding Place");
326 PoxPayloadOut multipart =
327 OrgAuthorityClientUtils.createOrganizationInstance(
328 knownResourceRefName, subBodyOrgMap, orgAuthClient.getItemCommonPartName());
330 String result = null;
331 ClientResponse<Response> res = orgAuthClient.createItem(knownResourceId, multipart);
333 int statusCode = res.getStatus();
334 Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
335 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
336 Assert.assertEquals(statusCode, STATUS_CREATED);
337 result = extractId(res);
339 res.releaseConnection();
347 * Read and check auth refs.
349 * @param testName the test name
350 * @throws Exception the exception
352 @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
353 dependsOnMethods = {"createWithAuthRefs"})
354 public void readAndCheckAuthRefs(String testName) throws Exception {
356 if (logger.isDebugEnabled()) {
357 logger.debug(testBanner(testName, CLASS_NAME));
360 testSetup(STATUS_OK, ServiceRequestType.READ);
362 // Submit the request to the service and store the response.
363 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
364 ClientResponse<String> res =
365 orgAuthClient.readItem(knownResourceId, knownItemResourceId);
366 assertStatusCode(res, testName);
368 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
369 OrganizationsCommon organization = (OrganizationsCommon) extractPart(input,
370 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
371 Assert.assertNotNull(organization);
372 if(logger.isDebugEnabled()){
373 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
375 // Check one or more of the authority fields in the Organization item
376 Assert.assertEquals(organization.getContactNames().getContactName().get(0),
377 organizationContactPersonRefName1);
378 Assert.assertEquals(organization.getContactNames().getContactName().get(1),
379 organizationContactPersonRefName2);
380 Assert.assertEquals(organization.getSubBodies().getSubBody().get(0),
383 // Get the auth refs and check them
384 // FIXME - need to create this method in the client
385 // and get the ID for the organization item
386 ClientResponse<AuthorityRefList> res2 =
387 orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
388 assertStatusCode(res2, testName);
390 AuthorityRefList list = res2.getEntity();
392 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
393 int numAuthRefsFound = items.size();
394 if(logger.isDebugEnabled()){
395 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
396 " authority references, found " + numAuthRefsFound);
398 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
399 "Did not find all expected authority references! " +
400 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
402 // Optionally output additional data about list members for debugging.
403 boolean iterateThroughList = true;
404 if(iterateThroughList && logger.isDebugEnabled()){
406 for(AuthorityRefList.AuthorityRefItem item : items){
407 logger.debug(testName + ": list-item[" + i + "] Field:" +
408 item.getSourceField() + "=" +
409 item.getItemDisplayName());
410 logger.debug(testName + ": list-item[" + i + "] refName=" +
412 logger.debug(testName + ": list-item[" + i + "] URI=" +
419 // ---------------------------------------------------------------
420 // Cleanup of resources created during testing
421 // ---------------------------------------------------------------
424 * Deletes all resources created by tests, after all tests have been run.
426 * This cleanup method will always be run, even if one or more tests fail.
427 * For this reason, it attempts to remove all resources created
428 * at any point during testing, even if some of those resources
429 * may be expected to be deleted by certain tests.
431 @AfterClass(alwaysRun=true)
432 public void cleanUp() {
433 String noTest = System.getProperty("noTestCleanup");
434 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
435 if (logger.isDebugEnabled()) {
436 logger.debug("Skipping Cleanup phase ...");
440 if (logger.isDebugEnabled()) {
441 logger.debug("Cleaning up temporary resources created for testing ...");
443 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
444 // Delete Person resource(s) (before PersonAuthority resources).
445 for (String resourceId : personIdsCreated) {
446 // Note: Any non-success responses are ignored and not reported.
447 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
449 // Delete PersonAuthority resource(s).
450 // Note: Any non-success response is ignored and not reported.
451 if(personAuthCSID!=null) {
452 personAuthClient.delete(personAuthCSID).releaseConnection();
455 String parentResourceId;
456 String itemResourceId;
457 OrgAuthorityClient client = new OrgAuthorityClient();
458 // Clean up item resources.
459 for (Map.Entry<String, String> entry : allItemResourceIdsCreated.entrySet()) {
460 itemResourceId = entry.getKey();
461 parentResourceId = entry.getValue();
462 // Note: Any non-success responses from the delete operation
463 // below are ignored and not reported.
464 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
467 // Clean up parent resources.
468 for (String resourceId : allResourceIdsCreated) {
469 // Note: Any non-success responses from the delete operation
470 // below are ignored and not reported.
471 client.delete(resourceId).releaseConnection();