]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
75075ecbfcc16bdd4c382a06cdebe860c21be7db
[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  
524
525     @Override
526     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
527     dependsOnMethods = {"deleteNonExistent"})
528     public void delete(String testName) throws Exception {
529
530         if (logger.isDebugEnabled()) {
531             logger.debug(testBanner(testName, CLASS_NAME));
532         }
533
534         int statusCode = delete(testName, TENANT_RESOURCE_1, TENANT_1_USER);
535     }
536
537     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
538     dependsOnMethods = {"updateNonExistent"})
539     public void delete2(String testName) throws Exception {
540
541         if (logger.isDebugEnabled()) {
542             logger.debug(testBanner(testName, CLASS_NAME));
543         }
544         int statusCode = delete(testName, TENANT_RESOURCE_2, TENANT_2_USER);
545
546     }
547
548     private int delete(String testName, String id, String userName) throws Exception {
549         // Perform setup.
550         setupDelete();
551         // Submit the request to the service and store the response.
552         DimensionClient client = new DimensionClient();
553         client.setAuth(true, userName, true, userName, true);
554         ClientResponse<Response> res = client.delete(id);
555         int statusCode = res.getStatus();
556
557         // Check the status code of the response: does it match
558         // the expected response(s)?
559         if (logger.isDebugEnabled()) {
560             logger.debug(testName + ": status = " + statusCode);
561         }
562         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
563                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
564         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
565         return statusCode;
566     }
567
568     // Failure outcomes
569     @Override
570     @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class,
571     dependsOnMethods = {"read"})
572     public void deleteNonExistent(String testName) throws Exception {
573         //ignoring this test as the service side returns 200 now even if it does
574         //not find a record in the db
575
576         if (logger.isDebugEnabled()) {
577             logger.debug(testBanner(testName, CLASS_NAME));
578         }
579         // Perform setup.
580         setupDelete();
581
582         // Submit the request to the service and store the response.
583         DimensionClient client = new DimensionClient();
584         //TENANT_2_USER of TENANT_2 is not allowed to delete the resource of TENANT_1
585         client.setAuth(true, TENANT_2_USER, true, TENANT_2_USER, true);
586         ClientResponse<Response> res = client.delete(TENANT_RESOURCE_1);
587         int statusCode = res.getStatus();
588
589         // Check the status code of the response: does it match
590         // the expected response(s)?
591         if (logger.isDebugEnabled()) {
592             logger.debug(testName + ": status = " + statusCode);
593         }
594         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
595                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
596         //going to incorrect Nuxeo domain would give DocumentNotFoundException
597         //instead of giving FORBIDDEN
598         Assert.assertEquals(statusCode, Response.Status.NOT_FOUND.getStatusCode());
599     }
600
601     // ---------------------------------------------------------------
602     // Utility tests : tests of code used in tests above
603     // ---------------------------------------------------------------
604     /**
605      * Tests the code for manually submitting data that is used by several
606      * of the methods above.
607      */
608     @Test(dependsOnMethods = {"create"})
609     public void testSubmitRequest() throws Exception {
610     }
611
612     // ---------------------------------------------------------------
613     // Utility methods used by tests above
614     // ---------------------------------------------------------------
615     @AfterClass(alwaysRun = true)
616     public void cleanUp() {
617         if (logger.isDebugEnabled()) {
618             testBanner("cleanUp", CLASS_NAME);
619         }
620         setupDelete();
621         String noTest = System.getProperty("noTestCleanup");
622         if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
623             if (logger.isDebugEnabled()) {
624                 logger.debug("Skipping Cleanup phase ...");
625             }
626             return;
627         }
628         if (logger.isDebugEnabled()) {
629             logger.debug("Cleaning up temporary resources created for testing ...");
630         }
631
632         //tenant admin users are used to create accounts, roles and permissions and relationships
633         //assumption : two tenant admin users exist before running this test
634
635         //FIXME delete on permission role deletes all roles associated with the permission
636         //this would delete association with ROLE_ADMINISTRATION too
637         //deletePermissionRoles();
638         deleteAccountRoles();
639         //FIXME delete on permission role deletes all roles associated with the permission
640         //this would delete association with ROLE_ADMINISTRATION too
641         //deletePermissions();
642         deleteRoles();
643         deleteAccounts();
644     }
645
646     private void deletePermissionRoles() {
647
648         //first delete relationships between the entities
649         for (String tenantId : tenantPermissions.keySet()) {
650             PermissionValue pv = tenantPermissions.get(tenantId);
651             deletePermissionRole(tenantId, pv.getPermissionId());
652         }
653     }
654
655     private void deleteAccountRoles() {
656         for (String tenantId : tenantAccounts.keySet()) {
657             AccountValue av = tenantAccounts.get(tenantId);
658             deleteAccountRole(tenantId, av.getAccountId());
659         }
660     }
661
662     private void deletePermissions() {
663         for (String tenantId : tenantPermissions.keySet()) {
664             PermissionValue pv = tenantPermissions.get(tenantId);
665             deletePermission(tenantId, pv.getPermissionId());
666         }
667     }
668
669     private void deleteRoles() {
670         for (String tenantId : tenantRoles.keySet()) {
671             RoleValue rv = tenantRoles.get(tenantId);
672             deleteRole(tenantId, rv.getRoleId());
673         }
674     }
675
676     private void deleteAccounts() {
677
678         for (String tenantId : tenantAccounts.keySet()) {
679             AccountValue av = tenantAccounts.get(tenantId);
680             deleteAccount(tenantId, av.getAccountId());
681         }
682     }
683
684     private String createPermission(String tenantId, String resName,
685             List<PermissionAction> actions, EffectType effect) {
686         setupCreate();
687         PermissionClient permClient = new PermissionClient();
688         UserInfo ui = tenantAdminUsers.get(tenantId);
689         permClient.setAuth(true, ui.userName, true, ui.password, true);
690         Permission permission = PermissionFactory.createPermissionInstance(resName,
691                 "default permissions for " + resName,
692                 actions, effect, true, true, true);
693         permission.setTenantId(tenantId);
694         ClientResponse<Response> res = permClient.create(permission);
695         int statusCode = res.getStatus();
696         if (logger.isDebugEnabled()) {
697             logger.debug("createPermission: resName=" + resName
698                     + " status = " + statusCode);
699         }
700         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
701                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
702         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
703         res.releaseConnection();
704         return extractId(res);
705     }
706
707     private void deletePermission(String tenantId, String permId) {
708         setupDelete();
709         PermissionClient permClient = new PermissionClient();
710         UserInfo ui = tenantAdminUsers.get(tenantId);
711         permClient.setAuth(true, ui.userName, true, ui.password, true);
712         ClientResponse<Response> res = permClient.delete(permId);
713         int statusCode = res.getStatus();
714         if (logger.isDebugEnabled()) {
715             logger.debug("deletePermission: delete permission id="
716                     + permId + " status=" + statusCode);
717         }
718         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
719                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
720         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
721         res.releaseConnection();
722     }
723
724     private String createRole(String tenantId, String roleName) {
725         setupCreate();
726         RoleClient roleClient = new RoleClient();
727         UserInfo ui = tenantAdminUsers.get(tenantId);
728         roleClient.setAuth(true, ui.userName, true, ui.password, true);
729         Role role = RoleFactory.createRoleInstance(roleName,
730                 "role for " + roleName, true);
731         role.setTenantId(tenantId);
732         ClientResponse<Response> res = roleClient.create(role);
733         int statusCode = res.getStatus();
734         if (logger.isDebugEnabled()) {
735             logger.debug("createRole: name=" + roleName
736                     + " status = " + statusCode);
737         }
738         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
739                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
740         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
741         res.releaseConnection();
742         return extractId(res);
743     }
744
745     private void deleteRole(String tenantId, String roleId) {
746         setupDelete();
747         RoleClient roleClient = new RoleClient();
748         UserInfo ui = tenantAdminUsers.get(tenantId);
749         roleClient.setAuth(true, ui.userName, true, ui.password, true);
750         ClientResponse<Response> res = roleClient.delete(roleId);
751         int statusCode = res.getStatus();
752         if (logger.isDebugEnabled()) {
753             logger.debug("deleteRole: delete role id=" + roleId
754                     + " status=" + statusCode);
755         }
756         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
757                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
758         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
759         res.releaseConnection();
760     }
761
762     private String createAccount(String tenantId, String userName, String email) {
763         setupCreate();
764         AccountClient accountClient = new AccountClient();
765         UserInfo ui = tenantAdminUsers.get(tenantId);
766         accountClient.setAuth(true, ui.userName, true, ui.password, true);
767         AccountsCommon account = AccountFactory.createAccountInstance(
768                 userName, userName, userName, email, tenantId,
769                 true, false, true, true);
770         ClientResponse<Response> res = accountClient.create(account);
771         int statusCode = res.getStatus();
772         if (logger.isDebugEnabled()) {
773             logger.debug("createAccount: tenantId=" + tenantId + " userName=" + userName
774                     + " status = " + statusCode);
775         }
776         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
777                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
778         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
779         res.releaseConnection();
780         return extractId(res);
781     }
782
783     private void deleteAccount(String tenantId, String accId) {
784         setupDelete();
785         AccountClient accClient = new AccountClient();
786         UserInfo ui = tenantAdminUsers.get(tenantId);
787         accClient.setAuth(true, ui.userName, true, ui.password, true);
788         ClientResponse<Response> res = accClient.delete(accId);
789         int statusCode = res.getStatus();
790         if (logger.isDebugEnabled()) {
791             logger.debug("deleteAccount: delete account id="
792                     + accId + " status=" + statusCode);
793         }
794         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
795                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
796         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
797         res.releaseConnection();
798     }
799
800     private String createAccountRole(String tenantId, AccountValue av,
801             Collection<RoleValue> rvs) {
802         setupCreate();
803
804         // Submit the request to the service and store the response.
805         AccountRole accRole = AccountRoleFactory.createAccountRoleInstance(
806                 av, rvs, true, true);
807         AccountRoleClient client = new AccountRoleClient();
808         UserInfo ui = tenantAdminUsers.get(tenantId);
809         client.setAuth(true, ui.userName, true, ui.password, true);
810         ClientResponse<Response> res = client.create(av.getAccountId(), accRole);
811         int statusCode = res.getStatus();
812
813         if (logger.isDebugEnabled()) {
814             logger.debug("createAccountRole: status = " + statusCode);
815         }
816         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
817                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
818         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
819         res.releaseConnection();
820         return extractId(res);
821     }
822
823     private void deleteAccountRole(String tenantId, String accountId) {
824         // Perform setup.
825         setupDelete();
826
827         // Submit the request to the service and store the response.
828         AccountRoleClient client = new AccountRoleClient();
829         UserInfo ui = tenantAdminUsers.get(tenantId);
830         client.setAuth(true, ui.userName, true, ui.password, true);
831         ClientResponse<Response> res = client.delete(
832                 accountId, "123");
833         int statusCode = res.getStatus();
834
835         // Check the status code of the response: does it match
836         // the expected response(s)?
837         if (logger.isDebugEnabled()) {
838             logger.debug("deleteAccountRole: status = " + statusCode);
839         }
840         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
841                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
842         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
843         res.releaseConnection();
844     }
845
846     private String createPermissionRole(String tenantId, PermissionValue pv,
847             Collection<RoleValue> rvs) {
848         setupCreate();
849         List<RoleValue> rvls = new ArrayList<RoleValue>();
850         rvls.addAll(rvs);
851         PermissionRole permRole = PermissionRoleFactory.createPermissionRoleInstance(
852                 pv, rvls, true, true);
853         PermissionRoleClient client = new PermissionRoleClient();
854         UserInfo ui = tenantAdminUsers.get(tenantId);
855         client.setAuth(true, ui.userName, true, ui.password, true);
856         ClientResponse<Response> res = client.create(pv.getPermissionId(), permRole);
857         int statusCode = res.getStatus();
858
859         if (logger.isDebugEnabled()) {
860             logger.debug("createPermissionRole: status = " + statusCode);
861         }
862         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
863                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
864         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
865         res.releaseConnection();
866         return extractId(res);
867     }
868
869     private void deletePermissionRole(String tenantId, String permId) {
870
871         // Perform setup.
872         setupDelete();
873
874         // Submit the request to the service and store the response.
875         PermissionRoleClient client = new PermissionRoleClient();
876         UserInfo ui = tenantAdminUsers.get(tenantId);
877         client.setAuth(true, ui.userName, true, ui.password, true);
878         ClientResponse<Response> res = client.delete(permId, "123");
879         int statusCode = res.getStatus();
880
881         // Check the status code of the response: does it match
882         // the expected response(s)?
883         if (logger.isDebugEnabled()) {
884             logger.debug("deletePermissionRole : status = " + statusCode);
885         }
886         Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
887                 invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
888         Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
889         res.releaseConnection();
890     }
891 }