public void testVirtEnt() throws Exception {
    UserTestUtils.addUserRole(user, RoleFactory.ACTIVATION_KEY_ADMIN);
    UserTestUtils.addVirtualization(user.getOrg());
    Channel baseChannel = ChannelTestUtils.createBaseChannel(user);
    Channel[] channels = ChannelTestUtils.setupBaseChannelForVirtualization(user, baseChannel);

    checkVirtEnt(
        ServerConstants.getServerGroupTypeVirtualizationEntitled(),
        channels[ChannelTestUtils.VIRT_INDEX],
        channels[ChannelTestUtils.TOOLS_INDEX]);
  }
 protected void setUp() throws Exception {
   super.setUp();
   user = UserTestUtils.createUserInOrgOne();
   UserTestUtils.addMonitoring(user.getOrg());
   probeSuite = ProbeSuiteTest.createTestProbeSuite(user);
   probe =
       (TemplateProbe)
           MonitoringFactoryTest.createTestProbe(user, MonitoringConstants.getProbeTypeSuite());
   probeSuite.addProbe(probe, user);
   MonitoringFactory.saveProbeSuite(probeSuite, user);
   probeSuite = (ProbeSuite) reload(probeSuite);
   action = new ProbeSuiteProbeEditAction();
 }
  public void testLookup() {
    // first lets just check on permissions...
    user.addPermanentRole(RoleFactory.ACTIVATION_KEY_ADMIN);
    final ActivationKey key = manager.createNewActivationKey(user, "Test");
    ActivationKey temp;
    // we make newuser
    // unfortunately satellite is NOT multiorg aware...
    // So we can't check on the org clause
    // so...
    User newUser =
        UserTestUtils.findNewUser("testUser2", "testOrg" + this.getClass().getSimpleName());
    try {
      manager.lookupByKey(key.getKey(), newUser);
      String msg =
          "Permission check failed :(.."
              + "Activation key should not have gotten found out"
              + " because the user does not have activation key admin role";

      fail(msg);
    } catch (Exception e) {
      // great!.. Exception for permission failure always welcome
    }
    try {
      temp = manager.lookupByKey(key.getKey() + "FOFOFOFOFOFOF", user);
      String msg = "NUll lookup failed, because this object should NOT exist!";
      fail(msg);
    } catch (Exception e) {
      // great!.. Exception for null lookpu is controvoersial but convenient..
    }
    temp = manager.lookupByKey(key.getKey(), user);
    assertNotNull(temp);
    assertEquals(user.getOrg(), temp.getOrg());
  }
  public void testDisabledUser() {
    LoginAction action = new LoginAction();
    User u = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());
    UserManager.disableUser(u, u);

    ActionMapping mapping = new ActionMapping();
    mapping.addForwardConfig(new ActionForward("failure", "path", false));
    PxtCookieManager pcm = new PxtCookieManager();
    RhnMockDynaActionForm form = new RhnMockDynaActionForm("loginForm");
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    RhnMockHttpServletResponse response = new RhnMockHttpServletResponse();

    RequestContext requestContext = new RequestContext(request);

    request.setSession(new MockHttpSession());
    request.setupServerName("mymachine.rhndev.redhat.com");
    WebSession s = requestContext.getWebSession();
    request.addCookie(pcm.createPxtCookie(s.getId(), request, 10));

    form.set("username", u.getLogin());
    /**
     * Since we know testUser's password is "password", just set that here. using u.getPassword()
     * will fail when we're using encrypted passwords.
     */
    form.set("password", "password");

    ActionForward rc = action.execute(mapping, form, request, response);

    assertEquals("failure", rc.getName());
  }
  public void testCustomDataKeys() {
    User user = UserTestUtils.findNewUser("testuser", "testorg");
    Org org = user.getOrg();

    Set keys = org.getCustomDataKeys();
    int sizeBefore = keys.size();

    CustomDataKey key = CustomDataKeyTest.createTestCustomDataKey(user);
    assertFalse(keys.contains(key));
    assertFalse(org.hasCustomDataKey(key.getLabel()));
    assertFalse(org.hasCustomDataKey("foo" + System.currentTimeMillis()));
    assertFalse(org.hasCustomDataKey(null));

    org.addCustomDataKey(key);

    keys = org.getCustomDataKeys();
    int sizeAfter = keys.size();

    assertTrue(keys.contains(key));
    assertTrue(sizeBefore < sizeAfter);
    assertTrue(org.hasCustomDataKey(key.getLabel()));

    CustomDataKey key2 = OrgFactory.lookupKeyByLabelAndOrg(key.getLabel(), org);
    assertNotNull(key2);

    key2 = OrgFactory.lookupKeyByLabelAndOrg(null, org);
    assertNull(key2);
  }
 public void testAddVirtualization() throws Exception {
   Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
   org1.getEntitlements().add(OrgFactory.getEntitlementVirtualization());
   TestUtils.saveAndFlush(org1);
   org1 = (Org) reload(org1);
   assertTrue(org1.hasEntitlement(OrgFactory.getEntitlementVirtualization()));
 }
  public void testStore() {
    Org org = UserTestUtils.findNewOrg("testorg");

    String login = TestUtils.randomString();
    command.setLogin(login);
    command.setPassword("password");
    command.setEmail("*****@*****.**");
    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());
  }
  public void testOrgDefautRegistrationToken() throws Exception {
    User user = UserTestUtils.findNewUser("testUser", "testOrg", true);
    Org orig = user.getOrg();
    orig.setName("org created by OrgFactory test: " + TestUtils.randomString());
    // build the channels set
    Channel channel1 = ChannelFactoryTest.createTestChannel(orig);
    flushAndEvict(channel1);
    orig.addOwnedChannel(channel1);
    orig = OrgFactory.save(orig);
    assertTrue(orig.getId().longValue() > 0);

    assertNull(orig.getToken());
    ActivationKey key = ActivationKeyTest.createTestActivationKey(user);
    // Token is hidden behind activation key so we have to look it up
    // manually:
    Token token = TokenFactory.lookupById(key.getId());
    orig.setToken(token);
    orig = OrgFactory.save(orig);
    Long origId = orig.getId();
    flushAndEvict(orig);

    Org lookup = OrgFactory.lookupById(origId);
    assertEquals(token.getId(), lookup.getToken().getId());
    lookup.setToken(null);
    flushAndEvict(lookup);

    lookup = OrgFactory.lookupById(origId);
    assertNull(lookup.getToken());
  }
  /**
   * In this test we actually return an HttpServletRequest so this code can be reused by other tests
   * to Login a user and get the Request (with session) that appears logged in. In order for this
   * test to be executed by JUnit we have to wrap its call in the above method with a void return
   * type.
   *
   * @throws Exception
   */
  public HttpServletRequest loginUserIntoSessionTest() throws Exception {
    LoginAction action = new LoginAction();
    User u = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());
    ActionMapping mapping = new ActionMapping();
    mapping.addForwardConfig(new ActionForward("loggedin", "path", false));
    PxtCookieManager pcm = new PxtCookieManager();
    RhnMockDynaActionForm form = new RhnMockDynaActionForm("loginForm");
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    RhnMockHttpServletResponse response = new RhnMockHttpServletResponse();

    RequestContext requestContext = new RequestContext(request);

    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setupGetAttribute("url_bounce", null);
    mockSession.setupGetAttribute("request_method", "GET");
    request.setSession(mockSession);
    request.setupServerName("mymachine.rhndev.redhat.com");
    WebSession s = requestContext.getWebSession();
    request.addCookie(pcm.createPxtCookie(s.getId(), request, 10));

    form.set("username", u.getLogin());
    /**
     * Since we know testUser's password is "password", just set that here. using u.getPassword()
     * will fail when we're using encrypted passwords.
     */
    form.set("password", "password");
    form.set("request_method", "POST");

    ActionForward rc = action.execute(mapping, form, request, response);

    assertNull(rc);
    return request;
  }
  /**
   * Test fetching a PackageAction
   *
   * @throws Exception
   */
  public void testLookupPackageAction() throws Exception {

    Action newA =
        ActionFactoryTest.createAction(
            UserTestUtils.createUser(
                "testUser", UserTestUtils.createOrg("testOrg" + this.getClass().getSimpleName())),
            ActionFactory.TYPE_PACKAGES_VERIFY);
    assertNotNull(newA.getId());
    assertTrue(newA instanceof PackageAction);
    PackageAction p = (PackageAction) newA;
    assertNotNull(p.getDetails());
    assertEquals(p.getDetails().size(), 1);
    PackageActionDetails firstDetail = (PackageActionDetails) p.getDetails().toArray()[0];

    /** Make sure PackageEvr was set & committed correctly */
    Set details = p.getDetails();
    Iterator ditr = details.iterator();
    while (ditr.hasNext()) {
      PackageActionDetails detail = (PackageActionDetails) ditr.next();
      assertNotNull(detail.getEvr().getId());
    }

    User user = UserTestUtils.findNewUser("TEST USER", "TEST ORG");
    Server testserver = ServerFactoryTest.createTestServer(user);

    PackageActionResult result = new PackageActionResult();
    result.setServer(testserver);
    result.setDetails(firstDetail);
    result.setResultCode(new Long(42));
    result.setCreated(new Date());
    result.setModified(new Date());

    firstDetail.addResult(result);

    ActionFactory.save(p);

    PackageAction p2 = (PackageAction) ActionFactory.lookupById(p.getId());

    assertNotNull(p2.getDetails());
    assertEquals(p2.getDetails().size(), 1);
    assertNotNull(p2.getDetails().toArray()[0]);
    firstDetail = (PackageActionDetails) p2.getDetails().toArray()[0];
    assertNotNull(firstDetail.getResults());
    assertEquals(firstDetail.getResults().size(), 1);
  }
  public void testKeyGeneration() throws Exception {

    ActivationKey k = createTestActivationKey(user);
    String note = k.getNote();
    String key = k.getKey();

    TestUtils.saveAndFlush(k);

    ActivationKey k2 = ActivationKeyFactory.lookupByKey(key);
    assertEquals(key, k2.getKey());
    assertEquals(note, k2.getNote());

    ActivationKey k3 = ActivationKeyFactory.lookupByKey(TestUtils.randomString());
    assertNull(k3);

    // Make sure we got the entitlements correct
    Server server = k2.getServer();
    assertEquals(1, server.getEntitlements().size());
    assertEquals(1, k2.getEntitlements().size());

    Entitlement e = server.getEntitlements().iterator().next();
    ServerGroupType t2 = k2.getEntitlements().iterator().next();
    assertEquals(e.getLabel(), t2.getLabel());

    // test out ActivationKeyManager.findByServer while we're here...
    ActivationKey k4 =
        ActivationKeyManager.getInstance().findByServer(server, user).iterator().next();
    assertNotNull(k4);
    assertEquals(key, k4.getKey());

    try {
      k3 = ActivationKeyManager.getInstance().findByServer(null, user).iterator().next();
      String msg =
          "Permission check failed :(.."
              + " Activation key should not have existed"
              + " for a server of 'null' id. An exception "
              + "should have been raised for this.";
      fail(msg);
    } catch (Exception ie) {
      // great!.. Exception for passing in invalid keys always welcome
    }

    User user1 = UserTestUtils.findNewUser("testuser", "testorg");
    Server server2 = ServerFactoryTest.createTestServer(user1);
    try {
      k3 = ActivationKeyManager.getInstance().findByServer(server2, user1).iterator().next();
      String msg =
          "Permission check failed :(.."
              + " Activation key should not have existed"
              + " for a server of the associated id. An exception "
              + "should have been raised for this.";
      fail(msg);
    } catch (Exception ie) {
      // great!.. Exception for passing in invalid keys always welcome
    }
  }
 public void testCommitOrg() throws Exception {
   Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
   String changedName = "OrgFactoryTest testCommitOrg " + TestUtils.randomString();
   org1.setName(changedName);
   org1 = OrgFactory.save(org1);
   Long id = org1.getId();
   flushAndEvict(org1);
   Org org2 = OrgFactory.lookupById(id);
   assertEquals(changedName, org2.getName());
 }
 public void testIllegalEntitlement() throws Exception {
   try {
     Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
     OrgEntitlementType invalid = new OrgEntitlementType("invalid");
     invalid.setLabel("ILLEGAL ENTITLEMENT");
     invalid.setName("ILLEGAL ENTITLEMENT NAME");
     org1.hasEntitlement(invalid);
     fail("Checked for illegal entitlement, should have received an exception");
   } catch (IllegalArgumentException e) {
     // Expected exception
   }
 }
 /**
  * Test the addition of an entitlement to an org This code should be refactored into a business
  * method of some sort if it becomes necessary to actually add entitlements progmatically from
  * within the Java code. For now we need this test because new Orgs don't have any entitlements.
  */
 public void testAddEntitlement() throws Exception {
   // Create a new Org and add an Entitlement
   Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
   Set entitlements = org1.getEntitlements();
   OrgEntitlementType oet = OrgFactory.lookupEntitlementByLabel("sw_mgr_enterprise");
   entitlements.add(oet);
   org1.setEntitlements(entitlements);
   org1 = OrgFactory.save(org1);
   Long orgId = org1.getId();
   // Re-lookup the object and test it
   flushAndEvict(org1);
   Org org2 = OrgFactory.lookupById(orgId);
   assertTrue(org2.hasEntitlement(oet));
 }
  public void testDeployConfig() throws Exception {
    UserTestUtils.addUserRole(user, RoleFactory.ACTIVATION_KEY_ADMIN);

    // need a tools channel for config deploy
    Channel base = ChannelTestUtils.createBaseChannel(user);
    ChannelTestUtils.setupBaseChannelForVirtualization(user, base);

    ActivationKey key = createActivationKey();
    // Create a config channel
    ConfigChannel cc = ConfigTestUtils.createConfigChannel(user.getOrg());
    ConfigChannelListProcessor proc = new ConfigChannelListProcessor();
    proc.add(key.getConfigChannelsFor(user), cc);
    key.setDeployConfigs(true);
    ActivationKeyFactory.save(key);
    assertTrue(key.getDeployConfigs());
    assertFalse(key.getChannels().isEmpty());
    assertFalse(key.getPackages().isEmpty());
  }
  public void testPostProcessValidSession() {
    User user = UserTestUtils.findNewUser("testUser", "testOrg");
    // 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());
  }
  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(XmlRpcTestUtils.getSessionKey(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());
  }
  public void testCreatePackageUpdateActionWithName() throws Exception {
    User usr = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());

    PackageAction testAction =
        (PackageAction) ActionFactoryTest.createAction(usr, ActionFactory.TYPE_PACKAGES_UPDATE);
    PackageActionDetailsTest.createTestDetailsWithName(usr, testAction);
    ActionFactory.save(testAction);
    flushAndEvict(testAction);
    /** Get action back out of db and make sure it committed correctly */
    Action same = ActionFactory.lookupById(testAction.getId());
    assertTrue(same instanceof PackageAction);
    PackageAction sameAction = (PackageAction) same;

    assertNotNull(sameAction.getDetails());
    assertEquals(sameAction.getDetails().size(), 2);
    assertNotNull(sameAction.getDetails().toArray()[0]);
    assertNotNull(sameAction.getDetails().toArray()[1]);
    assertEquals(sameAction.getName(), testAction.getName());
    assertEquals(sameAction.getId(), testAction.getId());
  }
  public void testAddServerGroup() throws Exception {
    Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
    assertTrue(org1.getEntitledServerGroups().size() > 0);
    boolean contains = false;
    for (Iterator itr = org1.getEntitledServerGroups().iterator(); itr.hasNext(); ) {
      ServerGroup group = (ServerGroup) itr.next();
      assertNotNull(group);
      if (ServerConstants.getServerGroupTypeUpdateEntitled().equals(group.getGroupType())) {
        contains = true;
      }
    }
    assertTrue(contains);

    // in hosted, the hibernate mapping files were broken so that adding a
    // second
    // server group would break a database constraint. This line ensures
    // that that
    // problem will not exist again.
    ServerGroupTest.createTestServerGroup(
        org1, ServerConstants.getServerGroupTypeEnterpriseEntitled());
  }
  public void testCreatePackageRemoveAction() throws Exception {
    User user = UserTestUtils.findNewUser("testUser", "testOrg" + this.getClass().getSimpleName());
    Server srvr = ServerFactoryTest.createTestServer(user);

    ServerAction sa = new ServerAction();
    sa.setStatus(ActionFactory.STATUS_QUEUED);
    sa.setRemainingTries(new Long(10));
    sa.setServer(srvr);
    log.debug("Creating PackageRemoveAction.");
    PackageAction pra =
        (PackageAction) ActionFactory.createAction(ActionFactory.TYPE_PACKAGES_REMOVE);
    pra.setOrg(user.getOrg());
    pra.setName("Package Removal");
    pra.addServerAction(sa);
    sa.setParentAction(pra);
    log.debug("Committing PackageRemoveAction.");
    ActionFactory.save(pra);

    PackageAction result = (PackageAction) ActionFactory.lookupById(pra.getId());

    assertEquals(pra, result);
  }
  public void testUpgradablePackagesFromServerSet() throws Exception {
    // Setup
    User admin = UserTestUtils.findNewUser("ssmUpgradeUser1", "ssmUpgradeOrg1");
    Org org = admin.getOrg();

    //   Create the server and add to the SSM
    Server server = ServerTestUtils.createTestSystem(admin);
    ServerTestUtils.addServersToSsm(admin, server.getId());

    //   Create upgraded package EVR so package will show up from the query
    PackageEvr upgradedPackageEvr = PackageEvrFactory.createPackageEvr("1", "1.0.0", "2");
    upgradedPackageEvr = (PackageEvr) TestUtils.saveAndReload(upgradedPackageEvr);

    ServerTestUtils.populateServerErrataPackages(
        org, server, upgradedPackageEvr, ErrataFactory.ERRATA_TYPE_SECURITY);
    ServerTestUtils.populateServerErrataPackages(
        org, server, upgradedPackageEvr, ErrataFactory.ERRATA_TYPE_BUG);

    // Test
    DataResult result = PackageManager.upgradablePackagesFromServerSet(admin);

    assertTrue(result != null);
    assertEquals(2, result.size());
  }
 /** Test to see if the Org returns list of UserGroup IDs */
 public void testGetRoles() throws Exception {
   Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
   assertNotNull(org1.getRoles());
   assertTrue(org1.hasRole(RoleFactory.ORG_ADMIN));
 }
 /**
  * Simple test illustrating how roles work. Note that the channel_admin role is implied for an org
  * admin iff the org has the channel_admin role.
  */
 public void testAddRole() {
   User user = UserTestUtils.findNewUser("testuser", "testorg");
   user.addPermanentRole(RoleFactory.ORG_ADMIN);
   assertTrue(user.hasRole(RoleFactory.CHANNEL_ADMIN));
 }
 public void testLookupById() throws Exception {
   Org org1 = UserTestUtils.findNewOrg("testOrg" + this.getClass().getSimpleName());
   assertNotNull(org1);
   assertTrue(org1.getId().longValue() > 0);
 }