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;
46 import org.collectionspace.services.person.PersonTermGroup;
48 import org.jboss.resteasy.client.ClientResponse;
50 import org.testng.Assert;
51 import org.testng.annotations.AfterClass;
52 import org.testng.annotations.Test;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
58 * LoaninAuthRefsTest, carries out Authority References tests against a
59 * deployed and running Loanin (aka Loans In) Service.
61 * $LastChangedRevision$
64 public class OrgAuthorityAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
67 private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
68 private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
70 // Instance variables specific to this test.
71 final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
72 final String ORG_AUTHORITY_NAME = "TestOrgAuth";
75 public String getServicePathComponent() {
76 return OrgAuthorityClient.SERVICE_PATH_COMPONENT;
80 protected String getServiceName() {
81 return OrgAuthorityClient.SERVICE_NAME;
84 protected String knownItemResourceId = null;
86 private String knownResourceRefName = null;
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 = 2; // Place authRef not legal, should not be returned.
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 getCommonList(
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")
139 public void createWithAuthRefs(String testName) throws Exception {
140 testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
142 // Create a new Organization Authority resource.
143 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
144 String shortId = createIdentifier();
145 String displayName = "TestOrgAuth-" + shortId;
146 //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
147 PoxPayloadOut multipart =
148 OrgAuthorityClientUtils.createOrgAuthorityInstance(
149 displayName, shortId, orgAuthClient.getCommonPartName());
151 // Submit the request to the service and store the response.
152 ClientResponse<Response> res = orgAuthClient.create(multipart);
154 int statusCode = res.getStatus();
155 // Check the status code of the response: does it match
156 // the expected response(s)?
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);
164 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
165 invalidStatusCodeMessage(testRequestType, statusCode));
166 Assert.assertEquals(statusCode, testExpectedStatusCode);
168 // Store the IDs from every resource created by tests,
169 // so they can be deleted after tests have been run.
170 String newId = extractId(res);
171 if (knownResourceId == null){
172 setKnownResource( newId, null ); //baseRefName );
174 allResourceIdsCreated.add(newId);
176 res.releaseConnection();
179 // Create all the person refs and entities
182 // Initialize values for a new Organization item, to be created within
183 // the newly-created Organization Authority resource.
185 // One or more fields in the Organization item record will
186 // contain references to Persons, via their refNames, as
187 // per the initialization(s) below.
188 Map<String, String> testOrgMap = new HashMap<String,String>();
189 testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
190 testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
192 Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
193 List<String> testOrgContactNames = new ArrayList<String>();
194 testOrgContactNames.add(organizationContactPersonRefName1);
195 testOrgContactNames.add(organizationContactPersonRefName2);
196 testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
197 List<String> testOrgSubBodies = new ArrayList<String>();
198 testOrgSubBodies.add(subBodyRefName);
199 testOrgRepeatablesMap.put(OrganizationJAXBSchema.SUB_BODIES, testOrgSubBodies);
201 MainBodyGroupList mainBodyList = new MainBodyGroupList();
202 List<MainBodyGroup> mainBodyGroups = mainBodyList.getMainBodyGroup();
203 MainBodyGroup mainBodyGroup = new MainBodyGroup();
204 mainBodyGroup.setShortName("Test Organization-" + shortId);
205 mainBodyGroup.setLongName("Test Organization Name");
206 mainBodyGroups.add(mainBodyGroup);
208 // Finishing creating the new Organization item, then
209 // submit the request to the service and store the response.
210 knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
211 knownResourceId, knownResourceRefName, testOrgMap,
212 testOrgRepeatablesMap, mainBodyList, orgAuthClient);
214 // Store the IDs from every item created by tests,
215 // so they can be deleted after tests have been run.
216 allResourceItemIdsCreated.put(knownItemResourceId, knownResourceId);
220 * Creates the person refs.
222 protected void createPersonRefs() {
223 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
224 // Create a temporary PersonAuthority resource, and its corresponding
225 // refName by which it can be identified.
226 PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
227 PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
229 ClientResponse<Response> res = personAuthClient.create(multipart);
231 int statusCode = res.getStatus();
232 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
233 invalidStatusCodeMessage(testRequestType, statusCode));
234 Assert.assertEquals(statusCode, STATUS_CREATED);
235 personAuthCSID = extractId(res);
237 res.releaseConnection();
240 //String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
242 // Create temporary Person resources, and their corresponding refNames
243 // by which they can be identified.
244 String csid = createPerson("Charlie", "Orgcontact", "charlieOrgcontact", null ); // authRefName);
245 personIdsCreated.add(csid);
246 organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
248 // Create temporary Person resources, and their corresponding refNames
249 // by which they can be identified.
250 csid = createPerson("Chelsie", "Contact", "chelsieContact", null ); // authRefName);
251 personIdsCreated.add(csid);
252 organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
256 * Creates the person.
258 * @param firstName the first name
259 * @param surName the sur name
264 protected String createPerson(String firstName, String surName, String shortId, String authRefName ) {
265 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
266 Map<String, String> personInfo = new HashMap<String,String>();
267 personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
268 personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
269 personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
270 List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
271 PersonTermGroup term = new PersonTermGroup();
272 String termName = firstName + " " + surName;
273 term.setTermDisplayName(termName);
274 term.setTermName(termName);
275 personTerms.add(term);
276 PoxPayloadOut multipart =
277 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
278 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
280 String result = null;
281 ClientResponse<Response> res = personAuthClient.createItem(personAuthCSID, multipart);
283 int statusCode = res.getStatus();
285 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
286 invalidStatusCodeMessage(testRequestType, statusCode));
287 Assert.assertEquals(statusCode, STATUS_CREATED);
288 result = extractId(res);
290 res.releaseConnection();
298 * Read and check auth refs.
300 * @param testName the test name
301 * @throws Exception the exception
303 @Test(dataProvider="testName",
304 dependsOnMethods = {"createWithAuthRefs"})
305 public void readAndCheckAuthRefs(String testName) throws Exception {
307 testSetup(STATUS_OK, ServiceRequestType.READ);
309 // Submit the request to the service and store the response.
310 OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
311 ClientResponse<String> res = orgAuthClient.readItem(knownResourceId, knownItemResourceId);
312 OrganizationsCommon organization = null;
314 assertStatusCode(res, testName);
315 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
316 organization = (OrganizationsCommon) extractPart(input,
317 orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
318 Assert.assertNotNull(organization);
319 if (logger.isDebugEnabled()){
320 logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
324 res.releaseConnection();
327 // Check one or more of the authority fields in the Organization item
328 Assert.assertEquals(organization.getContactNames().getContactName().get(0),
329 organizationContactPersonRefName1);
330 Assert.assertEquals(organization.getContactNames().getContactName().get(1),
331 organizationContactPersonRefName2);
334 // Get the auth refs and check them
335 // FIXME - need to create this method in the client
336 // and get the ID for the organization item
337 ClientResponse<AuthorityRefList> res2 =
338 orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
339 AuthorityRefList list = null;
341 assertStatusCode(res2, testName);
342 list = res2.getEntity();
345 res2.releaseConnection();
349 List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
350 int numAuthRefsFound = items.size();
351 if(logger.isDebugEnabled()){
352 logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
353 " authority references, found " + numAuthRefsFound);
355 Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
356 "Did not find all expected authority references! " +
357 "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
359 // Optionally output additional data about list members for debugging.
360 boolean iterateThroughList = true;
361 if(iterateThroughList && logger.isDebugEnabled()){
363 for(AuthorityRefList.AuthorityRefItem item : items){
364 logger.debug(testName + ": list-item[" + i + "] Field:" +
365 item.getSourceField() + "=" +
366 item.getItemDisplayName());
367 logger.debug(testName + ": list-item[" + i + "] refName=" +
369 logger.debug(testName + ": list-item[" + i + "] URI=" +
376 // ---------------------------------------------------------------
377 // Cleanup of resources created during testing
378 // ---------------------------------------------------------------
381 * Deletes all resources created by tests, after all tests have been run.
383 * This cleanup method will always be run, even if one or more tests fail.
384 * For this reason, it attempts to remove all resources created
385 * at any point during testing, even if some of those resources
386 * may be expected to be deleted by certain tests.
388 @AfterClass(alwaysRun=true)
389 public void cleanUp() {
390 String noTest = System.getProperty("noTestCleanup");
391 if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
392 if (logger.isDebugEnabled()) {
393 logger.debug("Skipping Cleanup phase ...");
397 if (logger.isDebugEnabled()) {
398 logger.debug("Cleaning up temporary resources created for testing ...");
400 PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
401 // Delete Person resource(s) (before PersonAuthority resources).
402 for (String resourceId : personIdsCreated) {
403 // Note: Any non-success responses are ignored and not reported.
404 personAuthClient.deleteItem(personAuthCSID, resourceId).releaseConnection();
406 // Delete PersonAuthority resource(s).
407 // Note: Any non-success response is ignored and not reported.
408 if(personAuthCSID!=null) {
409 personAuthClient.delete(personAuthCSID).releaseConnection();
412 String parentResourceId;
413 String itemResourceId;
414 OrgAuthorityClient client = new OrgAuthorityClient();
415 // Clean up item resources.
416 for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
417 itemResourceId = entry.getKey();
418 parentResourceId = entry.getValue();
419 // Note: Any non-success responses from the delete operation
420 // below are ignored and not reported.
421 client.deleteItem(parentResourceId, itemResourceId).releaseConnection();
424 // Clean up parent resources.
425 for (String resourceId : allResourceIdsCreated) {
426 // Note: Any non-success responses from the delete operation
427 // below are ignored and not reported.
428 client.delete(resourceId).releaseConnection();