/**
   * Add the up2date package to a system and a channel. Version should be specified such as "2.9.0"
   *
   * @param userIn
   * @param s
   * @param version
   * @param c
   * @return
   * @throws Exception
   */
  public static Package addUp2dateToSystemAndChannel(
      User userIn, Server s, String version, Channel c) throws Exception {

    Package p = null;
    PackageName pn = PackageFactory.lookupOrCreatePackageByName("up2date");
    if (pn != null) {
      List packages = PackageFactory.listPackagesByPackageName(pn);
      Iterator i = packages.iterator();
      while (i.hasNext()) {
        Package innerp = (Package) i.next();
        PackageEvr evr = innerp.getPackageEvr();
        if (evr != null && evr.getVersion().equals(version)) {
          p = innerp;
        }
      }
    }
    if (p == null) {
      p = PackageManagerTest.addPackageToSystemAndChannel("up2date", s, c);
      PackageEvr pevr = p.getPackageEvr();
      pevr.setEpoch("0");
      pevr.setVersion(version);
      pevr.setRelease("0");
      TestUtils.saveAndFlush(p);
      TestUtils.saveAndFlush(pevr);
    } else {
      PackageManagerTest.associateSystemToPackage(s, p);
    }

    return p;
  }
  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
    }
  }
Esempio n. 3
0
 public void testContentSource() throws Exception {
   Channel c = ChannelFactoryTest.createTestChannel(user);
   ContentSource cs = new ContentSource();
   cs.setLabel("repo_label-" + c.getLabel());
   cs.setSourceUrl("fake url");
   List<ContentSourceType> cst = ChannelFactory.listContentSourceTypes();
   cs.setType(cst.get(0));
   cs.setOrg(user.getOrg());
   cs = (ContentSource) TestUtils.saveAndReload(cs);
   c.getSources().add(cs);
   c = (Channel) TestUtils.saveAndReload(c);
   assertNotEmpty(c.getSources());
 }
  public void testPerformExecute() throws Exception {
    UserEditSetupAction action = new UserEditSetupAction();
    ActionHelper sah = new ActionHelper();
    sah.setUpAction(action);
    sah.getRequest().setRequestURL("foo");

    User user = sah.getUser();
    user.setTitle("Test title");
    // Lets add some roles
    Iterator it = UserFactory.IMPLIEDROLES.iterator();
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    while (it.hasNext()) {
      Role cr = (Role) it.next();
      user.getOrg().addRole(cr);
      user.addPermanentRole(cr);
    }

    setupExpectations(sah.getForm(), sah.getUser());

    // Below we test to make sure that some of
    // the strings in the form are localized
    TestUtils.enableLocalizationDebugMode();
    try {
      sah.executeAction();

      // verify the dyna form got the right values we expected.
      sah.getForm().verify();

      assertEquals(sah.getUser().getLastLoggedIn(), sah.getRequest().getAttribute("lastLoggedIn"));
      // Verify some more intensive stuff
      assertNotNull(sah.getRequest().getAttribute("adminRoles"));
      assertNotNull(sah.getRequest().getAttribute("regularRoles"));
      List<UserRoleStatusBean> regularRoles =
          (List<UserRoleStatusBean>) sah.getRequest().getAttribute("regularRoles");
      assertEquals(5, regularRoles.size());
      UserRoleStatusBean lv = regularRoles.get(0);
      assertTrue(TestUtils.isLocalized(lv.getName()));
      assertEquals(true, lv.isDisabled());
      assertNotNull(sah.getRequest().getAttribute("disabledRoles"));
      assertTrue(sah.getRequest().getAttribute("user") instanceof User);

      // If we have pam setup where we're testing, make sure displaypam was set
      String pamAuthService = Config.get().getString(ConfigDefaults.WEB_PAM_AUTH_SERVICE);
      if (pamAuthService != null && pamAuthService.trim().length() > 0) {
        assertNotNull(sah.getRequest().getAttribute("displaypam"));
      }
    } finally {
      TestUtils.disableLocalizationDebugMode();
    }
  }
  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 testLongNames() {
    int maxLogin = UserDefaults.get().getMaxUserLength();
    int maxPassword = UserDefaults.get().getMaxPasswordLength();
    int emailLength = UserDefaults.get().getMaxEmailLength();
    Config.get().setString(UserDefaults.MAX_USER_LENGTH, String.valueOf(5));
    Config.get().setString(UserDefaults.MAX_PASSWORD_LENGTH, String.valueOf(5));
    Config.get().setString(UserDefaults.MAX_EMAIL_LENGTH, String.valueOf(5));

    String invalidLogin = TestUtils.randomString();
    String invalidPassword = "******";
    String invalidEmail = "*****@*****.**";
    String validPrefix = "Sr.";

    // Test invalid values
    command.setLogin(invalidLogin);
    command.setEmail(invalidEmail);
    command.setPassword(invalidPassword);
    command.setPrefix(validPrefix);
    command.setFirstNames("testuser");
    command.setLastName("testuser");
    // We should get 4 errors (login, email, password, prefix)
    Object[] errors = command.validate();
    Config.get().setString(UserDefaults.MAX_USER_LENGTH, String.valueOf(maxLogin));
    Config.get().setString(UserDefaults.MAX_PASSWORD_LENGTH, String.valueOf(maxPassword));
    Config.get().setString(UserDefaults.MAX_EMAIL_LENGTH, String.valueOf(emailLength));
    assertEquals(3, errors.length);
  }
  public void testSystemPackageList() throws Exception {
    // need a system
    // need to add packages to that system
    // then need to query those values
    PageControl pc = new PageControl();
    pc.setIndexData(false);
    pc.setStart(1);

    user.addRole(RoleFactory.ORG_ADMIN);

    Server server = ServerFactoryTest.createTestServer(user, true);
    PackageManagerTest.addPackageToSystemAndChannel(
        "test-package-name" + TestUtils.randomString(),
        server,
        ChannelFactoryTest.createTestChannel(user));

    DataResult dr = PackageManager.systemPackageList(server.getId(), pc);
    assertNotNull(dr);
    assertEquals(1, dr.size());

    for (Iterator itr = dr.iterator(); itr.hasNext(); ) {
      Object o = itr.next();
      assertTrue(o instanceof PackageListItem);
    }
  }
 public void testCreateLotsofPackagesInChannel() throws Exception {
   String rand = TestUtils.randomString();
   Channel c = ChannelTestUtils.createTestChannel(user);
   for (int i = 0; i < 10; i++) {
     addPackageToChannel(rand, c);
   }
 }
  public void testValidate() {
    String invalidLogin = "";
    String validLogin = TestUtils.randomString();

    String invalidPassword = "******";
    String validPassword = "******";

    String invalidEmail = "foobar";
    String validEmail = "*****@*****.**";

    String invalidPrefix = "Foo.";
    String validPrefix = "Sr.";

    // Test invalid values
    command.setLogin(invalidLogin);
    command.setEmail(invalidEmail);
    command.setPassword(invalidPassword);
    command.setPrefix(invalidPrefix);
    command.setFirstNames("testuser");
    command.setLastName("testuser");

    // We should get 4 errors (login, email, password, prefix)
    Object[] errors = command.validate();
    assertEquals(4, errors.length);

    // Test valid values
    command.setLogin(validLogin);
    command.setEmail(validEmail);
    command.setPassword(validPassword);
    command.setPrefix(validPrefix);

    errors = command.validate();
    assertEquals(0, errors.length);
  }
