]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
aead4d2c906b84ab006e6aad7fbc48b3804b8b11
[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.account.client.test;
24
25 import java.util.Collection;
26 import java.util.Hashtable;
27 import java.util.List;
28 import java.lang.UnsupportedOperationException;
29
30 import org.collectionspace.services.account.AccountsCommon;
31 import org.collectionspace.services.account.AccountsCommonList;
32 import org.collectionspace.services.account.AccountListItem;
33 import org.collectionspace.services.authorization.AccountRole;
34 import org.collectionspace.services.authorization.AccountValue;
35 import org.collectionspace.services.authorization.Role;
36 import org.collectionspace.services.authorization.RoleValue;
37 import org.collectionspace.services.client.AccountClient;
38 import org.collectionspace.services.client.AccountFactory;
39 import org.collectionspace.services.client.AccountRoleClient;
40 import org.collectionspace.services.client.AccountRoleFactory;
41 import org.collectionspace.services.client.CollectionSpaceClient;
42 import org.collectionspace.services.client.RoleClient;
43 import org.collectionspace.services.client.RoleFactory;
44 import org.collectionspace.services.client.test.AbstractServiceTestImpl;
45 import org.collectionspace.services.client.test.ServiceRequestType;
46
47 import javax.ws.rs.core.Response;
48
49 import org.testng.Assert;
50 import org.testng.annotations.Test;
51 import org.testng.annotations.AfterClass;
52 import org.testng.annotations.BeforeClass;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * AccountServiceTest, carries out tests against a
58  * deployed and running Account, Role and AccountRole Services.
59  * 
60  * $LastChangedRevision: 917 $
61  * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $
62  */
63 public class AccountRoleServiceTest extends AbstractServiceTestImpl<AccountRole, AccountRole, AccountRole, AccountRole> {
64
65     /** The Constant logger. */
66     private final static String CLASS_NAME = AccountRoleServiceTest.class.getName();
67     private final static Logger logger = LoggerFactory.getLogger(CLASS_NAME);
68     // Instance variables specific to this test.
69     private String prebuiltAdminCSID = null;
70     private String prebuiltAdminUserId = "admin@core.collectionspace.org";
71     /** The all resource ids created. */
72     /** The acc values. */
73     private Hashtable<String, AccountValue> accValues = new Hashtable<String, AccountValue>();
74     /** The role values. */
75     private Hashtable<String, RoleValue> roleValues = new Hashtable<String, RoleValue>();
76     /*
77      * This method is called only by the parent class, AbstractServiceTestImpl
78      */
79
80     /* (non-Javadoc)
81      * @see org.collectionspace.services.client.test.BaseServiceTest#getServicePathComponent()
82      */
83     @Override
84     protected String getServicePathComponent() {
85         return new AccountRoleClient().getServicePathComponent();
86     }
87     
88     /**
89      * The entity type expected from the JAX-RS Response object
90      */
91     public Class<AccountRole> getEntityResponseType() {
92         return AccountRole.class;
93     }
94
95     /**
96      * Seed data.
97      */
98     @BeforeClass(alwaysRun = true)
99     public void seedData() {
100         String userId = "acc-role-user1";
101         String accId = createAccount(userId, "acc-role-user1-test@cspace.org");
102         AccountValue ava = new AccountValue();
103         ava.setScreenName(userId);
104         ava.setUserId(userId);
105         ava.setAccountId(accId);
106         accValues.put(ava.getScreenName(), ava);
107
108         String userId2 = "acc-role-user2";
109         String coAccId = createAccount(userId2, "acc-role-user2-test@cspace.org");
110         AccountValue avc = new AccountValue();
111         avc.setScreenName(userId2);
112         avc.setUserId(userId2);
113         avc.setAccountId(coAccId);
114         accValues.put(avc.getScreenName(), avc);
115
116         String rn1 = "ROLE_CO1";
117         String r1RoleId = createRole(rn1);
118         RoleValue rv1 = new RoleValue();
119         rv1.setRoleId(r1RoleId);
120         rv1.setRoleName(rn1);
121         roleValues.put(rv1.getRoleName(), rv1);
122
123         String rn2 = "ROLE_CO2";
124         String r2RoleId = createRole(rn2);
125         RoleValue rv2 = new RoleValue();
126         rv2.setRoleId(r2RoleId);
127         rv2.setRoleName(rn2);
128         roleValues.put(rv2.getRoleName(), rv2);
129     }
130
131     /* (non-Javadoc)
132      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
133      */
134     @Override
135     protected CollectionSpaceClient getClientInstance() {
136         return new AccountRoleClient();
137     }
138
139         @Override
140         protected CollectionSpaceClient getClientInstance(String clientPropertiesFilename) {
141         return new AccountRoleClient(clientPropertiesFilename);
142         }
143
144     // ---------------------------------------------------------------
145     // CRUD tests : CREATE tests
146     // ---------------------------------------------------------------
147     // Success outcomes
148     
149     public void createList(String testName) throws Exception {
150         // Do nothing.  We do not support list creation in this test yet.
151     }
152     
153         @Override
154         protected AccountRole createInstance(String commonPartName,
155                         String identifier) {
156                 AccountRole result = null;
157                 
158         // Use a known Account to associate the AccountRole instance to
159         AccountValue av = accValues.get("acc-role-user1");
160         AccountRole accRole = createAccountRoleInstance(av,
161                 roleValues.values(), true, true);
162         
163         result = accRole;
164         return result;
165         }
166         
167         @Override
168         public void create(String testName) throws Exception {
169                 setupCreate();
170         AccountValue av = accValues.get("acc-role-user1");
171         AccountRole accRole = createAccountRoleInstance(av,
172                 roleValues.values(), true, true);
173         AccountRoleClient client = new AccountRoleClient();
174         Response res = client.create(av.getAccountId(), accRole);
175         try {
176                 assertStatusCode(res, testName);
177             knownResourceId = av.getAccountId();
178             if (logger.isDebugEnabled()) {
179                 logger.debug(testName + ": Created an AccountRole instance for account with knownResourceId="
180                                 + knownResourceId);
181             }
182         } finally {
183                 if (res != null) {
184                         res.close();
185                 }
186         }
187         }
188
189     // ---------------------------------------------------------------
190     // CRUD tests : READ tests
191     // ---------------------------------------------------------------
192
193     @Test(dataProvider = "testName",
194                 dependsOnMethods = {"CRUDTests"})
195     public void readNoRelationship(String testName) throws Exception {
196         // Perform setup.
197         setupRead();
198
199         // Submit the request to the service and store the response.
200         AccountRoleClient client = new AccountRoleClient();
201         Response res = client.read(
202                 accValues.get("acc-role-user2").getAccountId());
203         try {
204             // Check the status code of the response: does it match
205             // the expected response(s)?
206             assertStatusCode(res, testName);
207             AccountRole output = res.readEntity(AccountRole.class);
208             if(logger.isDebugEnabled()) {
209                 org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
210                 String sOutput = objectAsXmlString(objectFactory.createAccountRole(output), AccountRole.class);
211                 logger.debug(testName + " received " + sOutput);
212             }
213         } finally {
214                 if (res != null) {
215                         res.close();
216                 }
217         }
218     }
219     
220     /*
221      * In this test, for setup, we associate both test roles ("ROLE_CO1", "ROLE_CO2") with the test account "acc-role-user2".
222      * After we've performed this setup, our call to "/role/{csid}/accountroles" should contain an AccountRole that has
223      * a list of 1 account -the test user account we associated during setup.
224      */
225     @Test(dataProvider = "testName",
226             dependsOnMethods = {"CRUDTests"})
227     public void readRoleAccounts(String testName) throws Exception {
228                 /*
229                  * Setup a temp local scope for local variables that we need to create the AccountRole for
230                  * the setup of the read tests.
231                  */
232         {
233                 // Associate "acc-role-user2" with all the roles.
234                 AccountValue av = accValues.get("acc-role-user2");
235                 AccountRole accRole = createAccountRoleInstance(av,
236                         roleValues.values(), true, true);
237                 AccountRoleClient client = new AccountRoleClient();
238                 setupCreate();          
239                 Response res = client.create(av.getAccountId(), accRole);
240                 try {
241                         assertStatusCode(res, testName);
242                 } finally {
243                         if (res != null) {
244                                 res.close();
245                         }
246                 }
247         }
248
249         //
250         // Now read the list of accounts associated with the role "ROLE_CO1".
251         // There should be just the "acc-role-user2" account.
252         //
253         RoleClient roleClient = new RoleClient();
254         
255         // Submit the request to the service and store the response.
256         setupRead();        
257         Response res = roleClient.readRoleAccounts(
258                         roleValues.get("ROLE_CO1").getRoleId());
259         try {
260             // Check the status code of the response: does it match
261             // the expected response(s)?
262             assertStatusCode(res, testName);
263             AccountRole output = res.readEntity(AccountRole.class);
264             
265             // Now verify that the role has 2 accounts associate to it.
266             Assert.assertEquals(output.getAccount().size(), 1);
267             String sOutput = objectAsXmlString(output, AccountRole.class);
268             if(logger.isDebugEnabled()) {
269                 logger.debug(testName + " received " + sOutput);
270             }
271         } finally {
272                 if (res != null) {
273                 res.close();
274             }
275         }
276     }    
277
278     // ---------------------------------------------------------------
279     // CRUD tests : READ_LIST tests
280     // ---------------------------------------------------------------
281     // Success outcomes
282
283     @Override
284     public void readList(String testName) throws Exception {
285         //
286         // There is no such thing as a list of AccountRole resources
287         //
288     }
289     
290     @Override
291     public void readPaginatedList(String testName) throws Exception {
292         //
293         // There is no such thing as a list of AccountRole resources
294         //
295     }    
296
297     // Failure outcomes
298     // None at present.
299     // ---------------------------------------------------------------
300     // CRUD tests : UPDATE tests
301     // ---------------------------------------------------------------
302     // Success outcomes
303
304     @Override
305     public void update(String testName) throws Exception {
306         //
307         // AccountRole entities cannot be updated.  You must delete and recreate them
308         //
309     }
310
311     @Override
312     @Test(dataProvider = "testName",
313         dependsOnMethods = {"CRUDTests"})
314     public void updateNonExistent(String testName) throws Exception {
315         //
316         // AccountRole entities cannot be updated.  You must delete and recreate them
317         //
318     }
319
320     // ---------------------------------------------------------------
321     // CRUD tests : DELETE tests
322     // ---------------------------------------------------------------
323     // Success outcomes
324     
325     @Override
326     public void delete(String testName) throws Exception {
327         //
328         // First, lookup the known account and delete all of its role relationships
329         //
330         AccountRoleClient client = new AccountRoleClient();
331         setupRead();        
332         Response readResponse = client.read(
333                 accValues.get("acc-role-user1").getAccountId());
334         AccountRole toDelete = null;
335         try {
336                 assertStatusCode(readResponse, testName);
337                 toDelete = readResponse.readEntity(AccountRole.class);
338                 Assert.assertNotNull(toDelete);
339         } finally {
340                 if (readResponse != null) {
341                         readResponse.close();
342                 }
343         }
344
345         setupDelete();                
346         Response res = client.delete(
347                 toDelete.getAccount().get(0).getAccountId(), toDelete); // delete form #1
348         try {
349                 assertStatusCode(readResponse, testName);
350         } finally {
351                 if (res != null) {
352                         res.close();
353                 }
354         }
355         //
356         // Recreate 'acc-role-user1' account and roles for the next test
357         //
358         create(testName);
359                 
360         //
361         // Lookup a known account and delete all of its role relationships again
362         //
363         setupRead();
364         readResponse = client.read(
365                         accValues.get("acc-role-user1").getAccountId());
366         toDelete = null;
367         try {
368                 toDelete = readResponse.readEntity(AccountRole.class);
369         } finally {
370                 if (readResponse != null) {
371                         readResponse.close();
372                 }
373         }
374
375         setupDelete();        
376         Response deleteRes = client.delete(toDelete.getAccount().get(0).getAccountId()); // delete form #2
377         try {
378             int statusCode = deleteRes.getStatus();
379             Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
380                     invalidStatusCodeMessage(testRequestType, statusCode));
381             Assert.assertEquals(statusCode, testExpectedStatusCode);
382         } finally {
383                 deleteRes.close();
384         }
385     }
386
387     @Test(dataProvider = "testName",
388             dependsOnMethods = {"CRUDTests"})
389         public void deleteLockedAccount(String testName) throws Exception {
390         findPrebuiltAdminAccount();
391
392         // Perform setup.
393         testExpectedStatusCode = Response.Status.FORBIDDEN.getStatusCode();
394         testRequestType = ServiceRequestType.DELETE;
395         testSetup(testExpectedStatusCode, testRequestType);
396
397         AccountRoleClient client = new AccountRoleClient();
398         Response res = client.delete(prebuiltAdminCSID);
399         try {
400                 int statusCode = res.getStatus();
401                 Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
402                                 invalidStatusCodeMessage(testRequestType, statusCode));
403                 Assert.assertEquals(statusCode, testExpectedStatusCode);
404         } finally {
405                 if (res != null) {
406                         res.close();
407                 }
408         }
409     }
410
411     //
412     // Tests with expected failure outcomes
413     //
414
415     @Override
416     public void deleteNonExistent(String testName) throws Exception {
417         //ignoring this test as the service side returns 200 now even if it does
418         //not find a record in the db
419         
420         //FIXME: REM - 1/9/2012, need to find out why a 200 status code is returned and fix this.
421     }
422     
423     // ---------------------------------------------------------------
424     // Search tests
425     // ---------------------------------------------------------------
426     
427     @Override
428     public void searchWorkflowDeleted(String testName) throws Exception {
429         // Fixme: null test for now, overriding test in base class
430     }    
431
432     // ---------------------------------------------------------------
433     // Utility methods used by tests above
434     // ---------------------------------------------------------------
435
436     /**
437      * Creates the account role instance.
438      *
439      * @param av the av
440      * @param rvs the rvs
441      * @param usePermId the use perm id
442      * @param useRoleId the use role id
443      * @return the account role
444      */
445     static public AccountRole createAccountRoleInstance(AccountValue pv,
446             Collection<RoleValue> rvs,
447             boolean usePermId,
448             boolean useRoleId) {
449
450         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
451                 pv, rvs, usePermId, useRoleId);
452
453         if (logger.isDebugEnabled()) {
454             logger.debug("to be created, accRole common");
455             org.collectionspace.services.authorization.ObjectFactory objectFactory = new org.collectionspace.services.authorization.ObjectFactory();
456             logger.debug(objectAsXmlString(objectFactory.createAccountRole(accRole), AccountRole.class));
457         }
458         return accRole;
459     }
460
461     /**
462      * Clean up.
463      */
464     @AfterClass(alwaysRun = true)
465     @Override
466     public void cleanUp() {
467
468         setupDelete();
469
470         String noTest = System.getProperty("noTestCleanup");
471         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
472             if (logger.isDebugEnabled()) {
473                 logger.debug("Skipping Cleanup phase ...");
474             }
475             return;
476         }
477         if (logger.isDebugEnabled()) {
478             logger.debug("Cleaning up temporary resources created for testing ...");
479         }
480
481         for (AccountValue pv : accValues.values()) {
482             deleteAccount(pv.getAccountId());
483         }
484
485         for (RoleValue rv : roleValues.values()) {
486             deleteRole(rv.getRoleId());
487         }
488     }
489
490     /**
491      * Creates the account.
492      *
493      * @param userName the user name
494      * @param email the email
495      * @return the string
496      */
497     private String createAccount(String userName, String email) {
498         AccountClient accClient = new AccountClient();
499         AccountsCommon account = AccountFactory.createAccountInstance(
500                 userName, userName, userName, email, accClient.getTenantId(),
501                 true, false, true, true);
502         String result = null;
503         
504         setupCreate();
505         Response res = accClient.create(account);
506         try {
507                 assertStatusCode(res, "CreateAccount");
508                 result = extractId(res);
509         } finally {
510                 if (res != null) {
511                         res.close();
512                 }
513         }
514
515         return result;
516     }
517
518     private void findPrebuiltAdminAccount() {
519         // Search for the prebuilt admin user and then hold its CSID
520         if (prebuiltAdminCSID == null) {
521             setupReadList();
522             AccountClient client = new AccountClient();
523             Response res = client.readSearchList(null, this.prebuiltAdminUserId, null);
524             try {
525                     assertStatusCode(res, "findPrebuiltAdminAccount");
526                     AccountsCommonList list = res.readEntity(AccountsCommonList.class);
527                     List<AccountListItem> items = list.getAccountListItem();
528                     Assert.assertEquals(1, items.size(), "Found more than one Admin account!");
529                     AccountListItem item = items.get(0);
530                     prebuiltAdminCSID = item.getCsid();
531                     if (logger.isDebugEnabled()) {
532                         logger.debug("Found Admin Account with ID: " + prebuiltAdminCSID);
533                     }
534             } finally {
535                 if (res != null) {
536                     res.close();
537                 }               
538             }
539         }
540     }
541     
542     /**
543      * Delete account.
544      *
545      * @param accId the acc id
546      */
547     private void deleteAccount(String accId) {
548         AccountClient accClient = new AccountClient();
549         setupDelete();
550         Response res = accClient.delete(accId);
551         try {
552                 assertStatusCode(res, "DeleteAccount");
553         } finally {
554                 if (res != null) {
555                         res.close();
556                 }
557         }
558     }
559
560     /**
561      * Creates the role.
562      *
563      * @param roleName the role name
564      * @return the string
565      */
566     private String createRole(String roleName) {
567         String result = null;
568         
569         RoleClient roleClient = new RoleClient();
570         Role role = RoleFactory.createRoleInstance(roleName,
571                         roleName, //the display name
572                 "role for " + roleName, true);
573         setupCreate();
574         Response res = roleClient.create(role);
575         try {
576                 assertStatusCode(res, "CreateRole");
577                 result = extractId(res);
578         } finally {
579                 if (res != null) {
580                         res.close();
581                 }
582         }
583         
584         return result;
585     }
586
587     /**
588      * Delete role.
589      *
590      * @param roleId the role id
591      */
592     private void deleteRole(String roleId) {
593         setupDelete();
594         RoleClient roleClient = new RoleClient();
595         Response res = roleClient.delete(roleId);
596         try {
597                 assertStatusCode(res, "DeleteRole");
598         } finally {
599                 if (res != null) {
600                         res.close();
601                 }
602         }
603     }
604
605         @Override
606         protected String getServiceName() {
607                 // AccountRoles service is a sub-service of the Account service, so we return Account's service name
608                 return AccountClient.SERVICE_NAME;
609         }
610
611     /*
612      * For convenience and terseness, this test method is the base of the test execution dependency chain.  Other test methods may
613      * refer to this method in their @Test annotation declarations.
614      */
615     @Override
616     @Test(dataProvider = "testName",
617                 dependsOnMethods = {
618                         "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"})    
619     public void CRUDTests(String testName) {
620         // Do nothing.  Simply here to for a TestNG execution order for our tests
621     }
622
623         @Override
624         protected AccountRole updateInstance(AccountRole commonPartObject) {
625         //
626         // AccountRole entities cannot be updated.  You must delete and recreate them
627         //
628                 return null;
629         }
630
631         @Override
632         protected void compareReadInstances(AccountRole original, AccountRole updated)
633                         throws Exception {
634                 // FIXME: Should add field checks here.
635         }
636
637         @Override
638         protected void compareUpdatedInstances(AccountRole original,
639                         AccountRole updated) throws Exception {
640         //
641         // AccountRole entities cannot be updated.  You must delete and recreate them
642         //
643         }
644
645         @Override
646         protected Class<AccountRole> getCommonListType() {
647                 return AccountRole.class;
648         }
649
650         @Override
651         protected long getSizeOfList(AccountRole list) {
652                 // TODO Auto-generated method stub
653                 throw new UnsupportedOperationException("Method getSizeOfList() is not implemented because this service does not support lists.");
654         }
655 }