]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
5b361412bf784af1e5367ab59733980d834cfb96
[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 import javax.ws.rs.core.Response;
30
31 import org.collectionspace.services.OrganizationJAXBSchema;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.HeldintrustClient;
34 import org.collectionspace.services.client.OrgAuthorityClientUtils;
35 import org.collectionspace.services.client.OrganizationClient;
36 import org.collectionspace.services.client.PoxPayloadOut;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.heldintrust.HeldintrustsCommon;
39 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.collectionspace.services.organization.OrgTermGroup;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.testng.Assert;
44 import org.testng.annotations.AfterClass;
45 import org.testng.annotations.Test;
46
47 /**
48  * OrganizationAuthRefDocsTest, carries out tests against a
49  * deployed and running Organization Service.
50  *
51  * $LastChangedRevision: 1327 $
52  * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $
53  */
54 public class OrganizationAuthRefDocsTest extends BaseServiceTest<AbstractCommonList> {
55
56     private static final Logger logger = LoggerFactory.getLogger(OrganizationAuthRefDocsTest.class);
57     // Instance variables specific to this test.
58     final String SERVICE_PATH_COMPONENT = "hits";
59     final String ORGANIZATION_AUTHORITY_NAME = "TestOrganizationAuth";
60     private String knownHitId = null;
61     private final List<String> hitIdsCreated = new ArrayList<String>();
62     private final List<String> orgIdsCreated = new ArrayList<String>();
63     private String orgAuthCSID = null;
64     private String currentContactOrgCSID = null;
65     private String depositorContactRefName = null;
66     private String depositorRefName = null;
67     private String externalApprovalIndividualRefName = null;
68     private String correspondenceSenderRefName = null;
69     private String valuerRefName = null;
70
71     @Override
72     protected String getServiceName() {
73         throw new UnsupportedOperationException(); //FIXME: REM - See http://issues.collectionspace.org/browse/CSPACE-3498
74     }
75
76     /* (non-Javadoc)
77      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
78      */
79     @Override
80     protected CollectionSpaceClient getClientInstance() {
81         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
82     }
83
84     @Override
85     protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
86         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
87     }
88
89     /* (non-Javadoc)
90      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client
91      * .ClientResponse)
92      */
93     @Override
94     protected AbstractCommonList getCommonList(Response response) {
95         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
96     }
97
98     // ---------------------------------------------------------------
99     // CRUD tests : CREATE tests
100     // ---------------------------------------------------------------
101     // Success outcomes
102     @Test(dataProvider = "testName", dataProviderClass = BaseServiceTest.class)
103     public void createHitWithAuthRefs(String testName) throws Exception {
104         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
105
106         // Submit the request to the service and store the response.
107         String identifier = createIdentifier();
108
109         // Create all the organization refs and entities
110         createOrgRefs();
111
112         HeldintrustClient heldInTrustClient = new HeldintrustClient();
113         PoxPayloadOut hitPayload = createHitInstance(
114             "entryNumber-" + identifier,
115             depositorContactRefName,
116             // Use currentOwnerRefName twice to test fix for CSPACE-2863
117             depositorContactRefName,
118             externalApprovalIndividualRefName,
119             correspondenceSenderRefName);
120
121         Response res = heldInTrustClient.create(hitPayload);
122         try {
123             int statusCode = res.getStatus();
124
125             // Check the status code of the response: does it match the expected response(s)?
126             // Specifically:
127             // Does it fall within the set of valid status codes?
128             // Does it exactly match the expected status code?
129             logger.debug("{}: status = {}", testName, statusCode);
130             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
131                               invalidStatusCodeMessage(testRequestType, statusCode));
132             Assert.assertEquals(statusCode, testExpectedStatusCode);
133             String newHitId = extractId(res);
134             Assert.assertNotNull(newHitId, "Could not create a new Hit record.");
135
136             // Store the ID returned from the first resource created
137             // for additional tests below.
138             if (knownHitId == null) {
139                 knownHitId = newHitId;
140                 logger.debug("{}: knownHitId={}", testName, knownHitId);
141             }
142
143             // Store the IDs from every resource created by tests,
144             // so they can be deleted after tests have been run.
145             hitIdsCreated.add(newHitId);
146         } finally {
147             res.close();
148         }
149
150     }
151
152     /**
153      * Creates the organization refs.
154      *
155      * @throws Exception
156      */
157     protected void createOrgRefs() throws Exception {
158         OrganizationClient orgAuthClient = new OrganizationClient();
159         PoxPayloadOut multipart = OrgAuthorityClientUtils.createOrgAuthorityInstance(
160             ORGANIZATION_AUTHORITY_NAME, ORGANIZATION_AUTHORITY_NAME, orgAuthClient.getCommonPartName());
161         Response res = orgAuthClient.create(multipart);
162         try {
163             int statusCode = res.getStatus();
164             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
165                               invalidStatusCodeMessage(testRequestType, statusCode));
166             Assert.assertEquals(statusCode, STATUS_CREATED);
167             orgAuthCSID = extractId(res);
168             Assert.assertNotNull(orgAuthCSID, "Could not create a new Organization authority record.");
169         } finally {
170             res.close();
171         }
172
173         currentContactOrgCSID = createOrganization("olivierContactCompany", "Olivier Contact Company",
174                                                    "Olivier Contact Company");
175         orgIdsCreated.add(currentContactOrgCSID);
176         depositorContactRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID,
177                                                                         currentContactOrgCSID, orgAuthClient);
178
179         String newOrgCSID =
180             createOrganization("debbieDepositorAssocs", "Debbie Depositor & Associates",
181                                "Debbie Depositor & Associates");
182         depositorRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
183         orgIdsCreated.add(newOrgCSID);
184
185         newOrgCSID = createOrganization("andrewExternalApprovalLtd", "Andrew External-Approval Ltd.",
186                                         "Andrew External-Approval Ltd.");
187         externalApprovalIndividualRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID,
188                                                                                   newOrgCSID, orgAuthClient);
189         orgIdsCreated.add(newOrgCSID);
190
191         newOrgCSID = createOrganization("ingridCorrespondenceSender", "Ingrid Correspondence Sender",
192                                         "Ingrid Correspondence Sender");
193         correspondenceSenderRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
194         orgIdsCreated.add(newOrgCSID);
195
196         newOrgCSID = createOrganization("vinceValuerLLC", "Vince Valuer LLC", "Vince Valuer LLC");
197         valuerRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient);
198         orgIdsCreated.add(newOrgCSID);
199     }
200
201     protected String createOrganization(String shortId, String shortName, String longName) throws Exception {
202         String result;
203
204         OrganizationClient orgAuthClient = new OrganizationClient();
205         Map<String, String> orgInfo = new HashMap<String, String>();
206         orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId);
207
208         List<OrgTermGroup> orgTerms = new ArrayList<OrgTermGroup>();
209         OrgTermGroup term = new OrgTermGroup();
210         term.setTermDisplayName(shortName);
211         term.setTermName(shortName);
212         term.setMainBodyName(longName);
213         orgTerms.add(term);
214         PoxPayloadOut multipart =
215             OrgAuthorityClientUtils.createOrganizationInstance(null,
216                                                                orgInfo, orgTerms,
217                                                                orgAuthClient.getItemCommonPartName());
218
219         Response res = orgAuthClient.createItem(orgAuthCSID, multipart);
220         try {
221             int statusCode = res.getStatus();
222
223             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
224                               invalidStatusCodeMessage(testRequestType, statusCode));
225             Assert.assertEquals(statusCode, STATUS_CREATED);
226             result = extractId(res);
227         } finally {
228             res.close();
229         }
230
231         return result;
232     }
233
234     // Success outcomes here
235     @Test(dataProvider = "testName", dataProviderClass = BaseServiceTest.class,
236           dependsOnMethods = {"createHitWithAuthRefs"})
237     public void readAndCheckAuthRefDocs(String testName) throws Exception {
238         // Perform setup.
239         testSetup(STATUS_OK, ServiceRequestType.READ);
240
241         // Get the auth ref docs and check them
242         OrganizationClient orgAuthClient = new OrganizationClient();
243         Response refDocListResp = orgAuthClient.getReferencingObjects(orgAuthCSID, currentContactOrgCSID);
244         AuthorityRefDocList list;
245         try {
246             assertStatusCode(refDocListResp, testName);
247             list = refDocListResp.readEntity(AuthorityRefDocList.class);
248             Assert.assertNotNull(list);
249         } finally {
250             if (refDocListResp != null) {
251                 refDocListResp.close();
252             }
253         }
254
255         // Optionally output additional data about list members for debugging.
256         int nHitsFound = 0;
257         final int EXPECTED_HITS = 3;
258         int i = 0;
259         logger.debug("{}: Docs that use: {}", testName, depositorContactRefName);
260         for (AuthorityRefDocList.AuthorityRefDocItem item : list.getAuthorityRefDocItem()) {
261             logger.debug("{}: list-item[{}] {} ({}) Name:[{}] Number:[{}] in field:[{}]", testName, i,
262                          item.getDocType(), item.getDocId(), item.getDocName(), item.getDocNumber(),
263                          item.getSourceField());
264             if (knownHitId.equalsIgnoreCase(item.getDocId())) {
265                 nHitsFound++;
266             }
267             i++;
268         }
269         Assert.assertTrue((nHitsFound == EXPECTED_HITS), "Did not find Hit (twice more) with authref!");
270     }
271
272
273     // ---------------------------------------------------------------
274     // Cleanup of resources created during testing
275     // ---------------------------------------------------------------
276
277     /**
278      * Deletes all resources created by tests, after all tests have been run.
279      *
280      * This cleanup method will always be run, even if one or more tests fail.
281      * For this reason, it attempts to remove all resources created
282      * at any point during testing, even if some of those resources
283      * may be expected to be deleted by certain tests.
284      *
285      * @throws Exception
286      */
287     @AfterClass(alwaysRun = true)
288     public void cleanUp() throws Exception {
289         String noTest = System.getProperty("noTestCleanup");
290         if (Boolean.parseBoolean(noTest)) {
291             logger.debug("Skipping Cleanup phase ...");
292             return;
293         }
294
295         logger.debug("Cleaning up temporary resources created for testing ...");
296         HeldintrustClient heldInTrustClient = new HeldintrustClient();
297         // Note: Any non-success responses are ignored and not reported.
298         for (String resourceId : hitIdsCreated) {
299             heldInTrustClient.delete(resourceId).close();
300         }
301         // Delete persons before PersonAuth
302         OrganizationClient personAuthClient = new OrganizationClient();
303         for (String resourceId : orgIdsCreated) {
304             personAuthClient.deleteItem(orgAuthCSID, resourceId).close();
305         }
306         if (orgAuthCSID != null) {
307             personAuthClient.delete(orgAuthCSID).close();
308         }
309     }
310
311     // ---------------------------------------------------------------
312     // Utility methods used by tests above
313     // ---------------------------------------------------------------
314     @Override
315     public String getServicePathComponent() {
316         return SERVICE_PATH_COMPONENT;
317     }
318
319     private PoxPayloadOut createHitInstance(String heldInTrustNumber,
320                                             String depositorContact,
321                                             String depositor,
322                                             String externalApprovalIndividual,
323                                             String correspondenceSender) throws Exception {
324         HeldintrustsCommon hit =
325             HeldintrustClientTestUtil.createHitInstance(heldInTrustNumber, depositorContact, depositor,
326                                                         externalApprovalIndividual, correspondenceSender);
327
328         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
329         multipart.addPart(new HeldintrustClient().getCommonPartName(), hit);
330
331         logger.debug("to be created, hit common");
332         logger.debug("{}", objectAsXmlString(hit, HeldintrustsCommon.class));
333
334         return multipart;
335     }
336 }