Esempio n. 10
0
 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()));
 }
Esempio n. 11
0
  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());
  }
  public static ActivationKey createTestActivationKey(User u, Server s) {

    String note = "" + TestUtils.randomString() + " -- Java unit test activation key.";

    ActivationKey key = ActivationKeyManager.getInstance().createNewReActivationKey(u, s, note);
    ActivationKeyFactory.save(key);
    return key;
  }
Esempio n. 13
0
 public void testDeleteChannel() throws Exception {
   Channel c = ChannelFactoryTest.createTestChannel(user);
   Long id = c.getId();
   assertNotNull(c);
   ChannelFactory.save(c);
   assertNotNull(ChannelFactory.lookupById(id));
   ChannelFactory.remove(c);
   TestUtils.flushAndEvict(c);
   assertNull(ChannelFactory.lookupById(id));
 }
Esempio n. 14
0
 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());
 }
Esempio n. 15
0
 private Org createTestOrg() throws Exception {
   Org org1 = OrgFactory.createOrg();
   org1.setName("org created by OrgFactory test: " + TestUtils.randomString());
   org1 = OrgFactory.save(org1);
   // build the channels set
   Channel channel1 = ChannelFactoryTest.createTestChannel(org1);
   flushAndEvict(channel1);
   org1.addOwnedChannel(channel1);
   assertTrue(org1.getId().longValue() > 0);
   return org1;
 }
