]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
db57d8aa7dbb9315dcaa3b57f4bba9b0550d8520
[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(Response response) {
123         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
124     }
125
126     // ---------------------------------------------------------------
127     // CRUD tests : CREATE tests
128     // ---------------------------------------------------------------
129     // Success outcomes
130     /**
131      * Creates the with auth refs.
132      *
133      * @param testName the test name
134      * @throws Exception the exception
135      */
136     @Test(dataProvider="testName")
137     public void createWithAuthRefs(String testName) throws Exception {
138         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
139
140         // Create a new Organization Authority resource.
141         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
142         String shortId = createIdentifier();
143         String displayName = "TestOrgAuth-" + shortId;
144         //String baseRefName = OrgAuthorityClientUtils.createOrgAuthRefName(shortId, null);
145         PoxPayloadOut multipart =
146             OrgAuthorityClientUtils.createOrgAuthorityInstance(
147                                 displayName, shortId, orgAuthClient.getCommonPartName());
148
149         // Submit the request to the service and store the response.
150         Response res = orgAuthClient.create(multipart);
151         try {
152                 int statusCode = res.getStatus();
153                 // Check the status code of the response: does it match
154                 // the expected response(s)?
155                 //
156                 // Specifically:
157                 // Does it fall within the set of valid status codes?
158                 // Does it exactly match the expected status code?
159                 if(logger.isDebugEnabled()){
160                     logger.debug(testName + ": status = " + statusCode);
161                 }
162                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
163                     invalidStatusCodeMessage(testRequestType, statusCode));
164                 Assert.assertEquals(statusCode, testExpectedStatusCode);
165         
166                 // Store the IDs from every resource created by tests,
167                 // so they can be deleted after tests have been run.
168                 String newId = extractId(res);
169                 if (knownResourceId == null){
170                         setKnownResource(newId, null ); //baseRefName );
171                 }
172                 allResourceIdsCreated.add(newId);
173         } finally {
174             res.close();
175         }        
176
177         // Create all the person refs and entities
178         createPersonRefs();
179
180         // Initialize values for a new Organization item, to be created within
181         // the newly-created Organization Authority resource.
182         //
183         // One or more fields in the Organization item record will
184         // contain references to Persons, via their refNames, as
185         // per the initialization(s) below.
186         Map<String, String> testOrgMap = new HashMap<String,String>();
187         testOrgMap.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
188         testOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Anytown, USA");
189
190         Map<String, List<String>> testOrgRepeatablesMap = new HashMap<String,List<String>>();
191         List<String> testOrgContactNames = new ArrayList<String>();
192         testOrgContactNames.add(organizationContactPersonRefName1);
193         testOrgContactNames.add(organizationContactPersonRefName2);
194         testOrgRepeatablesMap.put(OrganizationJAXBSchema.CONTACT_NAMES, testOrgContactNames);
195         
196         List<OrgTermGroup> terms = OrgAuthorityClientUtils.getTermGroupInstance("Org name");
197
198         // Finishing creating the new Organization item, then
199         // submit the request to the service and store the response.
200         knownItemResourceId = OrgAuthorityClientUtils.createItemInAuthority(
201                         knownResourceId, knownResourceRefName, testOrgMap,
202                         terms, testOrgRepeatablesMap, orgAuthClient);
203
204         // Store the IDs from every item created by tests,
205         // so they can be deleted after tests have been run.
206         allResourceItemIdsCreated.put(knownItemResourceId, knownResourceId);
207     }
208     
209     /**
210      * Creates the person refs.
211      */
212     protected void createPersonRefs() {
213         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
214         // Create a temporary PersonAuthority resource, and its corresponding
215         // refName by which it can be identified.
216         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
217             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
218         
219         Response res = personAuthClient.create(multipart);
220         try {
221             int statusCode = res.getStatus();
222             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
223                 invalidStatusCodeMessage(testRequestType, statusCode));
224             Assert.assertEquals(statusCode, STATUS_CREATED);
225             personAuthCSID = extractId(res);
226         } finally {
227             res.close();
228         }
229
230         //String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, null);
231         
232         // Create temporary Person resources, and their corresponding refNames
233         // by which they can be identified.
234         String csid = createPerson(personAuthCSID, "Charlie", "Orgcontact", "charlieOrgcontact", null ); // authRefName);
235         personIdsCreated.add(csid);
236         organizationContactPersonRefName1 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
237
238         // Create temporary Person resources, and their corresponding refNames
239         // by which they can be identified.
240         csid = createPerson(personAuthCSID, "Chelsie", "Contact", "chelsieContact", null ); // authRefName);
241         personIdsCreated.add(csid);
242         organizationContactPersonRefName2 = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, null);
243     }
244     
245     /**
246      * Creates the person.
247      *
248      * @param firstName the first name
249      * @param surName the sur name
250      * @param shortId
251      * @param authRefName
252      * @return the string
253      */
254     protected String createPerson(String personAuthCSID, String firstName, String surName, String shortId, String authRefName ) {
255         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
256         Map<String, String> personInfo = new HashMap<String,String>();
257         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
258         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
259         PersonTermGroup term = new PersonTermGroup();
260         String termName = firstName + " " + surName;
261         term.setTermDisplayName(termName);
262         term.setTermName(termName);
263         term.setForeName(firstName);
264         term.setSurName(surName);
265         personTerms.add(term);
266         PoxPayloadOut multipart = 
267             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
268                         null, personInfo, personTerms, personAuthClient.getItemCommonPartName());
269         
270         String result = null;
271         Response res = personAuthClient.createItem(personAuthCSID, multipart);
272         try {
273                 int statusCode = res.getStatus();
274         
275                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
276                         invalidStatusCodeMessage(testRequestType, statusCode));
277                 Assert.assertEquals(statusCode, STATUS_CREATED);
278                 result = extractId(res);
279         } finally {
280                 res.close();
281         }
282         
283         return result;
284     }
285
286     // Success outcomes
287     /**
288      * Read and check auth refs.
289      *
290      * @param testName the test name
291      * @throws Exception the exception
292      */
293     @Test(dataProvider="testName",
294         dependsOnMethods = {"createWithAuthRefs"})
295     public void readAndCheckAuthRefs(String testName) throws Exception {
296         // Perform setup.
297         testSetup(STATUS_OK, ServiceRequestType.READ);
298
299         // Submit the request to the service and store the response.
300         OrgAuthorityClient orgAuthClient = new OrgAuthorityClient();
301         Response res = orgAuthClient.readItem(knownResourceId, knownItemResourceId);
302         OrganizationsCommon organization = null;
303         try {
304                 assertStatusCode(res, testName);
305                 PoxPayloadIn input = new PoxPayloadIn((String)res.getEntity());
306                 organization = (OrganizationsCommon) extractPart(input,
307                     orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
308                 Assert.assertNotNull(organization);
309                 if (logger.isDebugEnabled()){
310                     logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
311                 }
312         } finally {
313                 if (res != null) {
314                 res.close();
315             }
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         Response res2 = orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
329         AuthorityRefList list = null;
330         try {
331                 assertStatusCode(res2, testName);
332                 list = res2.readEntity(AuthorityRefList.class);
333         } finally {
334                 if (res2 != null) {
335                         res2.close();
336             }
337         }
338         
339         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
340         int numAuthRefsFound = items.size();
341         if(logger.isDebugEnabled()){
342             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
343                 " authority references, found " + numAuthRefsFound);
344         }
345         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
346             "Did not find all expected authority references! " +
347             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
348
349         // Optionally output additional data about list members for debugging.
350         boolean iterateThroughList = true;
351         if(iterateThroughList && logger.isDebugEnabled()){
352             int i = 0;
353             for(AuthorityRefList.AuthorityRefItem item : items){
354                 logger.debug(testName + ": list-item[" + i + "] Field:" +
355                     item.getSourceField() + "=" +
356                     item.getItemDisplayName());
357                 logger.debug(testName + ": list-item[" + i + "] refName=" +
358                     item.getRefName());
359                 logger.debug(testName + ": list-item[" + i + "] URI=" +
360                     item.getUri());
361                 i++;
362             }
363         }
364     }
365
366     // ---------------------------------------------------------------
367     // Cleanup of resources created during testing
368     // ---------------------------------------------------------------
369
370     /**
371      * Deletes all resources created by tests, after all tests have been run.
372      *
373      * This cleanup method will always be run, even if one or more tests fail.
374      * For this reason, it attempts to remove all resources created
375      * at any point during testing, even if some of those resources
376      * may be expected to be deleted by certain tests.
377      */
378     @AfterClass(alwaysRun=true)
379     public void cleanUp() {
380         String noTest = System.getProperty("noTestCleanup");
381         if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
382             if (logger.isDebugEnabled()) {
383                 logger.debug("Skipping Cleanup phase ...");
384             }
385             return;
386         }
387         if (logger.isDebugEnabled()) {
388             logger.debug("Cleaning up temporary resources created for testing ...");
389         }
390         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
391         // Delete Person resource(s) (before PersonAuthority resources).
392         for (String resourceId : personIdsCreated) {
393             // Note: Any non-success responses are ignored and not reported.
394             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
395         }
396         // Delete PersonAuthority resource(s).
397         // Note: Any non-success response is ignored and not reported.
398         if(personAuthCSID!=null) {
399                 personAuthClient.delete(personAuthCSID).close();
400         }
401         
402         String parentResourceId;
403         String itemResourceId;
404         OrgAuthorityClient client = new OrgAuthorityClient();
405         // Clean up item resources.
406         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
407             itemResourceId = entry.getKey();
408             parentResourceId = entry.getValue();
409             // Note: Any non-success responses from the delete operation
410             // below are ignored and not reported.
411             client.deleteItem(parentResourceId, itemResourceId).close();
412         }
413         
414         // Clean up parent resources.
415         for (String resourceId : allResourceIdsCreated) {
416             // Note: Any non-success responses from the delete operation
417             // below are ignored and not reported.
418             client.delete(resourceId).close();
419         }
420     }
421 }