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