Esempio n. 16
0
  public void testIsProxy() throws Exception {
    Channel c = ChannelFactoryTest.createTestChannel(user);
    ChannelFamily cfam =
        ChannelFamilyFactoryTest.createTestChannelFamily(
            user, false, ChannelFamilyFactory.PROXY_CHANNEL_FAMILY_LABEL);

    c.setChannelFamily(cfam);

    TestUtils.saveAndFlush(c);

    Channel c2 = ChannelFactory.lookupById(c.getId());
    assertTrue(c2.isProxy());
  }
  public void testUpgradable() throws Exception {
    Map info =
        ErrataCacheManagerTest.createServerNeededPackageCache(user, ErrataFactory.ERRATA_TYPE_BUG);
    Server s = (Server) info.get("server");
    Package p = (Package) info.get("package");
    p = (Package) TestUtils.saveAndReload(p);

    DataResult<UpgradablePackageListItem> dr = PackageManager.upgradable(s.getId(), null);
    assertFalse(dr.isEmpty());
    boolean containsSamePackage = false;
    for (UpgradablePackageListItem item : dr) {
      if (p.getPackageName().getName().equals(item.getName())) {
        containsSamePackage = true;
      }
      assertTrue(item.getIdCombo().split("\\|").length == 3);
    }
    assertTrue(containsSamePackage);
  }
