]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9a829cc6043af269ba8ad71c0bfca07290a9b17f
[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 2010 University of California at Berkeley
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
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 /*
25  * To change this template, choose Tools | Templates
26  * and open the template in the editor.
27  */
28 package org.collectionspace.services.security.client.test;
29
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Date;
33 import java.util.Hashtable;
34 import java.util.List;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37 import org.collectionspace.services.account.AccountsCommon;
38 import org.collectionspace.services.authorization.AccountRole;
39 import org.collectionspace.services.authorization.AccountValue;
40 import org.collectionspace.services.authorization.ActionType;
41 import org.collectionspace.services.authorization.EffectType;
42
43 import org.collectionspace.services.authorization.Permission;
44 import org.collectionspace.services.authorization.PermissionAction;
45 import org.collectionspace.services.authorization.PermissionRole;
46 import org.collectionspace.services.authorization.PermissionValue;
47 import org.collectionspace.services.authorization.Role;
48 import org.collectionspace.services.authorization.RoleValue;
49 import org.collectionspace.services.client.AccountClient;
50 import org.collectionspace.services.client.AccountFactory;
51 import org.collectionspace.services.client.AccountRoleClient;
52 import org.collectionspace.services.client.AccountRoleFactory;
53 import org.collectionspace.services.client.CollectionSpaceClient;
54 import org.collectionspace.services.client.DimensionClient;
55 import org.collectionspace.services.client.DimensionFactory;
56 import org.collectionspace.services.client.PermissionClient;
57 import org.collectionspace.services.client.PermissionFactory;
58 import org.collectionspace.services.client.PermissionRoleClient;
59 import org.collectionspace.services.client.PermissionRoleFactory;
60 import org.collectionspace.services.client.RoleClient;
61 import org.collectionspace.services.client.RoleFactory;
62 import org.collectionspace.services.client.test.AbstractServiceTestImpl;
63 import org.collectionspace.services.dimension.DimensionsCommon;
64 import org.collectionspace.services.jaxb.AbstractCommonList;
65 import org.jboss.resteasy.client.ClientResponse;
66 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
67 import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
68 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
69
70 import org.testng.Assert;
71 import org.testng.annotations.Test;
72
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.testng.annotations.AfterClass;
76 import org.testng.annotations.BeforeClass;
77
78 /**
79  * AuthorizationServiceTest, carries out tests against a
80  * deployed and running Permission, Role, AccountRole, PermissionRole and
81  * CollectionObject Services.
82  *
83  * Pre-requisite : authorization-mgt/client tests seed some permissions used
84  * by this test
85  *
86  * $LastChangedRevision: 917 $
87  * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $
88  */
89 public class MultiTenancyTest extends AbstractServiceTestImpl {
90
91     private final String CLASS_NAME = MultiTenancyTest.class.getName();
92     private final Logger logger = LoggerFactory.getLogger(CLASS_NAME);
93     private final static String TENANT_1_ADMIN_USER = "test";
94     private final static String TENANT_2_ADMIN_USER = "test-pahma";
95     private final static String TENANT_1_USER = "user1@museum1.org";
96     private final static String TENANT_2_USER = "user2@museum2.org";
97     private final static String TENANT_1 = "1";
98     private final static String TENANT_2 = "2";
99     private final static String TEST_ROLE_NAME = "ROLE_TEST_REGISTRAR";
100     private final static String TEST_SERVICE_A = "dimensions";
101
102     private static class UserInfo {
103
104         String userName;
105         String password;
106
107         UserInfo(String u, String p) {
108             userName = u;
109             password = p;
110         }
111     }
112     // Instance variables specific to this test.
113     private String TENANT_RESOURCE_1 = null;
114     private String TENANT_RESOURCE_2 = null;
115     private List<String> allResourceIdsCreated = new ArrayList();
116     //key for userAccounts is userId
117     private Hashtable<String, AccountValue> userAccounts = new Hashtable<String, AccountValue>();
118     //key for permValues is id as there could be several perms for the same resource
119     private Hashtable<String, PermissionValue> permValues = new Hashtable<String, PermissionValue>();
120     //key for all tenantXXX tables is tenant id, expecting only one entity per tenant for this test
121     private Hashtable<String, UserInfo> tenantAdminUsers = new Hashtable<String, UserInfo>();
122     private Hashtable<String, AccountValue> tenantAccounts = new Hashtable<String, AccountValue>();
123     private Hashtable<String, RoleValue> tenantRoles = new Hashtable<String, RoleValue>();
124     private Hashtable<String, Role> tenantAdminRoles = new Hashtable<String, Role>();
125     private Hashtable<String, PermissionValue> tenantPermissions = new Hashtable<String, PermissionValue>();
126
127 //    private String permId1;
128 //    private String permId2;
129
130     /*
131      * This method is called only by the parent class, AbstractServiceTestImpl
132      */
133     @Override
134     protected String getServicePathComponent() {
135         return null;
136     }
137
138     @BeforeClass(alwaysRun = true)
139     public void seedData() {
140         if (logger.isDebugEnabled()) {
141             testBanner("seedData", CLASS_NAME);
142         }
143
144         //tenant admin users are used to create accounts, roles and permissions and relationships
145         //assumption : two tenant admin users exist before running this test
146         tenantAdminUsers.put(TENANT_1, new UserInfo(TENANT_1_ADMIN_USER, "test"));
147         tenantAdminUsers.put(TENANT_2, new UserInfo(TENANT_2_ADMIN_USER, "test"));
148
149         seedAccounts();
150         seedPermissions();
151         seedRoles();
152         seedAccountRoles();
153         seedPermissionRoles();
154     }
155
156     private void seedAccounts() {
157         seedAccount(TENANT_1, TENANT_1_USER);
158         seedAccount(TENANT_2, TENANT_2_USER);
159     }
160
161     private void seedAccount(String tenantId, String userId) {
162         //create account using default user in admin role but assign tenant id
163         //create username, email and password same for simplicity
164         String accId = createAccount(tenantId, userId, userId);
165         AccountValue ava = new AccountValue();
166         ava.setScreenName(userId);
167         ava.setUserId(userId);
168         ava.setAccountId(accId);
169         userAccounts.put(ava.getUserId(), ava);
170         tenantAccounts.put(tenantId, ava);
171         if (logger.isDebugEnabled()) {
172             logger.debug("seedAccount tenantId=" + tenantId + " userId=" + userId);
173         }
174     }
175
176     private void seedPermissions() {
177         String resource = TEST_SERVICE_A;
178
179         PermissionAction pac = new PermissionAction();
180         pac.setName(ActionType.CREATE);
181         PermissionAction par = new PermissionAction();
182         par.setName(ActionType.READ);
183         PermissionAction pau = new PermissionAction();
184         pau.setName(ActionType.UPDATE);
185         PermissionAction pad = new PermissionAction();
186         pad.setName(ActionType.DELETE);
187
188         //both users can create, read and update and delete
189         List<PermissionAction> testActions = new ArrayList<PermissionAction>();
190         testActions.add(pac);
191         testActions.add(par);
192         testActions.add(pau);
193         testActions.add(pad);
194
195         seedPermission(TENANT_1, resource, testActions, EffectType.PERMIT);
196         seedPermission(TENANT_2, resource, testActions, EffectType.PERMIT);
197     }
198
199     private void seedPermission(String tenantId,
200             String resource, List<PermissionAction> testActions, EffectType effect) {
201         //create permission using default user in admin role but assign tenant id
202         String id = createPermission(tenantId, resource, testActions, effect);
203         PermissionValue pv = new PermissionValue();
204         pv.setResourceName(resource);
205         pv.setPermissionId(id);
206         permValues.put(pv.getPermissionId(), pv);
207         tenantPermissions.put(tenantId, pv);
208         if (logger.isDebugEnabled()) {
209             logger.debug("seedPermission tenantId=" + tenantId
210                     + " permId=" + id + " resource=" + resource);
211         }
212     }
213
214     private void seedRoles() {
215         //create role using default user in admin role but assign tenant id
216         //use the same role name to check constraints
217         seedRole(TENANT_1, TEST_ROLE_NAME);
218         seedRole(TENANT_2, TEST_ROLE_NAME);
219     }
220
221     private void seedRole(String tenantId, String roleName) {
222         String rid = createRole(tenantId, roleName);
223         RoleValue rv = new RoleValue();
224         rv.setRoleId(rid);
225         rv.setRoleName(roleName);
226         tenantRoles.put(tenantId, rv);
227         if (logger.isDebugEnabled()) {
228             logger.debug("seedRole tenantId=" + tenantId + " roleName=" + roleName);
229         }
230     }
231
232     private void seedAccountRoles() {
233
234         for (String tenantId : tenantAccounts.keySet()) {
235             AccountValue av = (AccountValue) tenantAccounts.get(tenantId);
236             seedAccountRole(tenantId, av.getUserId());
237         }
238     }
239
240     private void seedAccountRole(String tenantId, String userId) {
241         List<RoleValue> tenantRoleValues = new ArrayList<RoleValue>();
242         tenantRoleValues.add(tenantRoles.get(tenantId));
243         createAccountRole(tenantId, userAccounts.get(userId), tenantRoleValues);
244         if (logger.isDebugEnabled()) {
245             logger.debug("seedAccountRole tenantId=" + tenantId + " userId=" + userId);
246         }
247     }
248
249     private void seedPermissionRoles() {
250
251         for (String tenantId : tenantPermissions.keySet()) {
252             PermissionValue pv = tenantPermissions.get(tenantId);
253             seedPermissionRole(tenantId, pv.getPermissionId());
254         }
255     }
256
257     private void seedPermissionRole(String tenantId, String permId) {
258         List<RoleValue> tenantRoleValues = new ArrayList<RoleValue>();
259         tenantRoleValues.add(tenantRoles.get(tenantId));
260         PermissionValue pv = permValues.get(permId);
261         createPermissionRole(tenantId, permValues.get(permId), tenantRoleValues);
262         if (logger.isDebugEnabled()) {
263             logger.debug("seedPermissionRole tenantId=" + tenantId
264                     + " permId=" + permId + " resource=" + pv.getResourceName());
265         }
266     }
267
268
269     /* (non-Javadoc)
270      * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
271      */
272     @Override
273     protected CollectionSpaceClient getClientInstance() {
274         return null;
275     }
276
277     /* (non-Javadoc)
278      * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse)
279      */
280     @Override
281     protected AbstractCommonList getAbstractCommonList(
282             ClientResponse<AbstractCommonList> response) {
283         //FIXME: http://issues.collectionspace.org/browse/CSPACE-1697
284         throw new UnsupportedOperationException();
285     }
286
287     @Test(dataProvider = "testName")
288     @Override
289     public void readPaginatedList(String testName) throws Exception {
290         //FIXME: http://issues.collectionspace.org/browse/CSPACE-1697
291     }
292     // ---------------------------------------------------------------
293     // CRUD tests : CREATE tests
294     // ---------------------------------------------------------------
295     // Success outcomes
296
297     @Override
298     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
299     public void create(String testName) throws Exception {
300         if (logger.isDebugEnabled()) {
301             logger.debug(testBanner(testName, CLASS_NAME));
302         }
303
304         ClientResponse<Response> res = create(testName, TENANT_1_USER, TENANT_1);
305
306         TENANT_RESOURCE_1 = extractId(res);
307
308         if (logger.isDebugEnabled()) {
309             logger.debug(testName + ": tenantId= " + TENANT_1
310                     + " userId=" + TENANT_1_USER
311                     + " TENANT_RESOURCE_1 id=" + TENANT_RESOURCE_1);
312         }
313     }
314
315     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
316     public void create2(String testName) throws Exception {
317         if (logger.isDebugEnabled()) {
318             logger.debug(testBanner(testName, CLASS_NAME));
319         }
320
321         ClientResponse<Response> res = create(testName, TENANT_2_USER, TENANT_2);
322
323         TENANT_RESOURCE_2 = extractId(res);
324         if (logger.isDebugEnabled()) {
325             logger.debug(testName + ": tenantId= " + TENANT_2
326                     + " userId=" + TENANT_2_USER
327                     + " TENANT_RESOURCE_2 id=" + TENANT_RESOURCE_2);
328         }
329     }
330
331     private ClientResponse<Response> create(String testName, String userName, String tenatnId) {
332         setupCreate();
333         // Submit the request to the service and store the response.
334         DimensionClient client = new DimensionClient();
335         client.setAuth(true, userName, true, userName, true);
336         String identifier = createIdentifier();
337         DimensionsCommon dimension = new DimensionsCommon();
338         dimension.setDimension("dimensionType");
339         dimension.setValue("value-" + identifier);
340         dimension.setValueDate(new Date().toString());
341         MultipartOutput multipart = DimensionFactory.createDimensionInstance(client.getCommonPartName(),
342                 dimension);
343         ClientResponse<Response> res = client.create(multipart);
344         int statusCode = res.getStatus();
345
346         if (logger.isDebugEnabled()) {
347             logger.debug(testName + ": status = " + statusCode);
348         }
349         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
350                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
351         Assert.assertEquals(statusCode, Response.Status.CREATED.getStatusCode());
352         return res;
353
354     }
355
356     //to not cause uniqueness violation for permRole, createList is removed
357     @Override
358     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
359     dependsOnMethods = {"create"})
360     public void createList(String testName) throws Exception {
361     }
362
363     // Failure outcomes
364     // Placeholders until the three tests below can be uncommented.
365     // See Issue CSPACE-401.
366     @Override
367     public void createWithEmptyEntityBody(String testName) throws Exception {
368     }
369
370     @Override
371     public void createWithMalformedXml(String testName) throws Exception {
372     }
373
374     @Override
375     public void createWithWrongXmlSchema(String testName) throws Exception {
376     }
377
378     // ---------------------------------------------------------------
379     // CRUD tests : READ tests
380     // ---------------------------------------------------------------
381     // Success outcomes
382     @Override
383     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
384     dependsOnMethods = {"create"})
385     public void read(String testName) throws Exception {
386
387         if (logger.isDebugEnabled()) {
388             logger.debug(testBanner(testName, CLASS_NAME));
389         }
390         DimensionsCommon dimension = read(testName, TENANT_RESOURCE_1, TENANT_1_USER);
391         Assert.assertNotNull(dimension);
392         if (logger.isDebugEnabled()) {
393             logger.debug(testName + ": tenantId= " + TENANT_1
394                     + " userId=" + TENANT_1_USER
395                     + " TENANT_RESOURCE_1 retrieved id=" + dimension.getCsid());
396         }
397     }
398
399     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
400     dependsOnMethods = {"create2"})
401     public void read2(String testName) throws Exception {
402
403         if (logger.isDebugEnabled()) {
404             logger.debug(testBanner(testName, CLASS_NAME));
405         }
406         DimensionsCommon dimension = read(testName, TENANT_RESOURCE_2, TENANT_2_USER);
407         Assert.assertNotNull(dimension);
408         if (logger.isDebugEnabled()) {
409             logger.debug(testName + ": tenantId= " + TENANT_2
410                     + " userId=" + TENANT_2_USER
411                     + " TENANT_RESOURCE_1 retrieved id=" + dimension.getCsid());
412         }
413     }
414
415     private DimensionsCommon read(String testName, String id, String userName) throws Exception {
416         setupRead();
417         // Submit the request to the service and store the response.
418         DimensionClient client = new DimensionClient();
419         client.setAuth(true, userName, true, userName, true);
420         ClientResponse<MultipartInput> res = client.read(id);
421         int statusCode = res.getStatus();
422
423         // Check the status code of the response: does it match
424         // the expected response(s)?
425         if (logger.isDebugEnabled()) {
426             logger.debug(testName + ": status = " + statusCode);
427         }
428         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
429                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
430         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
431
432         MultipartInput input = (MultipartInput) res.getEntity();
433         return (DimensionsCommon) extractPart(input,
434                 client.getCommonPartName(), DimensionsCommon.class);
435     }
436     // Failure outcomes
437
438     @Override
439     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
440     public void readNonExistent(String testName) throws Exception {
441
442         // Perform setup.
443         setupReadNonExistent();
444     }
445
446     // ---------------------------------------------------------------
447     // CRUD tests : READ_LIST tests
448     // ---------------------------------------------------------------
449     // Success outcomes
450     @Override
451     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
452     dependsOnMethods = {"createList", "read"})
453     public void readList(String testName) throws Exception {
454         setupReadList();
455     }
456
457     // Failure outcomes
458     // None at present.
459     // ---------------------------------------------------------------
460     // CRUD tests : UPDATE tests
461     // ---------------------------------------------------------------
462     // Success outcomes
463     @Override
464     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
465     dependsOnMethods = {"read", "readList", "readNonExistent"})
466     public void update(String testName) throws Exception {
467         setupUpdate();
468
469     }
470
471     // Failure outcomes
472     // Placeholders until the three tests below can be uncommented.
473     // See Issue CSPACE-401.
474     @Override
475     public void updateWithEmptyEntityBody(String testName) throws Exception {
476     }
477
478     @Override
479     public void updateWithMalformedXml(String testName) throws Exception {
480     }
481
482     @Override
483     public void updateWithWrongXmlSchema(String testName) throws Exception {
484     }
485
486     @Override
487     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
488     dependsOnMethods = {"read2", "readNonExistent", "testSubmitRequest"})
489     public void updateNonExistent(String testName) throws Exception {
490
491         DimensionClient client = new DimensionClient();
492         //TENANT_1_USER is not allowed to update the resource of TENANT_2
493         client.setAuth(true, TENANT_1_USER, true, TENANT_1_USER, true);
494
495         DimensionsCommon dimension = new DimensionsCommon();
496         dimension.setDimension("dimensionType");
497         // Update the content of this resource.
498         dimension.setValue("updated-" + dimension.getValue());
499         dimension.setValueDate("updated-" + dimension.getValueDate());
500         // Submit the request to the service and store the response.
501         MultipartOutput output = new MultipartOutput();
502         OutputPart commonPart = output.addPart(dimension, MediaType.APPLICATION_XML_TYPE);
503         commonPart.getHeaders().add("label", client.getCommonPartName());
504
505         ClientResponse<MultipartInput> res = client.update(TENANT_RESOURCE_2, output);
506         int statusCode = res.getStatus();
507         // Check the status code of the response: does it match the expected response(s)?
508         if (logger.isDebugEnabled()) {
509             logger.debug(testName + " resource = " + TENANT_RESOURCE_2
510                     + " status = " + statusCode);
511         }
512         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
513                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
514         //going to incorrect Nuxeo domain would give DocumentNotFoundException
515         //instead of giving FORBIDDEN
516         Assert.assertEquals(statusCode, Response.Status.NOT_FOUND.getStatusCode());
517     }
518
519     // ---------------------------------------------------------------
520     // CRUD tests : DELETE tests
521     // ---------------------------------------------------------------
522     // Success outcomes
523     @Override
524     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
525     dependsOnMethods = {"deleteNonExistent"})
526     public void delete(String testName) throws Exception {
527
528         if (logger.isDebugEnabled()) {
529             logger.debug(testBanner(testName, CLASS_NAME));
530         }
531
532         int statusCode = delete(testName, TENANT_RESOURCE_1, TENANT_1_USER);
533     }
534
535     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
536     dependsOnMethods = {"updateNonExistent"})
537     public void delete2(String testName) throws Exception {
538
539         if (logger.isDebugEnabled()) {
540             logger.debug(testBanner(testName, CLASS_NAME));
541         }
542         int statusCode = delete(testName, TENANT_RESOURCE_2, TENANT_2_USER);
543
544     }
545
546     private int delete(String testName, String id, String userName) throws Exception {
547         // Perform setup.
548         setupDelete();
549         // Submit the request to the service and store the response.
550         DimensionClient client = new DimensionClient();
551         client.setAuth(true, userName, true, userName, true);
552         ClientResponse<Response> res = client.delete(id);
553         int statusCode = res.getStatus();
554
555         // Check the status code of the response: does it match
556         // the expected response(s)?
557         if (logger.isDebugEnabled()) {
558             logger.debug(testName + ": status = " + statusCode);
559         }
560         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
561                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
562         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
563         return statusCode;
564     }
565
566     // Failure outcomes
567     @Override
568     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
569     dependsOnMethods = {"read"})
570     public void deleteNonExistent(String testName) throws Exception {
571         //ignoring this test as the service side returns 200 now even if it does
572         //not find a record in the db
573
574         if (logger.isDebugEnabled()) {
575             logger.debug(testBanner(testName, CLASS_NAME));
576         }
577         // Perform setup.
578         setupDelete();
579
580         // Submit the request to the service and store the response.
581         DimensionClient client = new DimensionClient();
582         //TENANT_2_USER of TENANT_2 is not allowed to delete the resource of TENANT_1
583         client.setAuth(true, TENANT_2_USER, true, TENANT_2_USER, true);
584         ClientResponse<Response> res = client.delete(TENANT_RESOURCE_1);
585         int statusCode = res.getStatus();
586
587         // Check the status code of the response: does it match
588         // the expected response(s)?
589         if (logger.isDebugEnabled()) {
590             logger.debug(testName + ": status = " + statusCode);
591         }
592         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
593                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
594         //going to incorrect Nuxeo domain would give DocumentNotFoundException
595         //instead of giving FORBIDDEN
596         Assert.assertEquals(statusCode, Response.Status.NOT_FOUND.getStatusCode());
597     }
598
599     // ---------------------------------------------------------------
600     // Utility tests : tests of code used in tests above
601     // ---------------------------------------------------------------
602     /**
603      * Tests the code for manually submitting data that is used by several
604      * of the methods above.
605      */
606     @Test(dependsOnMethods = {"create"})
607     public void testSubmitRequest() throws Exception {
608     }
609
610     // ---------------------------------------------------------------
611     // Utility methods used by tests above
612     // ---------------------------------------------------------------
613     @AfterClass(alwaysRun = true)
614     public void cleanUp() {
615         if (logger.isDebugEnabled()) {
616             testBanner("cleanUp", CLASS_NAME);
617         }
618         setupDelete();
619         String noTest = System.getProperty("noTestCleanup");
620         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
621             if (logger.isDebugEnabled()) {
622                 logger.debug("Skipping Cleanup phase ...");
623             }
624             return;
625         }
626         if (logger.isDebugEnabled()) {
627             logger.debug("Cleaning up temporary resources created for testing ...");
628         }
629
630         //tenant admin users are used to create accounts, roles and permissions and relationships
631         //assumption : two tenant admin users exist before running this test
632
633         deletePermissionRoles();
634         deleteAccountRoles();
635         //deletePermissions would delete association with ROLE_XXX_ADMINISTRTOR too
636         //deletePermissions();
637         deleteRoles();
638         deleteAccounts();
639     }
640
641     private void deletePermissionRoles() {
642
643         for (String tenantId : tenantPermissions.keySet()) {
644             List<RoleValue> tenantRoleValues = new ArrayList<RoleValue>();
645             tenantRoleValues.add(tenantRoles.get(tenantId));
646             PermissionValue pv = tenantPermissions.get(tenantId);
647             deletePermissionRole(tenantId, pv, tenantRoleValues);
648         }
649     }
650
651     private void deleteAccountRoles() {
652         for (String tenantId : tenantAccounts.keySet()) {
653             List<RoleValue> tenantRoleValues = new ArrayList<RoleValue>();
654             tenantRoleValues.add(tenantRoles.get(tenantId));
655             AccountValue av = tenantAccounts.get(tenantId);
656             deleteAccountRole(tenantId, av, tenantRoleValues);
657         }
658     }
659
660     private void deletePermissions() {
661         for (String tenantId : tenantPermissions.keySet()) {
662             PermissionValue pv = tenantPermissions.get(tenantId);
663             deletePermission(tenantId, pv.getPermissionId());
664         }
665     }
666
667     private void deleteRoles() {
668         for (String tenantId : tenantRoles.keySet()) {
669             RoleValue rv = tenantRoles.get(tenantId);
670             deleteRole(tenantId, rv.getRoleId());
671         }
672     }
673
674     private void deleteAccounts() {
675
676         for (String tenantId : tenantAccounts.keySet()) {
677             AccountValue av = tenantAccounts.get(tenantId);
678             deleteAccount(tenantId, av.getAccountId());
679         }
680     }
681
682     private String createPermission(String tenantId, String resName,
683             List<PermissionAction> actions, EffectType effect) {
684         setupCreate();
685         PermissionClient permClient = new PermissionClient();
686         UserInfo ui = tenantAdminUsers.get(tenantId);
687         permClient.setAuth(true, ui.userName, true, ui.password, true);
688         Permission permission = PermissionFactory.createPermissionInstance(resName,
689                 "default permissions for " + resName,
690                 actions, effect, true, true, true);
691         permission.setTenantId(tenantId);
692         ClientResponse<Response> res = permClient.create(permission);
693         int statusCode = res.getStatus();
694         if (logger.isDebugEnabled()) {
695             logger.debug("createPermission: resName=" + resName
696                     + " status = " + statusCode);
697         }
698         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
699                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
700         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
701         res.releaseConnection();
702         return extractId(res);
703     }
704
705     private void deletePermission(String tenantId, String permId) {
706         setupDelete();
707         PermissionClient permClient = new PermissionClient();
708         UserInfo ui = tenantAdminUsers.get(tenantId);
709         permClient.setAuth(true, ui.userName, true, ui.password, true);
710         ClientResponse<Response> res = permClient.delete(permId);
711         int statusCode = res.getStatus();
712         if (logger.isDebugEnabled()) {
713             logger.debug("deletePermission: delete permission id="
714                     + permId + " status=" + statusCode);
715         }
716         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
717                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
718         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
719         res.releaseConnection();
720     }
721
722     private String createRole(String tenantId, String roleName) {
723         setupCreate();
724         RoleClient roleClient = new RoleClient();
725         UserInfo ui = tenantAdminUsers.get(tenantId);
726         roleClient.setAuth(true, ui.userName, true, ui.password, true);
727         Role role = RoleFactory.createRoleInstance(roleName,
728                 "role for " + roleName, true);
729         role.setTenantId(tenantId);
730         ClientResponse<Response> res = roleClient.create(role);
731         int statusCode = res.getStatus();
732         if (logger.isDebugEnabled()) {
733             logger.debug("createRole: name=" + roleName
734                     + " status = " + statusCode);
735         }
736         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
737                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
738         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
739         res.releaseConnection();
740         return extractId(res);
741     }
742
743     private void deleteRole(String tenantId, String roleId) {
744         setupDelete();
745         RoleClient roleClient = new RoleClient();
746         UserInfo ui = tenantAdminUsers.get(tenantId);
747         roleClient.setAuth(true, ui.userName, true, ui.password, true);
748         ClientResponse<Response> res = roleClient.delete(roleId);
749         int statusCode = res.getStatus();
750         if (logger.isDebugEnabled()) {
751             logger.debug("deleteRole: delete role id=" + roleId
752                     + " status=" + statusCode);
753         }
754         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
755                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
756         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
757         res.releaseConnection();
758     }
759
760     private String createAccount(String tenantId, String userName, String email) {
761         setupCreate();
762         AccountClient accountClient = new AccountClient();
763         UserInfo ui = tenantAdminUsers.get(tenantId);
764         accountClient.setAuth(true, ui.userName, true, ui.password, true);
765         AccountsCommon account = AccountFactory.createAccountInstance(
766                 userName, userName, userName, email, tenantId,
767                 true, false, true, true);
768         ClientResponse<Response> res = accountClient.create(account);
769         int statusCode = res.getStatus();
770         if (logger.isDebugEnabled()) {
771             logger.debug("createAccount: tenantId=" + tenantId + " userName=" + userName
772                     + " status = " + statusCode);
773         }
774         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
775                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
776         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
777         res.releaseConnection();
778         return extractId(res);
779     }
780
781     private void deleteAccount(String tenantId, String accId) {
782         setupDelete();
783         AccountClient accClient = new AccountClient();
784         UserInfo ui = tenantAdminUsers.get(tenantId);
785         accClient.setAuth(true, ui.userName, true, ui.password, true);
786         ClientResponse<Response> res = accClient.delete(accId);
787         int statusCode = res.getStatus();
788         if (logger.isDebugEnabled()) {
789             logger.debug("deleteAccount: delete account id="
790                     + accId + " status=" + statusCode);
791         }
792         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
793                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
794         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
795         res.releaseConnection();
796     }
797
798     private String createAccountRole(String tenantId, AccountValue av,
799             Collection<RoleValue> rvs) {
800         setupCreate();
801
802         // Submit the request to the service and store the response.
803         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
804                 av, rvs, true, true);
805         AccountRoleClient client = new AccountRoleClient();
806         UserInfo ui = tenantAdminUsers.get(tenantId);
807         client.setAuth(true, ui.userName, true, ui.password, true);
808         ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
809         int statusCode = res.getStatus();
810
811         if (logger.isDebugEnabled()) {
812             logger.debug("createAccountRole: status = " + statusCode);
813         }
814         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
815                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
816         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
817         res.releaseConnection();
818         return extractId(res);
819     }
820
821     private void deleteAccountRole(String tenantId, AccountValue av,
822             List<RoleValue> rvs) {
823         // Perform setup.
824         setupDelete();
825
826         // Submit the request to the service and store the response.
827         AccountRoleClient client = new AccountRoleClient();
828         UserInfo ui = tenantAdminUsers.get(tenantId);
829         client.setAuth(true, ui.userName, true, ui.password, true);
830         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
831                 av, rvs, true, true);
832         ClientResponse<Response> res = client.delete(
833                 av.getAccountId());
834         int statusCode = res.getStatus();
835
836         // Check the status code of the response: does it match
837         // the expected response(s)?
838         if (logger.isDebugEnabled()) {
839             logger.debug("deleteAccountRole: status = " + statusCode);
840         }
841         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
842                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
843         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
844         res.releaseConnection();
845     }
846
847     private String createPermissionRole(String tenantId, PermissionValue pv,
848             Collection<RoleValue> rvs) {
849         setupCreate();
850         List<RoleValue> rvls = new ArrayList<RoleValue>();
851         rvls.addAll(rvs);
852         PermissionRole permRole = PermissionRoleFactory.createPermissionRoleInstance(
853                 pv, rvls, true, true);
854         PermissionRoleClient client = new PermissionRoleClient();
855         UserInfo ui = tenantAdminUsers.get(tenantId);
856         client.setAuth(true, ui.userName, true, ui.password, true);
857         ClientResponse<Response> res = client.create(pv.getPermissionId(), permRole);
858         int statusCode = res.getStatus();
859
860         if (logger.isDebugEnabled()) {
861             logger.debug("createPermissionRole: status = " + statusCode);
862         }
863         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
864                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
865         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
866         res.releaseConnection();
867         return extractId(res);
868     }
869
870     private void deletePermissionRole(String tenantId, PermissionValue pv, List<RoleValue> rvls) {
871
872         // Perform setup.
873         setupDelete();
874
875         // Submit the request to the service and store the response.
876         PermissionRoleClient client = new PermissionRoleClient();
877         UserInfo ui = tenantAdminUsers.get(tenantId);
878         client.setAuth(true, ui.userName, true, ui.password, true);
879         PermissionRole permRole = PermissionRoleFactory.createPermissionRoleInstance(
880                 pv, rvls, true, true);
881         ClientResponse<Response> res = client.delete(pv.getPermissionId());
882         int statusCode = res.getStatus();
883
884         // Check the status code of the response: does it match
885         // the expected response(s)?
886         if (logger.isDebugEnabled()) {
887             logger.debug("deletePermissionRole : status = " + statusCode);
888         }
889         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
890                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
891         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
892         res.releaseConnection();
893     }
894 }