]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7d7904257caa99c6c29b80b0f26bd3c14f56b7b9
[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.OrganizationClient;
36 import org.collectionspace.services.client.OrgAuthorityClientUtils;
37 import org.collectionspace.services.client.PersonClient;
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 import org.testng.Assert;
47 import org.testng.annotations.AfterClass;
48 import org.testng.annotations.Test;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * LoaninAuthRefsTest, carries out Authority References tests against a
54  * deployed and running Loanin (aka Loans In) Service.
55  *
56  * $LastChangedRevision$
57  * $LastChangedDate$
58  */
59 public class OrgAuthorityAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
60
61    /** The logger. */
62     private final String CLASS_NAME = OrgAuthorityAuthRefsTest.class.getName();
63     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
64
65     // Instance variables specific to this test.
66     final String PERSON_AUTHORITY_NAME = "TestPersonAuthForOrgTest";
67     final String ORG_AUTHORITY_NAME = "TestOrgAuth";
68     
69         @Override
70         public String getServicePathComponent() {
71                 return OrganizationClient.SERVICE_PATH_COMPONENT;
72         }
73
74         @Override
75         protected String getServiceName() {
76                 return OrganizationClient.SERVICE_NAME;
77         }
78
79     protected String knownItemResourceId = null;
80         
81     private String knownResourceRefName = null;
82             
83     /** The person ids created. */
84     private List<String> personIdsCreated = new ArrayList<String>();
85     
86     // CSID for the instance of the test Person authority
87     // created during testing.
88     private String personAuthCSID = null;
89     
90     /** The organization contact person refNames. */
91     private String organizationContactPersonRefName1 = null;
92     private String organizationContactPersonRefName2 = null;
93
94     // The refName of an Organization item that represents
95     // the sub-body organization of a second Organization item.
96     private String subBodyRefName = null;
97     
98     /** The number of authorityreferences expected. */
99     private final int NUM_AUTH_REFS_EXPECTED = 2;       // Place authRef not legal, should not be returned.
100
101     protected void setKnownResource( String id, String refName ) {
102         knownResourceId = id;
103         knownResourceRefName = refName;
104     }
105
106     /* (non-Javadoc)
107      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
108      */
109     @Override
110     protected CollectionSpaceClient getClientInstance() {
111         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
112     }
113     
114         @Override
115         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
116         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
117         }
118
119         /* (non-Javadoc)
120      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
121      */
122     @Override
123         protected AbstractCommonList getCommonList(Response 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         OrganizationClient orgAuthClient = new OrganizationClient();
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      * @throws Exception 
213      */
214     protected void createPersonRefs() throws Exception {
215         PersonClient personAuthClient = new PersonClient();
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      * @throws Exception 
256      */
257     protected String createPerson(String personAuthCSID, String firstName, String surName, String shortId, String authRefName ) throws Exception {
258         PersonClient personAuthClient = new PersonClient();
259         Map<String, String> personInfo = new HashMap<String,String>();
260         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
261         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
262         PersonTermGroup term = new PersonTermGroup();
263         String termName = firstName + " " + surName;
264         term.setTermDisplayName(termName);
265         term.setTermName(termName);
266         term.setForeName(firstName);
267         term.setSurName(surName);
268         personTerms.add(term);
269         PoxPayloadOut multipart = 
270             PersonAuthorityClientUtils.createPersonInstance(personAuthCSID,
271                         null, personInfo, personTerms, personAuthClient.getItemCommonPartName());
272         
273         String result = null;
274         Response res = personAuthClient.createItem(personAuthCSID, multipart);
275         try {
276                 int statusCode = res.getStatus();
277         
278                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
279                         invalidStatusCodeMessage(testRequestType, statusCode));
280                 Assert.assertEquals(statusCode, STATUS_CREATED);
281                 result = extractId(res);
282         } finally {
283                 res.close();
284         }
285         
286         return result;
287     }
288
289     // Success outcomes
290     /**
291      * Read and check auth refs.
292      *
293      * @param testName the test name
294      * @throws Exception the exception
295      */
296     @Test(dataProvider="testName",
297         dependsOnMethods = {"createWithAuthRefs"})
298     public void readAndCheckAuthRefs(String testName) throws Exception {
299         // Perform setup.
300         testSetup(STATUS_OK, ServiceRequestType.READ);
301
302         // Submit the request to the service and store the response.
303         OrganizationClient orgAuthClient = new OrganizationClient();
304         Response res = orgAuthClient.readItem(knownResourceId, knownItemResourceId);
305         OrganizationsCommon organization = null;
306         try {
307                 assertStatusCode(res, testName);
308                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
309                 organization = (OrganizationsCommon) extractPart(input,
310                     orgAuthClient.getItemCommonPartName(), OrganizationsCommon.class);
311                 Assert.assertNotNull(organization);
312                 if (logger.isDebugEnabled()){
313                     logger.debug(objectAsXmlString(organization, OrganizationsCommon.class));
314                 }
315         } finally {
316                 if (res != null) {
317                 res.close();
318             }
319         }
320         
321         // Check one or more of the authority fields in the Organization item
322         Assert.assertEquals(organization.getContactNames().getContactName().get(0),
323                 organizationContactPersonRefName1);
324         Assert.assertEquals(organization.getContactNames().getContactName().get(1),
325                 organizationContactPersonRefName2);
326
327
328         // Get the auth refs and check them
329         // FIXME - need to create this method in the client
330         // and get the ID for the organization item
331         Response res2 = orgAuthClient.getItemAuthorityRefs(knownResourceId, knownItemResourceId);
332         AuthorityRefList list = null;
333         try {
334                 assertStatusCode(res2, testName);
335                 list = res2.readEntity(AuthorityRefList.class);
336         } finally {
337                 if (res2 != null) {
338                         res2.close();
339             }
340         }
341         
342         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
343         int numAuthRefsFound = items.size();
344         if(logger.isDebugEnabled()){
345             logger.debug("Expected " + NUM_AUTH_REFS_EXPECTED +
346                 " authority references, found " + numAuthRefsFound);
347         }
348         Assert.assertEquals(numAuthRefsFound, NUM_AUTH_REFS_EXPECTED,
349             "Did not find all expected authority references! " +
350             "Expected " + NUM_AUTH_REFS_EXPECTED + ", found " + numAuthRefsFound);
351
352         // Optionally output additional data about list members for debugging.
353         boolean iterateThroughList = true;
354         if(iterateThroughList && logger.isDebugEnabled()){
355             int i = 0;
356             for(AuthorityRefList.AuthorityRefItem item : items){
357                 logger.debug(testName + ": list-item[" + i + "] Field:" +
358                     item.getSourceField() + "=" +
359                     item.getItemDisplayName());
360                 logger.debug(testName + ": list-item[" + i + "] refName=" +
361                     item.getRefName());
362                 logger.debug(testName + ": list-item[" + i + "] URI=" +
363                     item.getUri());
364                 i++;
365             }
366         }
367     }
368
369     // ---------------------------------------------------------------
370     // Cleanup of resources created during testing
371     // ---------------------------------------------------------------
372
373     /**
374      * Deletes all resources created by tests, after all tests have been run.
375      *
376      * This cleanup method will always be run, even if one or more tests fail.
377      * For this reason, it attempts to remove all resources created
378      * at any point during testing, even if some of those resources
379      * may be expected to be deleted by certain tests.
380      * @throws Exception 
381      */
382     @AfterClass(alwaysRun=true)
383     public void cleanUp() throws Exception {
384         String noTest = System.getProperty("noTestCleanup");
385         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
386             if (logger.isDebugEnabled()) {
387                 logger.debug("Skipping Cleanup phase ...");
388             }
389             return;
390         }
391         
392         if (logger.isDebugEnabled()) {
393             logger.debug("Cleaning up temporary resources created for testing ...");
394         }
395                 
396         String parentResourceId;
397         String itemResourceId;
398         OrganizationClient client = new OrganizationClient();
399         // Clean up item resources.
400         for (Map.Entry<String, String> entry : allResourceItemIdsCreated.entrySet()) {
401             itemResourceId = entry.getKey();
402             parentResourceId = entry.getValue();
403             // Note: Any non-success responses from the delete operation
404             // below are ignored and not reported.
405             client.deleteItem(parentResourceId, itemResourceId).close();
406         }
407         
408         //
409         // Delete the person authority items we created for the authRefs.  Note
410         // that we needed to delete the objects/records referencing these authority items first since
411         // we can't delete authority items that still have records referencing them
412         //
413         PersonClient personAuthClient = new PersonClient();
414         // Delete Person resource(s) (before PersonAuthority resources).
415         for (String resourceId : personIdsCreated) {
416             // Note: Any non-success responses are ignored and not reported.
417             personAuthClient.deleteItem(personAuthCSID, resourceId).close();
418         }
419         
420         // Delete PersonAuthority resource(s).
421         // Note: Any non-success response is ignored and not reported.
422         if (personAuthCSID != null) {
423                 personAuthClient.delete(personAuthCSID).close();
424         }        
425         
426         // Clean up parent resources.
427         for (String resourceId : allResourceIdsCreated) {
428             // Note: Any non-success responses from the delete operation
429             // below are ignored and not reported.
430             client.delete(resourceId).close();
431         }
432     }
433 }