Esempio n. 18
0
  public void testHasAcl() {

    MockHttpServletRequest request = TestUtils.getRequestWithSessionAndUser();
    String singleTrue = "true_test()";
    String multipleTrue = "first_true_acl(); second_true_acl()";
    String singleFalse = "false_test()";
    String multipleFalse = "first_false_acl(); second_false_acl()";
    String lastFalse = "first_true_acl(); second_true_acl(); first_false_acl()";
    String oneFalse = "first_true_acl(); first_false_acl(); second_true_acl()";
    String singleFoo = "is_foo(foo)";
    String doubleFoo = "is_foo(foo); is_foo(foo)";
    String fooPlus = "true_test(); is_foo(foo)";
    String notFoo = "is_foo(notfoo)";
    String invalid = "flkas";
    String mixinFoo = MockFooAclHandler.class.getName();
    String mixinMultiple = MockMultipleAclHandler.class.getName();
    String mixinBoolean = BooleanAclHandler.class.getName();

    assertTrue(AclManager.hasAcl(singleTrue, request, mixinBoolean));
    assertTrue(AclManager.hasAcl(multipleTrue, request, mixinMultiple));
    assertFalse(AclManager.hasAcl(singleFalse, request, mixinBoolean));
    assertFalse(AclManager.hasAcl(multipleFalse, request, mixinMultiple));
    assertFalse(AclManager.hasAcl(lastFalse, request, mixinMultiple));
    assertFalse(AclManager.hasAcl(oneFalse, request, mixinMultiple));
    assertTrue(AclManager.hasAcl(singleFoo, request, mixinFoo));
    assertTrue(AclManager.hasAcl(doubleFoo, request, mixinFoo));
    assertTrue(AclManager.hasAcl(fooPlus, request, mixinFoo + "," + mixinBoolean));
    assertFalse(AclManager.hasAcl(notFoo, request, mixinFoo));

    try {
      AclManager.hasAcl(invalid, request, mixinBoolean);
      fail(); // should never get here
    } catch (Exception e) {
      // no op
    }

    try {
      AclManager.hasAcl(oneFalse, request, invalid);
      fail(); // should never get here
    } catch (Exception e) {
      // no op
    }
  }
  /**
   * Create a package with the given name and add it to the given channel. If a package by that name
   * already exists, this simply returns that package.
   *
   * @param packageName The name of the package to create.
   * @param c The channel to which to add the package
   * @return The package with that name in the channel.
   * @throws Exception
   */
  public static Package addPackageToChannel(String packageName, Channel c) throws Exception {

    PackageName pn = PackageFactory.lookupOrCreatePackageByName(packageName);
    if (pn == null) {
      pn = PackageNameTest.createTestPackageName();
      pn.setName(packageName);
    }

    Long existingId = ChannelManager.getLatestPackageEqual(c.getId(), packageName);

    if (existingId != null) {
      return PackageFactory.lookupByIdAndOrg(existingId, c.getOrg());
    }

    // existingId =
    Session session = HibernateFactory.getSession();
    Query query =
        session.createQuery(
            "from Package as "
                + "package where package.org.id = "
                + c.getOrg().getId()
                + " and package.packageName.id = "
                + pn.getId());
    List packages = query.list();
    Package retval = null;
    if (packages != null && packages.size() > 0) {
      retval = (Package) packages.get(0);
    } else {
      retval = PackageTest.createTestPackage(c.getOrg());
    }

    retval.setPackageName(pn);
    TestUtils.saveAndFlush(retval);
    PackageTest.addPackageToChannelNewestPackage(retval, c);

    return retval;
  }
  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());
  }
 public ActivationKey createActivationKey() throws Exception {
   user.addPermanentRole(RoleFactory.ACTIVATION_KEY_ADMIN);
   return manager.createNewActivationKey(user, TestUtils.randomString());
 }
  /**
   * Tests save().
   *
   * @throws Exception if something bad happens
   */
  @SuppressWarnings("unchecked")
  public void testSave() throws Exception {
    RhnMockHttpServletRequest request = TestUtils.getRequestWithSessionAndUser();
    user = new RequestContext(request).getCurrentUser();

    ActionChainSaveAction saveAction = new ActionChainSaveAction();
    String label = TestUtils.randomString();
    ActionChain actionChain = ActionChainFactory.createActionChain(label, user);
    for (int i = 0; i < 6; i++) {
      Action action = ActionFactory.createAction(ActionFactory.TYPE_ERRATA);
      action.setOrg(user.getOrg());
      ActionFactory.save(action);
      ActionChainFactory.queueActionChainEntry(
          action, actionChain, ServerFactoryTest.createTestServer(user), i / 2);
    }
    Action lastAction = ActionFactory.createAction(ActionFactory.TYPE_ERRATA);
    lastAction.setOrg(user.getOrg());
    ActionFactory.save(lastAction);
    ActionChainFactory.queueActionChainEntry(
        lastAction, actionChain, ServerFactoryTest.createTestServer(user), 3);

    String newLabel = TestUtils.randomString();
    List<Long> deletedEntries = new LinkedList<Long>();
    deletedEntries.add(lastAction.getId());
    List<Integer> deletedSortOrders = new LinkedList<Integer>();
    deletedSortOrders.add(0);
    deletedSortOrders.add(3);
    List<Integer> reorderedSortOrders = new LinkedList<Integer>();
    reorderedSortOrders.add(2);
    reorderedSortOrders.add(1);

    String resultString =
        saveAction.save(
            actionChain.getId(),
            newLabel,
            deletedEntries,
            deletedSortOrders,
            reorderedSortOrders,
            request);

    Map<String, Object> result = (Map<String, Object>) new JSONReader().read(resultString);
    assertEquals(true, result.get(ActionChainSaveAction.SUCCESS_FIELD));
    assertEquals(
        LocalizationService.getInstance().getMessage("actionchain.jsp.saved"),
        result.get(ActionChainSaveAction.TEXT_FIELD));
    assertEquals(newLabel, actionChain.getLabel());

    Set<ActionChainEntry> entries = actionChain.getEntries();
    assertEquals(4, entries.size());

    List<ActionChainEntry> sortedEntries = new LinkedList<ActionChainEntry>();
    sortedEntries.addAll(entries);
    Collections.sort(
        sortedEntries,
        new Comparator<ActionChainEntry>() {
          public int compare(ActionChainEntry entry1, ActionChainEntry entry2) {
            return entry1.getId().compareTo(entry2.getId());
          }
        });
    for (int i = 0; i < sortedEntries.size(); i++) {
      assertEquals((Integer) (1 - i / 2), sortedEntries.get(i).getSortOrder());
    }
  }
 public void testNullServer() throws Exception {
   ActivationKey key = ActivationKeyFactory.createNewKey(user, TestUtils.randomString());
   assertNotNull(key.getEntitlements());
   assertTrue(key.getEntitlements().size() == 1);
 }