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