Here are the examples of the java api class com.redhat.rhn.domain.user.User taken from open source projects.
1. UserTestUtils#createUserInternal()
Project: spacewalk
File: UserTestUtils.java
File: UserTestUtils.java
private static User createUserInternal(String userName, boolean randomLogin) { UserFactory.getSession(); User usr = UserFactory.createUser(); if (randomLogin) { usr.setLogin(userName + TestUtils.randomString()); } else { usr.setLogin(userName); } usr.setPassword(TEST_PASSWORD); usr.setFirstNames("userName" + TestUtils.randomString()); usr.setLastName("userName" + TestUtils.randomString()); String prefix = (String) LocalizationService.getInstance().availablePrefixes().toArray()[0]; usr.setPrefix(prefix); usr.setEmail("[email protected]"); return usr; }
2. MigrationManagerTest#testUpdateAdminRelationships()
Project: spacewalk
File: MigrationManagerTest.java
File: MigrationManagerTest.java
public void testUpdateAdminRelationships() throws Exception { for (User origOrgAdmin : origOrgAdmins) { assertTrue(origOrgAdmin.getServers().contains(server)); } for (User destOrgAdmin : destOrgAdmins) { assertFalse(destOrgAdmin.getServers().contains(server)); } MigrationManager.updateAdminRelationships(origOrg, destOrg, server); for (User origOrgAdmin : origOrgAdmins) { assertFalse(origOrgAdmin.getServers().contains(server)); } for (User destOrgAdmin : destOrgAdmins) { assertTrue(destOrgAdmin.getServers().contains(server)); } }
3. UserManagerTest#testLookupUserOrgBoundaries()
Project: spacewalk
File: UserManagerTest.java
File: UserManagerTest.java
public void testLookupUserOrgBoundaries() { User usr1 = UserTestUtils.findNewUser("testUser", "testOrg1", true); User usr2 = UserTestUtils.findNewUser("testUser", "testOrg2"); User usr3 = UserTestUtils.createUser("testUser123", usr1.getOrg().getId()); try { UserManager.lookupUser(usr1, usr2.getLogin()); String msg = "User1 of Org Id = %s should" + "not be able to access Usr2 of Org Id= %s"; fail(String.format(msg, usr1.getOrg().getId(), usr2.getOrg().getId())); } catch (LookupException e) { } assertEquals(usr3, UserManager.lookupUser(usr1, usr3.getLogin())); }
4. UserManagerTest#testListRolesAssignable()
Project: spacewalk
File: UserManagerTest.java
File: UserManagerTest.java
public void testListRolesAssignable() throws Exception { User user = UserTestUtils.findNewUser(); assertTrue(UserManager.listRolesAssignableBy(user).isEmpty()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserManager.storeUser(user); assertTrue(UserManager.listRolesAssignableBy(user).contains(RoleFactory.CONFIG_ADMIN)); assertFalse(UserManager.listRolesAssignableBy(user).contains(RoleFactory.SAT_ADMIN)); User sat = UserTestUtils.createSatAdminInOrgOne(); assertTrue(UserManager.listRolesAssignableBy(sat).contains(RoleFactory.SAT_ADMIN)); }
5. ServerGroupManagerTest#testAccess()
Project: spacewalk
File: ServerGroupManagerTest.java
File: ServerGroupManagerTest.java
public void testAccess() throws Exception { user.addPermanentRole(RoleFactory.SYSTEM_GROUP_ADMIN); ManagedServerGroup sg = manager.create(user, NAME, DESCRIPTION); assertTrue(manager.canAccess(user, sg)); User newUser = UserTestUtils.createUser("testDiffUser", user.getOrg().getId()); assertFalse(manager.canAccess(newUser, sg)); List admins = new ArrayList(); admins.add(newUser); manager.associateAdmins(sg, admins, user); assertTrue(manager.canAccess(newUser, sg)); manager.dissociateAdmins(sg, admins, user); assertFalse(manager.canAccess(newUser, sg)); User orgAdmin = UserTestUtils.createUser("testDiffUser", user.getOrg().getId()); orgAdmin.addPermanentRole(RoleFactory.ORG_ADMIN); assertTrue(manager.canAccess(orgAdmin, sg)); }
6. EditAddressSetupActionTest#testPerformExecuteWithAddr()
Project: spacewalk
File: EditAddressSetupActionTest.java
File: EditAddressSetupActionTest.java
public void testPerformExecuteWithAddr() throws Exception { EditAddressSetupAction action = new EditAddressSetupAction(); ActionHelper sah = new ActionHelper(); sah.setUpAction(action); sah.getRequest().setupAddParameter("type", Address.TYPE_MARKETING); User user = sah.getUser(); user.setPhone("555-1212"); user.setFax("555-1212"); setupExpectations(sah.getForm(), user); sah.executeAction(); assertNotNull(sah.getForm().get("uid")); sah.getForm().verify(); }
7. RoleTest#testOrgAdminRole()
Project: spacewalk
File: RoleTest.java
File: RoleTest.java
/** * We need to make sure that the implied roles are added when a user * is an org admin. */ public void testOrgAdminRole() throws Exception { User usr = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Org o1 = usr.getOrg(); // Add the CHANNEL_ADMIN role to the Org o1.addRole(RoleFactory.CHANNEL_ADMIN); o1 = OrgFactory.save(o1); usr.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(usr); // Now check to see if the user gets the implied CHANNEL_ADMIN role User usr2 = UserFactory.lookupById(usr.getId()); assertTrue(usr2.hasRole(RoleFactory.CHANNEL_ADMIN)); }
8. RoleTest#testUserAddRole()
Project: spacewalk
File: RoleTest.java
File: RoleTest.java
/** * Test to see if we can add a role to a user */ public void testUserAddRole() { User usr = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Org o1 = usr.getOrg(); o1.addRole(RoleFactory.CHANNEL_ADMIN); o1 = OrgFactory.save(o1); assertFalse(usr.hasRole(RoleFactory.CHANNEL_ADMIN)); usr.addPermanentRole(RoleFactory.CHANNEL_ADMIN); assertTrue(usr.hasRole(RoleFactory.CHANNEL_ADMIN)); UserFactory.save(usr); User usr2 = UserFactory.lookupById(usr.getId()); assertTrue(usr2.hasRole(RoleFactory.CHANNEL_ADMIN)); }
9. CreateUserAction#createIntoOrg()
Project: spacewalk
File: CreateUserAction.java
File: CreateUserAction.java
private User createIntoOrg(RequestContext requestContext, CreateUserCommand command, String password, ActionMessages msgs) { User creator = requestContext.getCurrentUser(); Org org = creator.getOrg(); command.setOrg(org); command.setCompany(creator.getCompany()); command.setMakeOrgAdmin(false); command.setMakeSatAdmin(false); command.storeNewUser(); User newUser = command.getUser(); msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.userCreatedIntoOrg", StringEscapeUtils.escapeHtml(newUser.getLogin()), newUser.getEmail())); return newUser; }
10. BaseSystemListActionTestCase#testSelectAll()
Project: spacewalk
File: BaseSystemListActionTestCase.java
File: BaseSystemListActionTestCase.java
public void testSelectAll() throws Exception { BaseSystemListAction action = createAction(); ActionHelper ah = new ActionHelper(); ah.setUpAction(action); ah.setupProcessPagination(); User user = ah.getUser(); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserManager.storeUser(user); ah.getRequest().setupAddParameter("items_on_page", (String[]) null); ah.getRequest().setupAddParameter("items_selected", (String[]) null); ah.executeAction("selectall"); // This test only ensures that 'Select All' doesn't blow up. // To really test that something got selected, we would have to create an // appropriate system for each of the subclasses. The fact that the set cleaner // doesn't clean servers that should stay in the set is already tested by // testAddOne() }
11. BaseSystemListActionTestCase#testAddOne()
Project: spacewalk
File: BaseSystemListActionTestCase.java
File: BaseSystemListActionTestCase.java
public void testAddOne() throws Exception { BaseSystemListAction action = createAction(); ActionHelper ah = new ActionHelper(); ah.setUpAction(action); ah.setupProcessPagination(); User user = ah.getUser(); user.addPermanentRole(RoleFactory.ORG_ADMIN); // Create a server that can be put in the set. Note that the // server is not set up entirely right for subclasses, which would // only display servers with certain attributes, e.g. a satellite. // But this test is only concerned with keeping a server in the set // w/o having it cleaned up by the set cleaner Server server = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); UserManager.storeUser(user); String sid = server.getId().toString(); ah.getRequest().setupAddParameter("items_on_page", (String[]) null); ah.getRequest().setupAddParameter("items_selected", new String[] { sid }); ah.executeAction("updatelist"); RhnSetActionTest.verifyRhnSetData(ah.getUser(), RhnSetDecl.SYSTEMS, 1); }
12. InProgressSystemsActionTest#testSelectAll()
Project: spacewalk
File: InProgressSystemsActionTest.java
File: InProgressSystemsActionTest.java
public void testSelectAll() throws Exception { InProgressSystemsAction action = new InProgressSystemsAction(); ActionHelper ah = new ActionHelper(); ah.setUpAction(action); ah.setupProcessPagination(); User user = ah.getUser(); user.addPermanentRole(RoleFactory.ORG_ADMIN); Action a = ActionFactoryTest.createAction(user, ActionFactory.TYPE_HARDWARE_REFRESH_LIST); for (int i = 0; i < 4; i++) { Server server = ServerFactoryTest.createTestServer(user, true); ServerActionTest.createServerAction(server, a); } ah.getRequest().setupAddParameter("aid", a.getId().toString()); //stupid mock ah.getRequest().setupAddParameter("aid", a.getId().toString()); ah.getRequest().setupAddParameter("items_on_page", (String[]) null); ah.getRequest().setupAddParameter("items_selected", (String[]) null); ah.executeAction("selectall"); RhnSetActionTest.verifyRhnSetData(user.getId(), "unscheduleaction", 4); }
13. UserTest#testServerPerms()
Project: spacewalk
File: UserTest.java
File: UserTest.java
public void testServerPerms() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server server = ServerTestUtils.createTestSystem(user); assertEquals(1, user.getServers().size()); assertTrue(user.getServers().contains(server)); user.removeServer(server); user = UserFactory.lookupById(user.getId()); assertEquals(0, user.getServers().size()); }
14. UserTest#testSystemGroupMethods()
Project: spacewalk
File: UserTest.java
File: UserTest.java
public void testSystemGroupMethods() { User usr = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); assertEquals(0, usr.getDefaultSystemGroupIds().size()); // We currently don't have a way in the Java code to // add SystemGroups, we can only update pre-existing ones // so for now this test can only see if it correctly can // call these methods vs creating new SysGroups and adding // them to the set. usr.setDefaultSystemGroupIds(usr.getDefaultSystemGroupIds()); assertNotNull(usr.getDefaultSystemGroupIds()); }
15. UserFactoryTest#testLookupByLogin()
Project: spacewalk
File: UserFactoryTest.java
File: UserFactoryTest.java
public void testLookupByLogin() throws Exception { Long id = UserTestUtils.createUser("testUser", "testOrg" + this.getClass().getSimpleName()); User usr = UserFactory.lookupById(id); String createdLogin = usr.getLogin(); assertNotNull(usr); User usrByLogin = UserFactory.lookupByLogin(usr.getLogin()); assertNotNull(usrByLogin); assertNotNull(usrByLogin.getLogin()); assertEquals(usrByLogin.getLogin(), createdLogin); assertNotNull(usrByLogin.getOrg()); }
16. ProxyServerTest#testProxyServer()
Project: spacewalk
File: ProxyServerTest.java
File: ProxyServerTest.java
public void testProxyServer() throws Exception { User user = UserTestUtils.findNewUser("testuser", "testorg"); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled(), ServerFactoryTest.TYPE_SERVER_PROXY); //flushAndEvict(server); Server s = ServerFactory.lookupById(server.getId()); assertNotNull("Server not found", s); assertFalse(s.isSatellite()); assertTrue(s.isProxy()); }
17. RoleTest#testUserAddRoleNotInOrg()
Project: spacewalk
File: RoleTest.java
File: RoleTest.java
/** * Test to make sure you can't add a Role to a User who's Org * doesn't have that Role. */ public void testUserAddRoleNotInOrg() { User usr = UserFactory.createUser(); Org org = OrgFactory.createOrg(); org.setName("testOrg" + this.getClass().getSimpleName()); usr.setOrg(org); assertFalse(usr.hasRole(RoleFactory.CHANNEL_ADMIN)); boolean failed = false; try { usr.addPermanentRole(RoleFactory.CHANNEL_ADMIN); } catch (IllegalArgumentException iae) { failed = true; } assertTrue(failed); }
18. SystemManagerTest#testSystemWithFeature()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testSystemWithFeature() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); PageControl pc = new PageControl(); pc.setStart(1); pc.setPageSize(20); DataResult<SystemOverview> systems = SystemManager.systemsWithFeature(user, ServerConstants.FEATURE_KICKSTART, pc); int origCount = systems.size(); user.addPermanentRole(RoleFactory.ORG_ADMIN); // Create a test server so we have one in the list. Server s = ServerFactoryTest.createTestServer(user, true); ServerFactory.save(s); systems = SystemManager.systemsWithFeature(user, ServerConstants.FEATURE_KICKSTART, pc); int newCount = systems.size(); assertNotNull(systems); assertFalse(systems.isEmpty()); assertTrue(systems.size() > 0); assertTrue(newCount > origCount); assertTrue(systems.size() <= 20); }
19. SystemManagerTest#testSystemList()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testSystemList() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); // Create a test server so we have one in the list. ServerFactoryTest.createTestServer(user, true); DataResult<SystemOverview> systems = SystemManager.systemList(user, null); assertNotNull(systems); assertFalse(systems.isEmpty()); assertTrue(systems.size() > 0); }
20. SystemManagerTest#testSystemsNotInSg()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testSystemsNotInSg() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); // Create a test server so we have one in the list. Server s = ServerFactoryTest.createTestServer(user, true); ManagedServerGroup sg = ServerGroupTestUtils.createManaged(user); DataResult<SystemOverview> systems = SystemManager.systemsNotInGroup(user, sg, null); assertNotNull(systems); assertFalse(systems.isEmpty()); assertTrue(serverInList(s, systems)); SystemManager.addServerToServerGroup(s, sg); systems = SystemManager.systemsNotInGroup(user, sg, null); assertFalse(serverInList(s, systems)); }
21. SystemManagerTest#testDeleteVirtualServer()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testDeleteVirtualServer() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server host = ServerTestUtils.createVirtHostWithGuests(user, 1); Server guest = (host.getGuests().iterator().next()).getGuestSystem(); Long sid = guest.getId(); Server test = SystemManager.lookupByIdAndUser(sid, user); assertNotNull(test); SystemManager.deleteServer(user, sid); try { test = SystemManager.lookupByIdAndUser(sid, user); fail("Found deleted server"); } catch (LookupException e) { } }
22. SystemManagerTest#testDeleteServer()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testDeleteServer() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server s = ServerFactoryTest.createTestServer(user, true); Long id = s.getId(); Server test = SystemManager.lookupByIdAndUser(id, user); assertNotNull(test); SystemManager.deleteServer(user, id); try { test = SystemManager.lookupByIdAndUser(id, user); fail("Found deleted server"); } catch (LookupException e) { } }
23. SystemManagerTest#testSnapshotServer()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testSnapshotServer() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerFactoryTest.createTestServer(user, true); Long id = server.getId(); assertTrue(SystemManager.serverHasFeature(id, "ftr_snapshotting")); assertEquals(new Integer(0), numberOfSnapshots(id)); SystemManager.snapshotServer(null, "test"); assertEquals(new Integer(0), numberOfSnapshots(id)); SystemManager.snapshotServer(server, "Testing snapshots"); assertEquals(new Integer(1), numberOfSnapshots(id)); }
24. OrgManagerTest#testOrgsInSat()
Project: spacewalk
File: OrgManagerTest.java
File: OrgManagerTest.java
/** * TestOrgsInsat * @throws Exception if error */ public void testOrgsInSat() throws Exception { User user = UserTestUtils.findNewUser("test-morg", "testorg-foo", true); Org o = user.getOrg(); // add satellite_admin since its not one of the implied roles o.addRole(RoleFactory.SAT_ADMIN); user.addPermanentRole(RoleFactory.SAT_ADMIN); UserFactory.save(user); UserTestUtils.addManagement(o); UserTestUtils.addVirtualization(o); DataList orgs = OrgManager.activeOrgs(user); assertNotNull(orgs); assertTrue(orgs.size() > 0); }
25. MigrationManager#updateAdminRelationships()
Project: spacewalk
File: MigrationManager.java
File: MigrationManager.java
/** * Update the org admin to server relationships in the originating and destination * orgs. * * @param fromOrg originating org where the server currently exists * @param toOrg destination org where the server will be migrated to * @param server Server to be migrated. */ public static void updateAdminRelationships(Org fromOrg, Org toOrg, Server server) { // the mix and it could take quite some time. for (User admin : fromOrg.getActiveOrgAdmins()) { admin.removeServer(server); UserFactory.save(admin); } // add the server to all org admins in the destination org for (User admin : toOrg.getActiveOrgAdmins()) { admin.addServer(server); UserFactory.save(admin); } }
26. ActionManagerTest#testSchedulePackageVerify()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testSchedulePackageVerify() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); assertNotNull(user); Server srvr = ServerFactoryTest.createTestServer(user, true); RhnSet set = RhnSetManager.createSet(user.getId(), "verify_package_list", SetCleanup.NOOP); assertNotNull(srvr); assertNotNull(set); Package pkg = PackageTest.createTestPackage(user.getOrg()); set.addElement(pkg.getPackageName().getId(), pkg.getPackageEvr().getId(), pkg.getPackageArch().getId()); RhnSetManager.store(set); PackageAction pa = ActionManager.schedulePackageVerify(user, srvr, set, new Date()); assertNotNull(pa); assertNotNull(pa.getId()); PackageAction pa1 = (PackageAction) ActionManager.lookupAction(user, pa.getId()); assertNotNull(pa1); assertEquals(pa, pa1); }
27. ActionManagerTest#testFailedSystems()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testFailedSystems() throws Exception { User user1 = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Action a1 = ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); ServerAction sa = (ServerAction) a1.getServerActions().toArray()[0]; sa.setStatus(ActionFactory.STATUS_FAILED); ActionFactory.save(a1); // Gotta be ORG_ADMIN to view failed systems user1.addPermanentRole(RoleFactory.ORG_ADMIN); // Here we have to commit the User because we added a Server // and need to update their rhnUserServerPerms table. This should be // mapped to hibernate so we don't have to do these two manual commits! UserFactory.save(user1); assertTrue(ActionManager.failedSystems(user1, a1, null).size() > 0); }
28. ActionManagerTest#testInProgressSystems()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testInProgressSystems() throws Exception { User user1 = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Action a1 = ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); ServerAction sa = (ServerAction) a1.getServerActions().toArray()[0]; sa.setStatus(ActionFactory.STATUS_QUEUED); ActionFactory.save(a1); // Gotta be ORG_ADMIN to view failed systems user1.addPermanentRole(RoleFactory.ORG_ADMIN); // Here we have to commit the User because we added a Server // and need to update their rhnUserServerPerms table. This should be // mapped to hibernate so we don't have to do these two manual commits! UserFactory.save(user1); DataResult dr = ActionManager.inProgressSystems(user1, a1, null); assertTrue(dr.size() > 0); assertTrue(dr.get(0) instanceof ActionedSystem); ActionedSystem as = (ActionedSystem) dr.get(0); as.setSecurityErrata(new Long(1)); assertNotNull(as.getSecurityErrata()); }
29. ActionManagerTest#testRecentlyScheduledActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testRecentlyScheduledActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Action parent = ActionFactoryTest.createAction(user, ActionFactory.TYPE_ERRATA); ServerAction child = ServerActionTest.createServerAction(ServerFactoryTest.createTestServer(user), parent); child.setStatus(ActionFactory.STATUS_COMPLETED); child.setCreated(new Date(System.currentTimeMillis())); parent.addServerAction(child); ActionFactory.save(parent); UserFactory.save(user); DataResult dr = ActionManager.recentlyScheduledActions(user, null, 30); assertNotEmpty(dr); }
30. ActionManagerTest#testCompletedActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testCompletedActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Action parent = ActionFactoryTest.createAction(user, ActionFactory.TYPE_ERRATA); ServerAction child = ServerActionTest.createServerAction(ServerFactoryTest.createTestServer(user), parent); child.setStatus(ActionFactory.STATUS_COMPLETED); parent.addServerAction(child); ActionFactory.save(parent); UserFactory.save(user); DataResult dr = ActionManager.completedActions(user, null); assertNotEmpty(dr); }
31. ActionManagerTest#testCancelActionWithParentFails()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testCancelActionWithParentFails() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); Action parent = createActionWithServerActions(user, 1); Action child = createActionWithServerActions(user, 1); child.setPrerequisite(parent); List actionList = createActionList(user, new Action[] { child }); try { ActionManager.cancelActions(user, actionList); fail("Exception not thrown when deleting action with a prerequisite."); } catch (ActionIsChildException e) { } }
32. ActionManagerTest#testCancelActionWithMultipleServerActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testCancelActionWithMultipleServerActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); Action parent = createActionWithServerActions(user, 2); List actionList = createActionList(user, new Action[] { parent }); assertServerActionCount(parent, 2); assertActionsForUser(user, 1); ActionManager.cancelActions(user, actionList); assertServerActionCount(parent, 0); // shouldn't have been deleted assertActionsForUser(user, 1); }
33. ActionManagerTest#testCancelActionWithChildren()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testCancelActionWithChildren() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); Action parent = createActionWithServerActions(user, 1); Action child = createActionWithServerActions(user, 1); child.setPrerequisite(parent); List actionList = createActionList(user, new Action[] { parent }); assertServerActionCount(parent, 1); assertActionsForUser(user, 2); ActionManager.cancelActions(user, actionList); assertServerActionCount(parent, 0); // shouldn't have been deleted assertActionsForUser(user, 2); }
34. ActionManagerTest#testSimpleCancelActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testSimpleCancelActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); Action parent = createActionWithServerActions(user, 1); List actionList = createActionList(user, new Action[] { parent }); assertServerActionCount(parent, 1); assertActionsForUser(user, 1); ActionManager.cancelActions(user, actionList); assertServerActionCount(parent, 0); // shouldn't have been deleted assertActionsForUser(user, 1); }
35. ActionManagerTest#testPendingActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testPendingActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Action parent = ActionFactoryTest.createAction(user, ActionFactory.TYPE_ERRATA); ServerAction child = ServerActionTest.createServerAction(ServerFactoryTest.createTestServer(user), parent); child.setStatus(ActionFactory.STATUS_QUEUED); parent.addServerAction(child); ActionFactory.save(parent); UserFactory.save(user); DataResult dr = ActionManager.pendingActions(user, null); Long actionid = new Long(parent.getId().longValue()); TestUtils.arraySearch(dr.toArray(), "getId", actionid); assertNotEmpty(dr); }
36. ActionManagerTest#testFailedActions()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testFailedActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Action parent = ActionFactoryTest.createAction(user, ActionFactory.TYPE_ERRATA); ServerAction child = ServerActionTest.createServerAction(ServerFactoryTest.createTestServer(user), parent); child.setStatus(ActionFactory.STATUS_FAILED); parent.addServerAction(child); ActionFactory.save(parent); UserFactory.save(user); DataResult dr = ActionManager.failedActions(user, null); assertNotEmpty(dr); }
37. ActionManagerTest#testLookupAction()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testLookupAction() throws Exception { User user1 = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user1.addPermanentRole(RoleFactory.ORG_ADMIN); Action a1 = ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); Long actionId = a1.getId(); //Users must have access to a server for the action to lookup the action Server s = ServerFactoryTest.createTestServer(user1, true); a1.addServerAction(ServerActionTest.createServerAction(s, a1)); ActionManager.storeAction(a1); Action a2 = ActionManager.lookupAction(user1, actionId); assertNotNull(a2); }
38. ActionManagerTest#testGetSystemGroups()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testGetSystemGroups() throws Exception { User user1 = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); user1.addPermanentRole(RoleFactory.ORG_ADMIN); // Here we have to commit the User because we added a Server // and need to update their rhnUserServerPerms table. This should be // mapped to hibernate so we don't have to do these two manual commits! UserFactory.save(user1); PageControl pc = new PageControl(); pc.setIndexData(false); pc.setFilterColumn("earliest"); pc.setStart(1); DataResult dr = ActionManager.pendingActions(user1, pc); assertNotNull(dr); assertTrue(dr.size() > 0); }
39. UserHandler#setReadOnly()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * @param loggedInUser The current user * @param login User to modify. * @param readOnly readOnly flag to set * @return 1 (should always succeed) * @xmlrpc.doc Sets whether the target user should have only read-only API access or * standard full scale access. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #param_desc("boolean", "readOnly", "Sets whether the target user should * have only read-only API access or standard full scale access.") * @xmlrpc.returntype #return_int_success() */ public int setReadOnly(User loggedInUser, String login, Boolean readOnly) { //Logged in user must be an org admin. ensureOrgAdmin(loggedInUser); User targetUser = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); if (!targetUser.isReadOnly()) { if (readOnly && targetUser.hasRole(RoleFactory.ORG_ADMIN) && targetUser.getOrg().numActiveOrgAdmins() < 2) { throw new InvalidOperationException("error.readonly_org_admin", targetUser.getOrg().getName()); } if (readOnly && targetUser.hasRole(RoleFactory.SAT_ADMIN) && SatManager.getActiveSatAdmins().size() < 2) { throw new InvalidOperationException("error.readonly_sat_admin"); } } targetUser.setReadOnly(readOnly); return 1; }
40. UserHandler#addRole()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Adds a role to the given user * @param loggedInUser The current user * @param login The login for the user you would like to add the role to * @param role The role you would like to give the user * @return Returns 1 if successful (exception otherwise) * @throws FaultException A FaultException is thrown if the user doesn't have access * to lookup the user corresponding to login or if the user does not exist. * * @xmlrpc.doc Adds a role to a user. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User login name to update.") * @xmlrpc.param #param_desc("string", "role", "Role label to add. Can be any of: * satellite_admin, org_admin, channel_admin, config_admin, system_group_admin, or * activation_key_admin.") * @xmlrpc.returntype #return_int_success() */ public int addRole(User loggedInUser, String login, String role) throws FaultException { validateRoleInputs(role, loggedInUser); if (RoleFactory.SAT_ADMIN.getLabel().equals(role)) { return modifySatAdminRole(loggedInUser, login, true); } User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); // Retrieve the role object corresponding to the role label passed in and // add to user Role r = RoleFactory.lookupByLabel(role); target.addPermanentRole(r); UserManager.storeUser(target); return 1; }
41. UserSerializer#doSerialize()
Project: spacewalk
File: UserSerializer.java
File: UserSerializer.java
/** * {@inheritDoc} */ protected void doSerialize(Object value, Writer output, XmlRpcSerializer serializer) throws XmlRpcException, IOException { SerializerHelper helper = new SerializerHelper(serializer); User user = (User) value; helper.add("id", user.getId()); helper.add("login", user.getLogin()); helper.add("login_uc", user.getLoginUc()); if (user.isDisabled()) { helper.add("enabled", Boolean.FALSE); } else { helper.add("enabled", Boolean.TRUE); } helper.writeTo(output); }
42. ProxyHandlerTest#testDeactivateProxy()
Project: spacewalk
File: ProxyHandlerTest.java
File: ProxyHandlerTest.java
public void testDeactivateProxy() throws Exception { User user = UserTestUtils.findNewUser("testuser", "testorg"); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled(), ServerFactoryTest.TYPE_SERVER_PROXY); // TODO: need to actually create a valid proxy server, the // above doesn't come close to creating a REAL server. ClientCertificate cert = SystemManager.createClientCertificate(server); cert.validate(server.getSecret()); ProxyHandler ph = new ProxyHandler(); int rc = ph.deactivateProxy(cert.toString()); assertEquals(1, rc); }
43. ProxyHandlerTest#testActivateProxy()
Project: spacewalk
File: ProxyHandlerTest.java
File: ProxyHandlerTest.java
public void testActivateProxy() throws Exception { User user = UserTestUtils.findNewUser("testuser", "testorg"); ProxyHandler ph = new ProxyHandler(); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled(), ServerFactoryTest.TYPE_SERVER_NORMAL); ClientCertificate cert = SystemManager.createClientCertificate(server); cert.validate(server.getSecret()); int rc = ph.activateProxy(cert.toString(), "5.0"); assertEquals(1, rc); }
44. PreferencesLocaleHandler#setLocale()
Project: spacewalk
File: PreferencesLocaleHandler.java
File: PreferencesLocaleHandler.java
/** * Set the language the user will display in the user interface. * @param loggedInUser The current user * in user. * @param login The login of the user whose language will be changed. * @param locale Locale code to be used as the users language. * @return Returns 1 if successful (exception otherwise) * * @xmlrpc.doc Set a user's locale. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #param_desc("string", "locale", "Locale to set. (from listLocales)") * @xmlrpc.returntype #return_int_success() */ public int setLocale(User loggedInUser, String login, String locale) { LocalizationService ls = LocalizationService.getInstance(); List locales = ls.getConfiguredLocales(); Object o = CollectionUtils.find(locales, new LocalePredicate(locale)); if (o == null) { throw new InvalidLocaleCodeException(locale); } User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); target.setPreferredLocale(locale); UserManager.storeUser(target); return 1; }
45. PreferencesLocaleHandler#setTimeZone()
Project: spacewalk
File: PreferencesLocaleHandler.java
File: PreferencesLocaleHandler.java
/** * Set the TimeZone for the given user. * @param loggedInUser The current user * in user. * @param login The login of the user whose timezone will be changed. * @param tzid TimeZone id * @return Returns 1 if successful (exception otherwise) * * @xmlrpc.doc Set a user's timezone. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #param_desc("int", "tzid" "Timezone ID. (from listTimeZones)") * @xmlrpc.returntype #return_int_success() */ public int setTimeZone(User loggedInUser, String login, Integer tzid) { List tzs = UserManager.lookupAllTimeZones(); Object o = CollectionUtils.find(tzs, new TzPredicate(tzid)); if (o == null) { throw new InvalidTimeZoneException(tzid); } User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); target.setTimeZone((RhnTimeZone) o); UserManager.storeUser(target); return 1; }
46. VisibleSystemsListActionTest#testSelectAll()
Project: spacewalk
File: VisibleSystemsListActionTest.java
File: VisibleSystemsListActionTest.java
public void testSelectAll() throws Exception { Action action = new VisibleSystemsListAction(); ActionHelper ah = new ActionHelper(); ah.setUpAction(action); ah.setupClampListBounds(); User user = ah.getUser(); user.addPermanentRole(RoleFactory.ORG_ADMIN); TestUtils.saveAndFlush(user); ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); ah.getRequest().setupAddParameter("newset", (String[]) null); ah.getRequest().setupAddParameter("items_on_page", (String[]) null); ah.getRequest().setupAddParameter("items_selected", (String[]) null); ah.getRequest().setupAddParameter("uid", user.getId().toString()); RhnSetDecl.SYSTEMS.clear(user); assertTrue(0 == RhnSetDecl.SYSTEMS.get(user).size()); ah.executeAction("selectall"); assertTrue(0 < RhnSetDecl.SYSTEMS.get(user).size()); }
47. EditAddressActionTest#setUpSuccess()
Project: spacewalk
File: EditAddressActionTest.java
File: EditAddressActionTest.java
private void setUpSuccess() { action = new EditAddressAction(); mapping = new ActionMapping(); success = new ActionForward("success", "path", false); form = new RhnMockDynaActionForm("editAddressForm"); request = TestUtils.getRequestWithSessionAndUser(); response = new MockHttpServletResponse(); RequestContext requestContext = new RequestContext(request); // The logged in user needs to be the OrgAdmin of his Org in order // for him to be able to edit somebody else's address information. User loggedInUser = requestContext.getCurrentUser(); loggedInUser.addPermanentRole(RoleFactory.ORG_ADMIN); UserManager.storeUser(loggedInUser); usr = UserTestUtils.createUser("differentUser", loggedInUser.getOrg().getId()); // Have to grab the UID out of the request so we can reset it String userIdRaw = request.getParameter("uid"); userIdRaw = usr.getId().toString(); // Put it back into the Request request.setupAddParameter("uid", userIdRaw); }
48. ChangeEmailSetupActionTest#testChangeEmailSetupAction()
Project: spacewalk
File: ChangeEmailSetupActionTest.java
File: ChangeEmailSetupActionTest.java
public void testChangeEmailSetupAction() throws Exception { ChangeEmailSetupAction action = new ChangeEmailSetupAction(); ActionHelper sah = new ActionHelper(); sah.setUpAction(action); LocalizationService ls = LocalizationService.getInstance(); User user = sah.getUser(); //Test verified sah.getRequest().setupAddParameter("uid", ""); user.setEmail("[email protected]"); UserManager.storeUser(user); ActionForward result = sah.executeAction(); assertEquals(RhnHelper.DEFAULT_FORWARD, result.getName()); //If we are a satellite, then we should expect yourchangeemail.instructions //and message.Update assertEquals(ls.getMessage("yourchangeemail.instructions"), sah.getRequest().getAttribute("pageinstructions")); assertEquals(ls.getMessage("message.Update"), sah.getRequest().getAttribute("button_label")); }
49. UserManager#loginReadOnlyUser()
Project: spacewalk
File: UserManager.java
File: UserManager.java
/** * This method should be ONLY called when we need to authenticate read-only user * e.g. for purpose of the API calls * Login the user with the given username and password. * @param username User's login name * @param password User's unencrypted password. * @return Returns the user if login is successful, or null othewise. * @throws LoginException if login fails. The message is a string resource key. */ public static User loginReadOnlyUser(String username, String password) throws LoginException { try { loginUser(username, password); } catch (LoginException e) { if (!e.getMessage().equals("error.user_readonly")) { throw e; } } User user = UserFactory.lookupByLogin(username); user.authenticate(password); return performLoginActions(user); }
50. SystemManagerTest#testListCustomKeys()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testListCustomKeys() throws Exception { User admin = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); admin.addPermanentRole(RoleFactory.ORG_ADMIN); CustomDataKey key = new CustomDataKey(); key.setCreator(admin); key.setLabel("testdsfd"); key.setDescription("test desc"); key.setOrg(admin.getOrg()); key.setLastModifier(admin); HibernateFactory.getSession().save(key); List<CustomDataKeyOverview> list = SystemManager.listDataKeys(admin); assertTrue(1 == list.size()); CustomDataKeyOverview dataKey = list.get(0); assertEquals(key.getLabel(), dataKey.getLabel()); }
51. SystemManagerTest#testRegisteredList()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testRegisteredList() throws Exception { User user = UserTestUtils.findNewUser(TestStatics.TESTUSER, TestStatics.TESTORG); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); ServerGroup group = ServerGroupTest.createTestServerGroup(user.getOrg(), null); SystemManager.addServerToServerGroup(server, group); ServerFactory.save(server); DataResult<SystemOverview> dr = SystemManager.registeredList(user, null, 0); assertNotEmpty(dr); }
52. SystemManagerTest#testGetSsmSystemsSubscribedToChannel()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testGetSsmSystemsSubscribedToChannel() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); UserFactory.save(user); Server s = ServerTestUtils.createTestSystem(user); RhnSetDecl.SYSTEMS.clear(user); RhnSet set = RhnSetDecl.SYSTEMS.get(user); set.addElement(s.getId()); RhnSetManager.store(set); List<Map<String, Object>> systems = SystemManager.getSsmSystemsSubscribedToChannel(user, s.getBaseChannel().getId()); assertEquals(1, systems.size()); Map<String, Object> result1 = systems.get(0); assertEquals(s.getName(), result1.get("name")); assertEquals(s.getId(), result1.get("id")); }
53. SystemManagerTest#testEntitleServer()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
/** * Tests adding and removing entitlement on a server * @throws Exception if something goes wrong */ public void testEntitleServer() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); user.addPermanentRole(RoleFactory.ORG_ADMIN); Server server = ServerTestUtils.createTestSystem(user); ChannelTestUtils.setupBaseChannelForVirtualization(user, server.getBaseChannel()); UserTestUtils.addVirtualization(user.getOrg()); TestUtils.saveAndFlush(user.getOrg()); assertTrue(SystemManager.canEntitleServer(server, EntitlementManager.VIRTUALIZATION)); boolean hasErrors = SystemManager.entitleServer(server, EntitlementManager.VIRTUALIZATION).hasErrors(); assertFalse(hasErrors); assertTrue(server.hasEntitlement(EntitlementManager.VIRTUALIZATION)); // Removal SystemManager.removeServerEntitlement(server.getId(), EntitlementManager.VIRTUALIZATION); server = (Server) reload(server); assertFalse(server.hasEntitlement(EntitlementManager.VIRTUALIZATION)); }
54. KickstartCleanupTest#createSession()
Project: spacewalk
File: KickstartCleanupTest.java
File: KickstartCleanupTest.java
private static KickstartSession createSession() throws Exception { User user = UserTestUtils.findNewUser("testUser", "ksSessionOrg"); KickstartData k = KickstartDataTest.createTestKickstartData(user.getOrg()); Server s = ServerFactoryTest.createTestServer(user); KickstartSessionState state = lookupByLabel("injected"); KickstartSession ksession = new KickstartSession(); ksession.setKsdata(k); ksession.setKickstartMode("label"); ksession.setKstree(KickstartableTreeTest.createTestKickstartableTree()); ksession.setOrg(k.getOrg()); ksession.setState(state); ksession.setCreated(new Date()); ksession.setModified(new Date()); ksession.setPackageFetchCount(new Long(0)); ksession.setDeployConfigs(Boolean.FALSE); ksession.setOldServer(s); ksession.setNewServer(s); KickstartVirtualizationType type = KickstartFactory.lookupKickstartVirtualizationTypeByLabel(KickstartVirtualizationType.XEN_PARAVIRT); ksession.setVirtualizationType(type); TestUtils.saveAndFlush(ksession); return ksession; }
55. UserManager#lookupUser()
Project: spacewalk
File: UserManager.java
File: UserManager.java
/** * Retrieve the specified user, assuming that the User making the request * has the required permissions. * @param user The user making the lookup request * @param login The login of the user to lookup. * @return the specified user. */ public static User lookupUser(User user, String login) { User returnedUser = null; if (login == null) { return null; } if (user.getLogin().equals(login)) { return user; } LocalizationService ls = LocalizationService.getInstance(); if (!user.hasRole(RoleFactory.ORG_ADMIN)) { //Throw an exception with a nice error message so the user //knows what went wrong. PermissionException pex = new PermissionException("Lookup user requires Org Admin"); pex.setLocalizedTitle(ls.getMessage("permission.jsp.title.lookupuser")); pex.setLocalizedSummary(ls.getMessage("permission.jsp.summary.lookupuser")); throw pex; } returnedUser = UserFactory.lookupByLogin(user, login); return returnedUser; }
56. UserManager#deleteUser()
Project: spacewalk
File: UserManager.java
File: UserManager.java
/** * Deletes a User * @param loggedInUser The user doing the deleting * @param targetUid The id for the user we're deleting */ public static void deleteUser(User loggedInUser, Long targetUid) { if (!loggedInUser.hasRole(RoleFactory.ORG_ADMIN)) { //Throw an exception with a nice error message so the user //knows what went wrong. LocalizationService ls = LocalizationService.getInstance(); PermissionException pex = new PermissionException("Deleting a user requires an Org Admin."); pex.setLocalizedTitle(ls.getMessage("permission.jsp.title.deleteuser")); pex.setLocalizedSummary(ls.getMessage("permission.jsp.summary.deleteuser")); throw pex; } // Do not allow deletion of the last Satellite Administrator: User toDelete = UserFactory.lookupById(loggedInUser, targetUid); if (!toDelete.isDisabled() && toDelete.hasRole(RoleFactory.SAT_ADMIN)) { if (SatManager.getActiveSatAdmins().size() == 1) { log.warn("Cannot delete the last Satellite Administrator"); throw new DeleteSatAdminException(toDelete); } } UserFactory.deleteUser(targetUid); }
57. UserManagerTest#testSystemSearchResults()
Project: spacewalk
File: UserManagerTest.java
File: UserManagerTest.java
public void testSystemSearchResults() throws Exception { User user = UserTestUtils.findNewUser(TestStatics.TESTUSER, TestStatics.TESTORG); Server s = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); s.setDescription("Test Description Value"); List<Long> ids = new ArrayList<Long>(); ids.add(s.getId()); DataResult<SystemSearchResult> dr = UserManager.visibleSystemsAsDtoFromList(user, ids); assertTrue(dr.size() >= 1); dr.elaborate(Collections.EMPTY_MAP); SystemSearchResult sr = dr.get(0); System.err.println("sr.getDescription() = " + sr.getDescription()); System.err.println("sr.getHostname() = " + sr.getHostname()); assertNotNull(sr.getDescription()); //assertTrue(sr.getHostname() != null); }
58. UserManagerTest#testVisibleSystemsAsDtoFromList()
Project: spacewalk
File: UserManagerTest.java
File: UserManagerTest.java
public void testVisibleSystemsAsDtoFromList() throws Exception { User user = UserTestUtils.findNewUser(TestStatics.TESTUSER, TestStatics.TESTORG); Server s = ServerFactoryTest.createTestServer(user, true, ServerConstants.getServerGroupTypeEnterpriseEntitled()); List<Long> ids = new ArrayList<Long>(); ids.add(s.getId()); List<SystemSearchResult> dr = UserManager.visibleSystemsAsDtoFromList(user, ids); assertTrue(dr.size() >= 1); }
59. UserManagerTest#testUsersInSet()
Project: spacewalk
File: UserManagerTest.java
File: UserManagerTest.java
public void testUsersInSet() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); RhnSet set = RhnSetManager.createSet(user.getId(), "test_user_list", SetCleanup.NOOP); for (int i = 0; i < 5; i++) { User usr = UserTestUtils.createUser("testBob", user.getOrg().getId()); set.addElement(usr.getId()); } RhnSetManager.store(set); PageControl pc = new PageControl(); pc.setStart(1); pc.setPageSize(10); DataResult dr = UserManager.usersInSet(user, "test_user_list", pc); assertEquals(5, dr.size()); assertTrue(dr.iterator().hasNext()); assertTrue(dr.iterator().next() instanceof UserOverview); UserOverview m = (UserOverview) (dr.iterator().next()); assertNotNull(m.getUserLogin()); }
60. UpdateUserCommandTest#assertPassword()
Project: spacewalk
File: UpdateUserCommandTest.java
File: UpdateUserCommandTest.java
private void assertPassword(String password, UpdateUserCommand cmd) { cmd.setPassword(password); User user = cmd.updateUser(); assertNotNull(user); // can't do this if we've encrypted the passwords if (!Config.get().getBoolean(ConfigDefaults.WEB_ENCRYPTED_PASSWORDS)) { String savedPassword = user.getPassword(); user.setPassword(password); assertEquals(savedPassword, user.getPassword()); } }
61. UpdateUserCommandTest#testPrefix()
Project: spacewalk
File: UpdateUserCommandTest.java
File: UpdateUserCommandTest.java
public void testPrefix() { command.setPrefix("Miss"); User user = command.updateUser(); assertNotNull(user); assertEquals("Miss", user.getPrefix()); command.setPrefix("Miss."); assertCommandThrows(IllegalArgumentException.class, command); command.setPrefix("Master of my Domain"); assertCommandThrows(IllegalArgumentException.class, command); command.setPrefix("King"); assertCommandThrows(IllegalArgumentException.class, command); }
62. CreateUserCommandTest#testStore()
Project: spacewalk
File: CreateUserCommandTest.java
File: CreateUserCommandTest.java
public void testStore() { Org org = UserTestUtils.findNewOrg("testorg"); String login = TestUtils.randomString(); command.setLogin(login); command.setPassword("password"); command.setEmail("[email protected]"); command.setPrefix("Dr."); command.setFirstNames("Chuck Norris"); command.setLastName("Texas Ranger"); command.setOrg(org); command.setCompany("Test company"); Object[] errors = command.validate(); assertEquals(0, errors.length); command.storeNewUser(); Long uid = command.getUser().getId(); assertNotNull(uid); User result = UserFactory.lookupById(uid); assertEquals(login, result.getLogin()); assertEquals(PageSizeDecorator.getDefaultPageSize(), result.getPageSize()); }
63. SystemManagerTest#testListDuplicatesByHostname()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testListDuplicatesByHostname() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); String[] hostnames = { "DUPHOST", "notADup", "duphost" }; for (String name : hostnames) { Server s1 = ServerFactoryTest.createTestServer(user, true); Network net = new Network(); net.setHostname("server_" + s1.getId()); net.setIpaddr("192.168.1.1"); net.setServer(s1); s1.addNetwork(net); setHostname(s1, name); } List<SystemOverview> list = SystemManager.listDuplicatesByHostname(user, "duphost"); assertTrue(list.size() == 2); DataResult<SystemOverview> dr = SystemManager.systemList(user, null); assertTrue(dr.size() == 3); }
64. SystemManagerTest#testInSet()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testInSet() throws Exception { User usr = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); RhnSet newrs = RhnSetManager.createSet(usr.getId(), "test_systems_list", SetCleanup.NOOP); for (int i = 0; i < 5; i++) { Server mySystem = ServerFactoryTest.createTestServer(usr, true); newrs.addElement(mySystem.getId()); } RhnSetManager.store(newrs); List<SystemOverview> dr = SystemManager.inSet(usr, newrs.getLabel()); assertEquals(5, dr.size()); assertTrue(dr.iterator().hasNext()); SystemOverview m = (dr.iterator().next()); assertNotNull(m.getName()); }
65. SystemManagerTest#testListInstalledPackage()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testListInstalledPackage() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server s = ServerFactoryTest.createTestServer(user); List<Map<String, Long>> list = SystemManager.listInstalledPackage("kernel", s); assertTrue(list.isEmpty()); InstalledPackage p = new InstalledPackage(); p.setArch(PackageFactory.lookupPackageArchByLabel("x86_64")); p.setName(PackageFactory.lookupOrCreatePackageByName("kernel")); p.setEvr(PackageEvrFactoryTest.createTestPackageEvr()); p.setServer(s); Set<InstalledPackage> set = new HashSet<InstalledPackage>(); set.add(p); s.setPackages(set); ServerFactory.save(s); list = SystemManager.listInstalledPackage("kernel", s); assertTrue(list.size() == 1); assertEquals(list.get(0).get("name_id"), p.getName().getId()); assertEquals(list.get(0).get("evr_id"), p.getEvr().getId()); }
66. SystemManagerTest#testHasPackageAvailable()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testHasPackageAvailable() throws Exception { User admin = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server server = ServerTestUtils.createTestSystem(admin); Package pack = PackageTest.createTestPackage(admin.getOrg()); assertFalse(SystemManager.hasPackageAvailable(server, pack.getPackageName().getId(), pack.getPackageArch().getId(), pack.getPackageEvr().getId())); assertFalse(SystemManager.hasPackageAvailable(server, pack.getPackageName().getId(), null, pack.getPackageEvr().getId())); server.getBaseChannel().addPackage(pack); TestUtils.saveAndFlush(pack); assertTrue(SystemManager.hasPackageAvailable(server, pack.getPackageName().getId(), pack.getPackageArch().getId(), pack.getPackageEvr().getId())); assertTrue(SystemManager.hasPackageAvailable(server, pack.getPackageName().getId(), null, pack.getPackageEvr().getId())); }
67. SystemManagerTest#testDeleteNote()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testDeleteNote() throws Exception { // Setup User admin = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server server = ServerTestUtils.createTestSystem(admin); int sizeBefore = server.getNotes().size(); server.addNote(admin, "Test Subject", "Test Body"); ServerFactory.save(server); TestUtils.flushAndEvict(server); server = ServerFactory.lookupById(server.getId()); int sizeAfter = server.getNotes().size(); assertTrue(sizeAfter == (sizeBefore + 1)); Note deleteMe = server.getNotes().iterator().next(); // Test SystemManager.deleteNote(admin, server.getId(), deleteMe.getId()); // Verify server = ServerFactory.lookupById(server.getId()); int sizeAfterDelete = server.getNotes().size(); assertEquals(sizeBefore, sizeAfterDelete); }
68. SystemManagerTest#setupHostWithGuests()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
private Server setupHostWithGuests(int numGuests) throws Exception { Server host = ServerTestUtils.createVirtHostWithGuests(numGuests); host.setRam(HOST_RAM_MB); addCpuToServer(host); User user = host.getCreator(); UserTestUtils.addVirtualization(user.getOrg()); for (Iterator<VirtualInstance> it = host.getGuests().iterator(); it.hasNext(); ) { VirtualInstance vi = it.next(); Server guest = vi.getGuestSystem(); guest.addChannel(ChannelTestUtils.createBaseChannel(user)); ServerTestUtils.addVirtualization(user, guest); } return host; }
69. SystemManagerTest#testEntitleVirtForGuest()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testEntitleVirtForGuest() throws Exception { Server host = ServerTestUtils.createVirtHostWithGuest(); User user = host.getCreator(); UserTestUtils.addVirtualization(user.getOrg()); Server guest = (host.getGuests().iterator().next()).getGuestSystem(); guest.addChannel(ChannelTestUtils.createBaseChannel(user)); ServerTestUtils.addVirtualization(user, guest); assertTrue(SystemManager.entitleServer(guest, EntitlementManager.VIRTUALIZATION).hasErrors()); assertFalse(guest.hasEntitlement(EntitlementManager.VIRTUALIZATION)); }
70. SystemManagerTest#testCountPackageActions()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testCountPackageActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server server = ServerFactoryTest.createTestServer(user); assertEquals(0, SystemManager.countActions(server.getId())); Action action = ActionFactoryTest.createAction(user, ActionFactory.TYPE_PACKAGES_DELTA); ServerActionTest.createServerAction(server, action); ActionFactory.save(action); assertEquals(1, SystemManager.countActions(server.getId())); Action action2 = ActionFactoryTest.createAction(user, ActionFactory.TYPE_PACKAGES_AUTOUPDATE); ServerActionTest.createServerAction(server, action2); ActionFactory.save(action); assertEquals(2, SystemManager.countActions(server.getId())); }
71. SystemManagerTest#testCountActions()
Project: spacewalk
File: SystemManagerTest.java
File: SystemManagerTest.java
public void testCountActions() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Server server = ServerFactoryTest.createTestServer(user); assertEquals(0, SystemManager.countActions(server.getId())); Action action = ActionFactoryTest.createAction(user, ActionFactory.TYPE_CONFIGFILES_UPLOAD); ServerActionTest.createServerAction(server, action); ActionFactory.save(action); assertEquals(1, SystemManager.countActions(server.getId())); Action action2 = ActionFactoryTest.createAction(user, ActionFactory.TYPE_CONFIGFILES_UPLOAD); ServerActionTest.createServerAction(server, action2); ActionFactory.save(action); assertEquals(2, SystemManager.countActions(server.getId())); }
72. SessionManagerTest#testPurgeSession()
Project: spacewalk
File: SessionManagerTest.java
File: SessionManagerTest.java
public void testPurgeSession() throws Exception { long duration = 3600L; User u = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); WebSession s = SessionManager.makeSession(u.getId(), duration); assertNotNull(s); long actualDuration = s.getExpires() - TimeUtils.currentTimeSeconds(); short tolerance = 2; // this works because it's in the same second. assertTrue(actualDuration > duration - tolerance); assertTrue(actualDuration < duration + tolerance); flushAndEvict(s); SessionManager.purgeUserSessions(u); try { SessionManager.lookupByKey(s.getKey()); fail("Lookup exception not thrown for a null key even after purge"); } catch (LookupException le) { } }
73. KickstartOptionsCommandTest#testKickstartOptionsCommand()
Project: spacewalk
File: KickstartOptionsCommandTest.java
File: KickstartOptionsCommandTest.java
public void testKickstartOptionsCommand() throws Exception { KickstartData k = KickstartDataTest.createKickstartWithOptions(user.getOrg()); User ksUser = UserTestUtils.createUser("testuser", k.getOrg().getId()); mockRequest = new RhnMockHttpServletRequest(); mockRequest.setupGetRemoteAddr("127.0.0.1"); request = new RhnHttpServletRequest(mockRequest); KickstartOptionsCommand command = new KickstartOptionsCommand(k.getId(), ksUser); assertNotNull(command); assertTrue(command.getDisplayOptions().size() > 0); assertTrue(command.getDisplayOptions().size() >= command.getKickstartData().getOptions().size()); }
74. KickstartSessionCreateCommand#addChildChannelsForProfile()
Project: spacewalk
File: KickstartSessionCreateCommand.java
File: KickstartSessionCreateCommand.java
private void addChildChannelsForProfile(Profile profile, Channel baseChannel, ActivationKey key) { log.debug("** addChildChannelsForProfile"); User orgAdmin = UserFactory.findRandomOrgAdmin(this.ksession.getOrg()); List channels = ProfileManager.getChildChannelsNeededForProfile(orgAdmin, baseChannel, profile); Iterator i = channels.iterator(); while (i.hasNext()) { Channel child = (Channel) i.next(); log.debug("** adding child channel for profile: " + child.getLabel()); key.addChannel(child); } }
75. ErrataManagerTest#testErrataInSet()
Project: spacewalk
File: ErrataManagerTest.java
File: ErrataManagerTest.java
public void testErrataInSet() throws Exception { User user = UserTestUtils.findNewUser(); Errata e = ErrataFactoryTest.createTestErrata(user.getOrg().getId()); e = (Errata) TestUtils.saveAndReload(e); RhnSet set = RhnSetDecl.ERRATA_TO_REMOVE.get(user); set.add(e.getId()); RhnSetManager.store(set); List<ErrataOverview> list = ErrataManager.errataInSet(user, set.getLabel()); boolean found = false; for (ErrataOverview item : list) { if (item.getId().equals(e.getId())) { found = true; } } assertTrue(found); }
76. ErrataManagerTest#testSystemsAffected()
Project: spacewalk
File: ErrataManagerTest.java
File: ErrataManagerTest.java
public void testSystemsAffected() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); PageControl pc = new PageControl(); pc.setStart(1); pc.setPageSize(5); Errata a = ErrataFactoryTest.createTestErrata(UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName())); DataResult systems = ErrataManager.systemsAffected(user, a.getId(), pc); assertNotNull(systems); assertTrue(systems.isEmpty()); assertFalse(systems.size() > 0); DataResult systems2 = ErrataManager.systemsAffected(user, new Long(-2), pc); assertTrue(systems2.isEmpty()); }
77. ErrataManagerTest#testRelevantErrataByTypeList()
Project: spacewalk
File: ErrataManagerTest.java
File: ErrataManagerTest.java
public void testRelevantErrataByTypeList() throws Exception { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); ErrataCacheManagerTest.createServerNeededPackageCache(user, ErrataFactory.ERRATA_TYPE_BUG); PageControl pc = new PageControl(); pc.setStart(1); pc.setPageSize(20); DataResult errata = ErrataManager.relevantErrataByType(user, pc, ErrataFactory.ERRATA_TYPE_BUG); assertNotNull(errata); assertTrue(errata.size() >= 1); }
78. ChannelManagerTest#testAddRemoveSubscribeRole()
Project: spacewalk
File: ChannelManagerTest.java
File: ChannelManagerTest.java
public void testAddRemoveSubscribeRole() throws Exception { User admin = UserTestUtils.createUser("adminUser", user.getOrg().getId()); Channel channel = ChannelFactoryTest.createTestChannel(admin); channel.setGloballySubscribable(false, admin.getOrg()); assertFalse(channel.isGloballySubscribable(admin.getOrg())); assertFalse(ChannelManager.verifyChannelSubscribe(user, channel.getId())); ChannelManager.addSubscribeRole(user, channel); assertTrue(ChannelManager.verifyChannelSubscribe(user, channel.getId())); ChannelManager.removeSubscribeRole(user, channel); assertFalse(ChannelManager.verifyChannelSubscribe(user, channel.getId())); }
79. ActionManagerTest#testAddServerToAction()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testAddServerToAction() throws Exception { User usr = UserTestUtils.createUser("testUser", UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName())); Server s = ServerFactoryTest.createTestServer(usr); Action a = ActionFactoryTest.createAction(usr, ActionFactory.TYPE_ERRATA); ActionManager.addServerToAction(s.getId(), a); assertNotNull(a.getServerActions()); assertEquals(a.getServerActions().size(), 1); Object[] array = a.getServerActions().toArray(); ServerAction sa = (ServerAction) array[0]; assertTrue(sa.getStatus().equals(ActionFactory.STATUS_QUEUED)); assertTrue(sa.getServer().equals(s)); }
80. ActionManagerTest#testCreateErrataAction()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testCreateErrataAction() throws Exception { User user = UserTestUtils.createUser("testUser", UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName())); Errata errata = ErrataFactoryTest.createTestErrata(user.getOrg().getId()); Action a = ActionManager.createErrataAction(user.getOrg(), errata); assertNotNull(a); assertNotNull(a.getOrg()); a = ActionManager.createErrataAction(user, errata); assertNotNull(a); assertNotNull(a.getOrg()); assertTrue(a.getActionType().equals(ActionFactory.TYPE_ERRATA)); }
81. ActionManagerTest#testRescheduleAction()
Project: spacewalk
File: ActionManagerTest.java
File: ActionManagerTest.java
public void testRescheduleAction() throws Exception { User user1 = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); Action a1 = ActionFactoryTest.createAction(user1, ActionFactory.TYPE_REBOOT); ServerAction sa = (ServerAction) a1.getServerActions().toArray()[0]; sa.setStatus(ActionFactory.STATUS_FAILED); sa.setRemainingTries(new Long(0)); ActionFactory.save(a1); ActionManager.rescheduleAction(a1); sa = (ServerAction) ActionFactory.reload(sa); assertTrue(sa.getStatus().equals(ActionFactory.STATUS_QUEUED)); assertTrue(sa.getRemainingTries().longValue() > 0); }
82. UserHandler#getLoggedInTime()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Returns the last logged in time of the given user. * @param loggedInUser The current user * in user. * @param login The login of the user. * @return last logged in time * @throws UserNeverLoggedInException if the given user has never logged in. * @deprecated Never returned usable value. * * @xmlrpc.doc Returns the time user last logged in. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.returntype dateTime.iso8601 */ @Deprecated public Date getLoggedInTime(User loggedInUser, String login) throws UserNeverLoggedInException { User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); Date d = target.getLastLoggedIn(); if (d != null) { return d; } throw new UserNeverLoggedInException(); }
83. UserHandler#listDefaultSystemGroups()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Returns default system groups for the given login. * @param loggedInUser The current user * in user. * @param login The login for the user whose Default ServerGroup list is * sought. * @return default system groups for the given login * * @xmlrpc.doc Returns a user's list of default system groups. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.returntype * #array() * #struct("system group") * #prop("int", "id") * #prop("string", "name") * #prop("string", "description") * #prop("int", "system_count") * #prop_desc("int", "org_id", "Organization ID for this system group.") * #struct_end() * #array_end() */ public Object[] listDefaultSystemGroups(User loggedInUser, String login) { User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); Set<Long> ids = target.getDefaultSystemGroupIds(); List<ServerGroup> sgs = new ArrayList(ids.size()); for (Long id : ids) { sgs.add(ServerGroupFactory.lookupByIdAndOrg(id, target.getOrg())); } return sgs.toArray(); }
84. UserHandler#usePamAuthentication()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Toggles whether or not a user users pamAuthentication or the basic RHN db auth. * @param loggedInUser The current user * @param login The login for the user you would like to change * @param val The value you would like to set this to (1 = true, 0 = false) * @return Returns 1 if successful (exception otherwise) * @throws FaultException A FaultException is thrown if the user doesn't have access * to lookup the user corresponding to login or if the user does not exist. * * @xmlrpc.doc Toggles whether or not a user uses PAM authentication or * basic RHN authentication. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.param #param("int", "pam_value") * #options() * #item("1 to enable PAM authentication") * #item("0 to disable.") * #options_end() * @xmlrpc.returntype #return_int_success() */ public int usePamAuthentication(User loggedInUser, String login, Integer val) throws FaultException { // Only org admins can use this method. ensureOrgAdmin(loggedInUser); User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); if (val.equals(new Integer(1))) { target.setUsePamAuthentication(true); } else { target.setUsePamAuthentication(false); } UserManager.storeUser(target); return 1; }
85. UserHandler#delete()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Deletes a user * @param loggedInUser The current user * @param login The login for the user you would like to delete * @return Returns 1 if successful (exception otherwise) * @throws FaultException A FaultException is thrown if the user doesn't have access * to lookup the user corresponding to login or if the user does not exist. * * @xmlrpc.doc Delete a user. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User login name to delete.") * @xmlrpc.returntype #return_int_success() */ public int delete(User loggedInUser, String login) throws FaultException { ensureOrgAdmin(loggedInUser); User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); try { UserManager.deleteUser(loggedInUser, target.getId()); } catch (DeleteSatAdminException e) { throw new DeleteUserException("user.cannot.delete.last.sat.admin"); } return 1; }
86. UserHandler#modifySatAdminRole()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Handles the vagaries related to granting or revoking sat admin role * @param loggedInUser the logged in user * @param login the login of the user who needs to be granted/revoked sat admin role * @param grant true if granting the role to the login, false for revoking... * @return 1 if it success.. Ofcourse error on failure.. */ private int modifySatAdminRole(User loggedInUser, String login, boolean grant) { ensureUserRole(loggedInUser, RoleFactory.SAT_ADMIN); SatManager manager = SatManager.getInstance(); User user = UserFactory.lookupByLogin(login); if (grant) { manager.grantSatAdminRoleTo(user, loggedInUser); } else { manager.revokeSatAdminRoleFrom(user, loggedInUser); } UserManager.storeUser(user); return 1; }
87. UserHandler#listRoles()
Project: spacewalk
File: UserHandler.java
File: UserHandler.java
/** * Lists the roles for a user * @param loggedInUser The current user * @param login The login for the user you want to get the roles for * @return Returns a list of roles for the user specified by login * @throws FaultException A FaultException is thrown if the user doesn't have access * to lookup the user corresponding to login or if the user does not exist. * * @xmlrpc.doc Returns a list of the user's roles. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param_desc("string", "login", "User's login name.") * @xmlrpc.returntype #array_single("string", "(role label)") */ public Object[] listRoles(User loggedInUser, String login) throws FaultException { // Get the logged in user User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); //List of role labels to return List roles = new ArrayList(); //Loop through the target users roles and stick the labels into the ArrayList Set roleObjects = target.getPermanentRoles(); for (Iterator itr = roleObjects.iterator(); itr.hasNext(); ) { Role r = (Role) itr.next(); roles.add(r.getLabel()); } return roles.toArray(); }
88. UserHandlerTest#testRemoveAssignedSystemGroupsInvalidGroup()
Project: spacewalk
File: UserHandlerTest.java
File: UserHandlerTest.java
public void testRemoveAssignedSystemGroupsInvalidGroup() throws Exception { User testUser = UserTestUtils.createUser("ksdjkfjasdkfjasdfjoiwenv", admin.getOrg().getId()); try { handler.removeAssignedSystemGroup(admin, testUser.getLogin(), "kdfjkdsjflksdjf", false); fail(); } catch (InvalidServerGroupException e) { } }
89. XmlRpcServletTest#testTranslation()
Project: spacewalk
File: XmlRpcServletTest.java
File: XmlRpcServletTest.java
public void testTranslation() throws Exception { User user = UserTestUtils.findNewUser("testuser", "testorg"); doTest("<?xml version=\"1.0\"?> <methodCall> " + "<methodName>unittest.getUserLogin</methodName> <params> " + "<param><value><i4>" + user.getId() + "</i4></value></param>" + "</params>" + "</methodCall>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<methodResponse><params><param><value><string>" + user.getLogin() + "</string></value></param></params>" + "</methodResponse>"); }
90. LoggingInvocationProcessorTest#testPostProcessValidSession()
Project: spacewalk
File: LoggingInvocationProcessorTest.java
File: LoggingInvocationProcessorTest.java
public void testPostProcessValidSession() { User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName()); // create a web session indicating a logged in user. WebSession s = WebSessionFactory.createSession(); s.setWebUserId(user.getId()); assertNotNull(s); WebSessionFactory.save(s); assertNotNull(s.getId()); String[] args = { s.getKey() }; lip.before(new XmlRpcInvocation(10, "handler", "method", null, Arrays.asList(args), writer)); Object rc = lip.after(new XmlRpcInvocation(10, "handler", "method", null, Arrays.asList(args), writer), "returnthis"); assertEquals("returnthis", rc); assertEquals("", writer.toString()); }
91. TaskomaticHandler#invoke()
Project: spacewalk
File: TaskomaticHandler.java
File: TaskomaticHandler.java
/** * translates any taskomatic API call to the internal taskomatic xmlrpc hanlder * @param methodCalled method to be forwarded * @param arguments list of argumets to be translated * @return forwarded result of the internal xmlrpc API * @throws XmlRpcFault in case of any exception */ public Object invoke(String methodCalled, List arguments) throws XmlRpcFault { List params = new ArrayList(arguments); String sessionKey = (String) params.remove(0); User loggedInUser = getLoggedInUser(sessionKey); checkUserRole(loggedInUser); addParameters(loggedInUser, params); log.info("Translating " + methodCalled); try { Object obj = client.invoke(TASKOMATIC_NAMESPACE + "." + methodCalled, params); return obj; } catch (XmlRpcException e) { throw new XmlRpcFault(1, e.getMessage()); } }
92. PackagesHandlerTest#testListFiles()
Project: spacewalk
File: PackagesHandlerTest.java
File: PackagesHandlerTest.java
public void testListFiles() throws Exception { User user = UserTestUtils.createUser("testUser", admin.getOrg().getId()); Package pkg = PackageTest.createTestPackage(user.getOrg()); Object[] files = handler.listFiles(admin, new Integer(pkg.getId().intValue())); // PackageTest.populateTestPackage populates a test package with 2 associated files assertEquals(2, files.length); //TODO: Once we work out the mappings between packages -> files -> capabilities //we should do some more exhaustive testing of this method. }
93. OrgHandlerTest#testMigrateSystem()
Project: spacewalk
File: OrgHandlerTest.java
File: OrgHandlerTest.java
public void testMigrateSystem() throws Exception { User newOrgAdmin = UserTestUtils.findNewUser("newAdmin", "newOrg", true); newOrgAdmin.getOrg().getTrustedOrgs().add(admin.getOrg()); OrgFactory.save(newOrgAdmin.getOrg()); Server server = ServerTestUtils.createTestSystem(admin); assertNotNull(server.getOrg()); List<Integer> servers = new LinkedList<Integer>(); servers.add(new Integer(server.getId().intValue())); // Actual migration is tested internally, just make sure the API call doesn't // error out: handler.migrateSystems(admin, newOrgAdmin.getOrg().getId().intValue(), servers); }
94. CryptoKeysHandlerTest#testListAllKeys()
Project: spacewalk
File: CryptoKeysHandlerTest.java
File: CryptoKeysHandlerTest.java
public void testListAllKeys() throws Exception { // Setup User otherOrg = UserTestUtils.findNewUser("testUser", "cryptoOrg", true); CryptoKey key = CryptoTest.createTestKey(otherOrg.getOrg()); KickstartFactory.saveCryptoKey(key); flushAndEvict(key); // Test CryptoKeysHandler handler = new CryptoKeysHandler(); List allKeys = handler.listAllKeys(otherOrg); // Verify assertNotNull(allKeys); assertEquals(allKeys.size(), 1); CryptoKeyDto dto = (CryptoKeyDto) allKeys.get(0); assertEquals(key.getDescription(), dto.getDescription()); assertEquals(key.getOrg().getId(), dto.getOrgId()); }
95. ChannelSoftwareHandlerTest#testIsUserSubscribable()
Project: spacewalk
File: ChannelSoftwareHandlerTest.java
File: ChannelSoftwareHandlerTest.java
public void testIsUserSubscribable() throws Exception { Channel c1 = ChannelFactoryTest.createTestChannel(admin); c1.setGloballySubscribable(false, admin.getOrg()); User user = UserTestUtils.createUser("foouser", admin.getOrg().getId()); assertEquals(0, handler.isUserSubscribable(admin, c1.getLabel(), user.getLogin())); handler.setUserSubscribable(admin, c1.getLabel(), user.getLogin(), true); assertEquals(1, handler.isUserSubscribable(admin, c1.getLabel(), user.getLogin())); handler.setUserSubscribable(admin, c1.getLabel(), user.getLogin(), false); assertEquals(0, handler.isUserSubscribable(admin, c1.getLabel(), user.getLogin())); }
96. ChannelSoftwareHandler#isUserManageable()
Project: spacewalk
File: ChannelSoftwareHandler.java
File: ChannelSoftwareHandler.java
/** * Returns whether the channel may be managed by the given user. * @param loggedInUser The current user * @param channelLabel The label for the channel in question * @param login The login for the user in question * @return whether the channel may be managed by the given user. * @throws FaultException thrown if * - The loggedInUser doesn't have permission to perform this action * - The login, sessionKey, or channelLabel is invalid * * @xmlrpc.doc Returns whether the channel may be managed by the given user. * @xmlrpc.param #session_key() * @xmlrpc.param #param_desc("string", "channelLabel", "label of the channel") * @xmlrpc.param #param_desc("string", "login", "login of the target user") * @xmlrpc.returntype int - 1 if manageable, 0 if not */ public int isUserManageable(User loggedInUser, String channelLabel, String login) throws FaultException { User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); Channel channel = lookupChannelByLabel(loggedInUser.getOrg(), channelLabel); if (!channel.isCustom()) { throw new InvalidChannelException("Manageable flag is relevant for custom channels only."); } //Verify permissions if (!(UserManager.verifyChannelAdmin(loggedInUser, channel) || loggedInUser.hasRole(RoleFactory.CHANNEL_ADMIN))) { throw new PermissionCheckFailureException(); } boolean flag = ChannelManager.verifyChannelManage(target, channel.getId()); return BooleanUtils.toInteger(flag); }
97. ChannelSoftwareHandler#isUserSubscribable()
Project: spacewalk
File: ChannelSoftwareHandler.java
File: ChannelSoftwareHandler.java
/** * Returns whether the channel may be subscribed to by the given user. * @param loggedInUser The current user * @param channelLabel The label for the channel in question * @param login The login for the user in question * @return whether the channel may be subscribed to by the given user. * @throws FaultException thrown if * - The loggedInUser doesn't have permission to perform this action * - The login, sessionKey, or channelLabel is invalid * * @xmlrpc.doc Returns whether the channel may be subscribed to by the given user. * @xmlrpc.param #session_key() * @xmlrpc.param #param_desc("string", "channelLabel", "label of the channel") * @xmlrpc.param #param_desc("string", "login", "login of the target user") * @xmlrpc.returntype int - 1 if subscribable, 0 if not */ public int isUserSubscribable(User loggedInUser, String channelLabel, String login) throws FaultException { User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); Channel channel = lookupChannelByLabel(loggedInUser.getOrg(), channelLabel); //Verify permissions if (!(UserManager.verifyChannelAdmin(loggedInUser, channel) || loggedInUser.hasRole(RoleFactory.CHANNEL_ADMIN))) { throw new PermissionCheckFailureException(); } boolean flag = ChannelManager.verifyChannelSubscribe(target, channel.getId()); return BooleanUtils.toInteger(flag); }
98. ChannelSoftwareHandler#setUserSubscribable()
Project: spacewalk
File: ChannelSoftwareHandler.java
File: ChannelSoftwareHandler.java
/** * Set the subscribable flag for a given channel and user. If value is set to 'true', * this method will give the user subscribe permissions to the channel. Otherwise, this * method revokes that privilege. * @param loggedInUser The current user * @param channelLabel The label for the channel in question * @param login The login for the user in question * @param value The boolean value telling us whether to grant subscribe permission or * revoke it. * @return Returns 1 on success, FaultException otherwise * @throws FaultException A FaultException is thrown if: * - The loggedInUser doesn't have permission to perform this action * - The login, sessionKey, or channelLabel is invalid * * @xmlrpc.doc Set the subscribable flag for a given channel and user. * If value is set to 'true', this method will give the user * subscribe permissions to the channel. Otherwise, that privilege is revoked. * @xmlrpc.param #session_key() * @xmlrpc.param #param_desc("string", "channelLabel", "label of the channel") * @xmlrpc.param #param_desc("string", "login", "login of the target user") * @xmlrpc.param #param_desc("boolean", "value", "value of the flag to set") * @xmlrpc.returntype #return_int_success() */ public int setUserSubscribable(User loggedInUser, String channelLabel, String login, Boolean value) throws FaultException { User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login); Channel channel = lookupChannelByLabel(loggedInUser, channelLabel); //Verify permissions if (!(UserManager.verifyChannelAdmin(loggedInUser, channel) || loggedInUser.hasRole(RoleFactory.CHANNEL_ADMIN))) { throw new PermissionCheckFailureException(); } if (value) { // Add the 'subscribe' role for the target user to the channel ChannelManager.addSubscribeRole(target, channel); } else { // Remove the 'subscribe' role for the target user to the channel ChannelManager.removeSubscribeRole(target, channel); } return 1; }
99. BaseHandler#getLoggedInUser()
Project: spacewalk
File: BaseHandler.java
File: BaseHandler.java
/** * Gets the currently logged in user. This is all done through the sessionkey we send * the user in AuthHandler.login. * @param sessionKey The key containing the session id that we can use to load the * session. * @return Returns the user logged into the session corresponding to the given * sessionkey. */ public static User getLoggedInUser(String sessionKey) { //Load the session WebSession session = SessionManager.loadSession(sessionKey); User user = session.getUser(); //Make sure there was a valid user in the session. If not, the session is invalid. if (user == null) { throw new LookupException("Could not find a valid user for session with key: " + sessionKey); } //Return the logged in user return user; }
100. AuthHandler#login()
Project: spacewalk
File: AuthHandler.java
File: AuthHandler.java
/** * Login using a username and password only. Creates a session containing the userId * and returns the key for the session. * @param username Username to check * @param password Password to check * @param durationIn The session duration * @return Returns the key for the session * @throws LoginException Throws a LoginException if the user can't be logged in. * * @xmlrpc.doc Login using a username and password. Returns the session key * used by other methods. * @xmlrpc.param #param("string", "username") * @xmlrpc.param #param("string", "password") * @xmlrpc.param #param_desc("int", "duration", "Length of session.") * @xmlrpc.returntype * #param("string", "sessionKey") */ public String login(String username, String password, Integer durationIn) throws LoginException { //Log in the user (handles authentication and active/disabled logic) User user = null; try { user = UserManager.loginReadOnlyUser(username, password); } catch (LoginException e) { throw new UserLoginException(e.getMessage()); } long duration = getDuration(durationIn); //Create a new session with the user WebSession session = SessionManager.makeSession(user.getId(), duration); return session.getKey(); }