]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
36d395fc317cddfe250e30afaec6cd5eb5983d38
[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.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.OrganizationsCommon;
44 import org.collectionspace.services.organization.OrgTermGroup;
45 import org.collectionspace.services.person.PersonTermGroup;
46
47 import org.jboss.resteasy.client.ClientResponse;
48
49 import org.testng.Assert;
50 import org.testng.annotations.AfterClass;
51 import org.testng.annotations.Test;
52
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * LoaninAuthRefsTest, carries out Authority References tests against a
58  * deployed and running Loanin (aka Loans In) Service.
59  *
60  * $LastChangedRevision$
61  * $LastChangedDate$
62  */
63 public class OrgAuthorityAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
64
65    /** The logger. */
66     private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
67     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
68
69     // Instance variables specific to this test.
70     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
71     final String ORG_AUTHORITY_NAME = "TestOrgAuth";
72     
73         @Override
74         public String getServicePathComponent() {
75                 return OrgAuthorityClient.SERVICE_PATH_COMPONENT;
76         }
77
78         @Override
79         protected String getServiceName() {
80                 return OrgAuthorityClient.SERVICE_NAME;
81         }
82
83     protected String knownItemResourceId = null;
84         
85     private String knownResourceRefName = null;
86             
87     /** The person ids created. */
88     private List<String> personIdsCreated = new ArrayList<String>();
89     
90     // CSID for the instance of the test Person authority
91     // created during testing.
92     private String personAuthCSID = null;
93     
94     /** The organization contact person refNames. */
95     private String organizationContactPersonRefName1 = null;
96     private String organizationContactPersonRefName2 = null;
97
98     // The refName of an Organization item that represents
99     // the sub-body organization of a second Organization item.
100     private String subBodyRefName = null;
101     
102     /** The number of authorityreferences expected. */
103     private final int NUM_AUTH_REFS_EXPECTED = 2;       // Place authRef not legal, should not be returned.
104
105     protected void setKnownResource( String id, String refName ) {
106         knownResourceId = id;
107         knownResourceRefName = refName;
108     }
109
110     /* (non-Javadoc)
111      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
112      */
113     @Override
114     protected CollectionSpaceClient getClientInstance() {
115         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
116     }
117     
118     /* (non-Javadoc)
119      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
120      */
121     @Override
122         protected AbstractCommonList getCommonList(
123                         ClientResponse<AbstractCommonList> response) {
124         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
125     }
126
127     // ---------------------------------------------------------------
128     // CRUD tests : CREATE tests
129     // ---------------------------------------------------------------
130     // Success outcomes
131     /**
132      * Creates the with auth refs.
133      *
134      * @param testName the test name
135      * @throws Exception the exception
136      */
137     @Test(dataProvider="testName")
138     public void createWithAuthRefs(String testName) throws Exception {
139         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
140
141         // Create a new Organization Authority resource.
142         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
143         String shortId = createIdentifier();
144         String displayName = "TestOrgAuth-" + shortId;
145         //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
146         PoxPayloadOut multipart =
147             OrgAuthorityClientUtils.createOrgAuthorityInstance(
148                                 displayName, shortId, orgAuthClient.getCommonPartName());
149
150         // Submit the request to the service and store the response.
151         Response res = orgAuthClient.create(multipart);
152         try {
153                 int statusCode = res.getStatus();
154                 // Check the status code of the response: does it match
155                 // the expected response(s)?
156                 //
157                 // Specifically:
158                 // Does it fall within the set of valid status codes?
159                 // Does it exactly match the expected status code?
160                 if(logger.isDebugEnabled()){
161                     logger.debug(testName + ": status = " + statusCode);
162                 }
163                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
164                     invalidStatusCodeMessage(testRequestType, statusCode));
165                 Assert.assertEquals(statusCode, testExpectedStatusCode);
166         
167                 // Store the IDs from every resource created by tests,
168                 // so they can be deleted after tests have been run.
169                 String newId = extractId(res);
170                 if (knownResourceId == null){
171                         setKnownResource(newId, null ); //baseRefName );
172                 }
173                 allResourceIdsCreated.add(newId);
174         } finally {
175             res.close();
176         }        
177
178         // Create all the person refs and entities
179         createPersonRefs();
180
181         // Initialize values for a new Organization item, to be created within
182         // the newly-created Organization Authority resource.
183         //
184         // One or more fields in the Organization item record will
185         // contain references to Persons, via their refNames, as
186         // per the initialization(s) below.
187         Map<String, String> testOrgMap = new HashMap<String,String>();
188         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
189         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
190
191         Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
192         List<String> testOrgContactNames = new ArrayList<String>();
193         testOrgContactNames.add(organizationContactPersonRefName1);
194         testOrgContactNames.add(organizationContactPersonRefName2);
195         testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
196         
197         List<OrgTermGroup> terms = OrgAuthorityClientUtils.getTermGroupInstance("Org name");
198
199         // Finishing creating the new Organization item, then
200         // submit the request to the service and store the response.
201         knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
202                         knownResourceId, knownResourceRefName, testOrgMap,
203                         terms, testOrgRepeatablesMap, orgAuthClient);
204
205         // Store the IDs from every item created by tests,
206         // so they can be deleted after tests have been run.
207         allResourceItemIdsCreated.put(knownItemResourceId, knownResourceId);
208     }
209     
210     /**
211      * Creates the person refs.
212      */
213     protected void createPersonRefs() {
214         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
215         // Create a temporary PersonAuthority resource, and its corresponding
216         // refName by which it can be identified.
217         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
218             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
219         
220         Response res = personAuthClient.create(multipart);
221         try {
222             int statusCode = res.getStatus();
223             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
224                 invalidStatusCodeMessage(testRequestType, statusCode));
225             Assert.assertEquals(statusCode, STATUS_CREATED);
226             personAuthCSID = extractId(res);
227         } finally {
228             res.close();
229         }
230
231         //String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
232         
233         // Create temporary Person resources, and their corresponding refNames
234         // by which they can be identified.
235         String csid = createPerson(personAuthCSID, "Charlie", "Orgcontact", "charlieOrgcontact", null ); // authRefName);
236         personIdsCreated.add(csid);
237         organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
238
239         // Create temporary Person resources, and their corresponding refNames
240         // by which they can be identified.
241         csid = createPerson(personAuthCSID, "Chelsie", "Contact", "chelsieContact", null ); // authRefName);
242         personIdsCreated.add(csid);
243         organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
244     }
245     
246     /**
247      * Creates the person.
248      *
249      * @param firstName the first name
250      * @param surName the sur name
251      * @param shortId
252      * @param authRefName
253      * @return the string
254      */
255     protected String createPerson(String personAuthCSID, String firstName, String surName, String shortId, String authRefName ) {
256         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
257         Map<String, String> personInfo = new HashMap<String,String>();
258         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
259         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
260         PersonTermGroup term = new PersonTermGroup();
261         String termName = firstName + " " + surName;
262         term.setTermDisplayName(termName);
263         term.setTermName(termName);
264         term.setForeName(firstName);
265         term.setSurName(surName);
266         personTerms.add(term);
267         PoxPayloadOut multipart = 
268             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
269                         null, personInfo, personTerms, personAuthClient.getItemCommonPartName());
270         
271         String result = null;
272         Response res = personAuthClient.createItem(personAuthCSID, multipart);
273         try {
274                 int statusCode = res.getStatus();
275         
276                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
277                         invalidStatusCodeMessage(testRequestType, statusCode));
278                 Assert.assertEquals(statusCode, STATUS_CREATED);
279                 result = extractId(res);
280         } finally {
281                 res.close();
282         }
283         
284         return result;
285     }
286
287     // Success outcomes
288     /**
289      * Read and check auth refs.
290      *
291      * @param testName the test name
292      * @throws Exception the exception
293      */
294     @Test(dataProvider="testName",
295         dependsOnMethods = {"createWithAuthRefs"})
296     public void readAndCheckAuthRefs(String testName) throws Exception {
297         // Perform setup.
298         testSetup(STATUS_OK, ServiceRequestType.READ);
299
300         // Submit the request to the service and store the response.
301         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
302         ClientResponse<String> res = orgAuthClient.readItem(knownResourceId, knownItemResourceId);
303         OrganizationsCommon organization = null;
304         try {
305                 assertStatusCode(res, testName);
306                 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
307                 organization = (OrganizationsCommon) extractPart(input,
308                     orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
309                 Assert.assertNotNull(organization);
310                 if (logger.isDebugEnabled()){
311                     logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
312                 }
313         } finally {
314                 if (res != null) {
315                 res.releaseConnection();
316             }
317         }
318         // Check one or more of the authority fields in the Organization item
319         Assert.assertEquals(organization.getContactNames().getContactName().get(0),
320                 organizationContactPersonRefName1);
321         Assert.assertEquals(organization.getContactNames().getContactName().get(1),
322                 organizationContactPersonRefName2);
323
324
325         // Get the auth refs and check them
326         // FIXME - need to create this method in the client
327         // and get the ID for the organization item
328         ClientResponse<AuthorityRefList> res2 =
329            orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
330         AuthorityRefList list = null;
331         try {
332                 assertStatusCode(res2, testName);
333                 list = res2.getEntity();
334         } finally {
335                 if (res2 != null) {
336                         res2.releaseConnection();
337             }
338         }
339         
340         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
341         int numAuthRefsFound = items.size();
342         if(logger.isDebugEnabled()){
343             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
344                 " authority references, found " + numAuthRefsFound);
345         }
346         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
347             "Did not find all expected authority references! " +
348             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
349
350         // Optionally output additional data about list members for debugging.
351         boolean iterateThroughList = true;
352         if(iterateThroughList && logger.isDebugEnabled()){
353             int i = 0;
354             for(AuthorityRefList.AuthorityRefItem item : items){
355                 logger.debug(testName + ": list-item[" + i + "] Field:" +
356                     item.getSourceField() + "=" +
357                     item.getItemDisplayName());
358                 logger.debug(testName + ": list-item[" + i + "] refName=" +
359                     item.getRefName());
360                 logger.debug(testName + ": list-item[" + i + "] URI=" +
361                     item.getUri());
362                 i++;
363             }
364         }
365     }
366
367     // ---------------------------------------------------------------
368     // Cleanup of resources created during testing
369     // ---------------------------------------------------------------
370
371     /**
372      * Deletes all resources created by tests, after all tests have been run.
373      *
374      * This cleanup method will always be run, even if one or more tests fail.
375      * For this reason, it attempts to remove all resources created
376      * at any point during testing, even if some of those resources
377      * may be expected to be deleted by certain tests.
378      */
379     @AfterClass(alwaysRun=true)
380     public void cleanUp() {
381         String noTest = System.getProperty("noTestCleanup");
382         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
383             if (logger.isDebugEnabled()) {
384                 logger.debug("Skipping Cleanup phase ...");
385             }
386             return;
387         }
388         if (logger.isDebugEnabled()) {
389             logger.debug("Cleaning up temporary resources created for testing ...");
390         }
391         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
392         // Delete Person resource(s) (before PersonAuthority resources).
393         for (String resourceId : personIdsCreated) {
394             // Note: Any non-success responses are ignored and not reported.
395             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
396         }
397         // Delete PersonAuthority resource(s).
398         // Note: Any non-success response is ignored and not reported.
399         if(personAuthCSID!=null) {
400                 personAuthClient.delete(personAuthCSID).close();
401         }
402         
403         String parentResourceId;
404         String itemResourceId;
405         OrgAuthorityClient client = new OrgAuthorityClient();
406         // Clean up item resources.
407         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
408             itemResourceId = entry.getKey();
409             parentResourceId = entry.getValue();
410             // Note: Any non-success responses from the delete operation
411             // below are ignored and not reported.
412             client.deleteItem(parentResourceId, itemResourceId).close();
413         }
414         
415         // Clean up parent resources.
416         for (String resourceId : allResourceIdsCreated) {
417             // Note: Any non-success responses from the delete operation
418             // below are ignored and not reported.
419             client.delete(resourceId).close();
420         }
421     }
422 }