]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9637b4ab5b2806680a5c083425e7378b306a60f1
[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.PersonJAXBSchema;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.PottagClient;
35 import org.collectionspace.services.client.PersonAuthorityClient;
36 import org.collectionspace.services.client.PersonAuthorityClientUtils;
37 import org.collectionspace.services.client.PayloadOutputPart;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.common.authorityref.AuthorityRefList;
41 import org.collectionspace.services.jaxb.AbstractCommonList;
42 import org.collectionspace.services.pottag.PottagsCommon;
43 import org.collectionspace.services.person.PersonTermGroup;
44
45 import org.testng.Assert;
46 import org.testng.annotations.AfterClass;
47 import org.testng.annotations.Test;
48
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 /**
53  * PottagAuthRefsTest, carries out Authority References tests against a
54  * deployed and running Pottag (aka Pot Tag) Service.
55  *
56  * $LastChangedRevision$
57  * $LastChangedDate$
58  */
59 public class PottagAuthRefsTest extends BaseServiceTest<AbstractCommonList> {
60
61     private final String CLASS_NAME = PottagAuthRefsTest.class.getName();
62     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
63     
64     // Instance variables specific to this test.
65     final String PERSON_AUTHORITY_NAME = "TestPersonAuth";
66     private List<String> pottagIdsCreated = new ArrayList<String>();
67     private List<String> personIdsCreated = new ArrayList<String>();
68     private String personAuthCSID = null;
69         private String taggedByAuthRef;
70
71     /* (non-Javadoc)
72      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
73      */
74     @Override
75     protected CollectionSpaceClient getClientInstance() {
76         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
77     }
78     
79     /* (non-Javadoc)
80      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
81      */
82     @Override
83         protected AbstractCommonList getCommonList(Response response) {
84         throw new UnsupportedOperationException(); //method not supported (or needed) in this test class
85     }
86
87     // ---------------------------------------------------------------
88     // CRUD tests : CREATE tests
89     // ---------------------------------------------------------------
90     // Success outcomes
91     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class)
92     public void createWithAuthRefs(String testName) throws Exception {
93         testSetup(STATUS_CREATED, ServiceRequestType.CREATE);
94
95         // Submit the request to the service and store the response.
96         String identifier = createIdentifier();
97         
98         // Create all the person refs and entities
99         createPersonRefs();
100
101         // Create a new Loans In resource.
102         //
103         // One or more fields in this resource will be PersonAuthority
104         // references, and will refer to Person resources by their refNames.
105         PottagClient pottagClient = new PottagClient();
106         PoxPayloadOut pottageInstance = createPottagInstance("familyName-" + identifier, this.taggedByAuthRef,
107                         "commonName-" + identifier);
108         Response response = pottagClient.create(pottageInstance);
109         try {
110                 assertStatusCode(response, testName);   
111                 // Store the ID returned from the first resource created for additional tests below.
112                 if (knownResourceId == null) {
113                     knownResourceId = extractId(response);
114                 }
115                 
116                 // Store the IDs from every resource created by tests,
117                 // so they can be deleted after tests have been run.
118                 pottagIdsCreated.add(extractId(response));
119         } finally {
120                 response.close();
121         }
122     }
123     
124     protected void createPersonRefs() throws Exception {
125         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
126         // Create a temporary PersonAuthority resource, and its corresponding
127         // refName by which it can be identified.
128         PoxPayloadOut multipart = PersonAuthorityClientUtils.createPersonAuthorityInstance(
129             PERSON_AUTHORITY_NAME, PERSON_AUTHORITY_NAME, personAuthClient.getCommonPartName());
130         Response res = personAuthClient.create(multipart);
131         try {
132                 int statusCode = res.getStatus();
133                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), invalidStatusCodeMessage(testRequestType, statusCode));
134                 Assert.assertEquals(statusCode, STATUS_CREATED);
135                 personAuthCSID = extractId(res);
136         } finally {
137                 res.close();
138         }
139         String authRefName = PersonAuthorityClientUtils.getAuthorityRefName(personAuthCSID, personAuthClient);
140         
141         // Create temporary Person resource, and a corresponding refName from which it can be identified.
142         String csid = createPerson("Harry", "Potter", "harryPotter", authRefName);
143         this.personIdsCreated.add(csid);
144         this.taggedByAuthRef = PersonAuthorityClientUtils.getPersonRefName(personAuthCSID, csid, personAuthClient);
145     }
146     
147     protected String createPerson(String firstName, String surName, String shortId, String authRefName ) throws Exception {
148         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
149         Map<String, String> personInfo = new HashMap<String,String>();
150         personInfo.put(PersonJAXBSchema.FORE_NAME, firstName);
151         personInfo.put(PersonJAXBSchema.SUR_NAME, surName);
152         personInfo.put(PersonJAXBSchema.SHORT_IDENTIFIER, shortId);
153         List<PersonTermGroup> personTerms = new ArrayList<PersonTermGroup>();
154         PersonTermGroup term = new PersonTermGroup();
155         String termName = firstName + " " + surName;
156         term.setTermDisplayName(termName);
157         term.setTermName(termName);
158         personTerms.add(term);
159         PoxPayloadOut multipart =
160                 PersonAuthorityClientUtils.createPersonInstance(personAuthCSID, 
161                                 authRefName, personInfo, personTerms, personAuthClient.getItemCommonPartName());
162         
163         Response res = personAuthClient.createItem(personAuthCSID, multipart);
164         try {
165                 int statusCode = res.getStatus();
166                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
167                         invalidStatusCodeMessage(testRequestType, statusCode));
168                 Assert.assertEquals(statusCode, STATUS_CREATED);
169                 return extractId(res);
170         } finally {
171                 res.close();
172         }
173     }
174
175     // Success outcomes
176     @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class,
177         dependsOnMethods = {"createWithAuthRefs"})
178     public void readAndCheckAuthRefs(String testName) throws Exception {
179         // Perform setup.
180         testSetup(STATUS_OK, ServiceRequestType.READ);
181
182         // Submit the request to the service and store the response.
183         PottagClient pottagClient = new PottagClient();
184         Response res = pottagClient.read(knownResourceId);
185         try {
186                 assertStatusCode(res, testName);
187                 // Extract the common part from the response.
188                 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
189                 PottagsCommon pottagCommon = (PottagsCommon) extractPart(input, pottagClient.getCommonPartName(),
190                                 PottagsCommon.class);
191                 Assert.assertNotNull(pottagCommon);
192         } finally {
193                 if (res != null) {
194                 res.close();
195             }
196         }
197         
198         // Get the auth refs and check them
199         res = pottagClient.getAuthorityRefs(knownResourceId);
200         AuthorityRefList list = null;
201         try {
202                 assertStatusCode(res, testName);
203                 list = res.readEntity(AuthorityRefList.class);
204                 Assert.assertNotNull(list);
205         } finally {
206                 if (res != null) {
207                         res.close();
208             }
209         }
210         
211         int expectedAuthRefs = personIdsCreated.size();
212         List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
213         int numAuthRefsFound = items.size();
214         if (logger.isDebugEnabled()) {
215             logger.debug("Expected " + expectedAuthRefs + " authority references, found " + numAuthRefsFound);
216         }
217
218         // Optionally output additional data about list members for debugging.
219         boolean iterateThroughList = true;
220         if (iterateThroughList && logger.isDebugEnabled()) {
221             int i = 0;
222             for(AuthorityRefList.AuthorityRefItem item : items){
223                 logger.debug(testName + ": list-item[" + i + "] Field:" +
224                                 item.getSourceField() + "= " +
225                         item.getAuthDisplayName() +
226                         item.getItemDisplayName());
227                 logger.debug(testName + ": list-item[" + i + "] refName=" +
228                         item.getRefName());
229                 logger.debug(testName + ": list-item[" + i + "] URI=" +
230                         item.getUri());
231                 i++;
232             }
233         }
234
235         Assert.assertEquals(numAuthRefsFound, expectedAuthRefs,
236             "Did not find all expected authority references! " + "Expected " + expectedAuthRefs + ", found " + numAuthRefsFound);
237     }
238
239
240     // ---------------------------------------------------------------
241     // Cleanup of resources created during testing
242     // ---------------------------------------------------------------
243
244     /**
245      * Deletes all resources created by tests, after all tests have been run.
246      *
247      * This cleanup method will always be run, even if one or more tests fail.
248      * For this reason, it attempts to remove all resources created
249      * at any point during testing, even if some of those resources
250      * may be expected to be deleted by certain tests.
251      * @throws Exception 
252      */
253     @AfterClass(alwaysRun=true)
254     public void cleanUp() throws Exception {
255         String noTest = System.getProperty("noTestCleanup");
256         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
257             if (logger.isDebugEnabled()) {
258                 logger.debug("Skipping Cleanup phase ...");
259             }
260             return;
261         }
262         if (logger.isDebugEnabled()) {
263             logger.debug("Cleaning up temporary resources created for testing ...");
264         }
265         
266         //
267         // Delete all the pottag records we created
268         PottagClient pottagClient = new PottagClient();
269         for (String resourceId : pottagIdsCreated) {
270             // Note: Any non-success responses are ignored and not reported.
271             pottagClient.delete(resourceId).close(); // alternative to pottagClient.delete(resourceId).releaseConnection();
272         }
273         
274         //
275         // Delete Person resource(s) (before PersonAuthority resources).     
276         PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
277         for (String resourceId : personIdsCreated) {
278             // Note: Any non-success responses are ignored and not reported.
279                 personAuthClient.deleteItem(personAuthCSID, resourceId).close();
280         }
281         if (personAuthCSID != null) {
282                 personAuthClient.delete(personAuthCSID).close();
283         }
284     }
285
286     // ---------------------------------------------------------------
287     // Utility methods used by tests above
288     // ---------------------------------------------------------------
289     public String getServiceName() {
290         return PottagClient.SERVICE_NAME;
291     }
292
293     @Override
294     public String getServicePathComponent() {
295         return PottagClient.SERVICE_PATH_COMPONENT;
296     }
297
298     private PoxPayloadOut createPottagInstance(String familyName,
299                 String taggedBy,
300                 String commonName) throws Exception {
301         PottagsCommon pottagCommon = new PottagsCommon();
302         pottagCommon.setFamily(familyName);
303         pottagCommon.setTaggedBy(taggedBy);
304         pottagCommon.setCommonName(commonName);
305
306         PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent());
307         PayloadOutputPart commonPart =
308                         multipart.addPart(new PottagClient().getCommonPartName(), pottagCommon);
309
310         if(logger.isDebugEnabled()){
311                 logger.debug("to be created, pottag common");
312                 logger.debug(objectAsXmlString(pottagCommon, PottagsCommon.class));
313         }
314
315         return multipart;
316     }
317
318     @Override
319     protected Class<AbstractCommonList> getCommonListType() {
320         return AbstractCommonList.class;
321     }
322
323         @Override
324         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) throws Exception {
325                 // TODO Auto-generated method stub
326                 return null;
327         }
328 }