public void testDelete() throws Exception {
    // Setup
    CryptoKey key = CryptoTest.createTestKey(admin.getOrg());
    KickstartFactory.saveCryptoKey(key);
    assertNotNull(KickstartFactory.lookupCryptoKeyById(key.getId(), key.getOrg()));
    flushAndEvict(key);

    // Test
    CryptoKeysHandler handler = new CryptoKeysHandler();
    handler.delete(adminKey, key.getDescription());

    // Verify
    CryptoKey deletedKey = KickstartFactory.lookupCryptoKeyById(key.getId(), key.getOrg());
    assertNull(deletedKey);
  }
  public void testLookupBySession() throws Exception {
    // Still have that weird error creating a test server
    // sometimes in hosted.
    ActivationKey k = createTestActivationKey(user);
    KickstartData ksdata = KickstartDataTest.createKickstartWithOptions(k.getOrg());
    KickstartFactory.saveKickstartData(ksdata);
    KickstartSession sess = KickstartSessionTest.createKickstartSession(ksdata, k.getCreator());
    KickstartFactory.saveKickstartSession(sess);
    k.setKickstartSession(sess);
    ActivationKeyFactory.save(k);
    k = (ActivationKey) reload(k);

    ActivationKey lookedUp = ActivationKeyFactory.lookupByKickstartSession(sess);
    assertNotNull(lookedUp);
  }
  /**
   * @param firstAction The first Action in the session's action chain
   *     <p>return Returns the KickstartSession.
   */
  protected KickstartSession setupKickstartSession(Action firstAction) {
    kickstartSession = new KickstartSession();
    Boolean deployConfig = this.getKsdata().getKickstartDefaults().getCfgManagementFlag();

    // TODO: Proxy logic

    // Setup the KickstartSession
    kickstartSession.setPackageFetchCount(new Long(0));
    kickstartSession.setKickstartMode(KickstartSession.MODE_ONETIME);
    kickstartSession.setDeployConfigs(deployConfig);
    kickstartSession.setAction(firstAction);
    kickstartSession.setKsdata(this.getKsdata());
    kickstartSession.setKstree(this.getKsdata().getTree());
    kickstartSession.setVirtualizationType(
        this.getKsdata().getKickstartDefaults().getVirtualizationType());
    kickstartSession.setLastAction(new Date());
    kickstartSession.setNewServer(this.getTargetServer());
    kickstartSession.setOldServer(this.getTargetServer());
    kickstartSession.setHostServer(this.getHostServer());
    kickstartSession.setUser(this.getUser());
    kickstartSession.setState(KickstartFactory.SESSION_STATE_CREATED);
    kickstartSession.setOrg(this.getUser().getOrg());
    kickstartSession.setSystemRhnHost(this.getProxyHost());
    kickstartSession.setVirtualizationType(
        this.getKsdata().getKickstartDefaults().getVirtualizationType());
    log.debug("** Saving new KickstartSession: " + kickstartSession.getId());
    KickstartFactory.saveKickstartSession(kickstartSession);
    log.debug("** Saved new KickstartSession: " + kickstartSession.getId());

    return kickstartSession;
  }
  /**
   * Cancel existing kickstart sessions on the host server for the system to be kickstarted (the
   * target server).
   */
  private void cancelExistingSessions() {
    Server hostServer = getHostServer();

    List sessions = KickstartFactory.lookupAllKickstartSessionsByServer(hostServer.getId());
    if (sessions != null) {
      log.debug("    Found sessions: " + sessions);
      Iterator i = sessions.iterator();
      while (i.hasNext()) {
        KickstartSession sess = (KickstartSession) i.next();
        if (sess != null && sess.getState() != null) {
          log.debug(
              "    Working with session: " + sess.getState().getLabel() + " id: " + sess.getId());
        }
        KickstartSessionState state = sess.getState();

        if (!state.equals(KickstartFactory.SESSION_STATE_FAILED)
            || !state.equals(KickstartFactory.SESSION_STATE_COMPLETE)) {
          log.debug(
              "    need to cancel this Session this.s: "
                  + hostServer.getId()
                  + " sess.hostServer: "
                  + (sess.getHostServer() == null ? "null" : "" + sess.getHostServer().getId()));
          if (sess.getHostServer() != null
              && sess.getHostServer().getId().equals(hostServer.getId())) {
            log.debug("    Marking session failed.");
            sess.markFailed(
                LocalizationService.getInstance().getMessage("kickstart.session.newsession"));
          }
        }
      }
    }
  }
 public void testEdit() throws Exception {
   CryptoKey key = CryptoTest.createTestKey(user.getOrg());
   KickstartFactory.saveCryptoKey(key);
   flushAndEvict(key);
   setupKey(new EditCryptoKeyCommand(user, key.getId()));
   assertNotNull(cmd.getCryptoKey());
   assertNull(cmd.store());
 }
  public void testGetDetails() throws Exception {
    // Setup
    CryptoKey key = CryptoTest.createTestKey(admin.getOrg());
    KickstartFactory.saveCryptoKey(key);
    assertNotNull(KickstartFactory.lookupCryptoKeyById(key.getId(), key.getOrg()));
    flushAndEvict(key);

    // Test
    CryptoKeysHandler handler = new CryptoKeysHandler();
    CryptoKey cryptoKey = handler.getDetails(adminKey, key.getDescription());

    // Verify
    assertNotNull(cryptoKey);
    assertEquals(cryptoKey.getDescription(), cryptoKey.getDescription());
    assertEquals(cryptoKey.getCryptoKeyType().getLabel(), cryptoKey.getCryptoKeyType().getLabel());
    assertEquals(cryptoKey.getKeyString(), cryptoKey.getKeyString());
  }
  public void testValidateKickstartChannel() throws Exception {
    Channel base = ChannelTestUtils.createBaseChannel(user);
    Channel tools = ChannelTestUtils.createChildChannel(user, base);
    ksdata.getTree().setChannel(base);
    ksdata
        .getTree()
        .setInstallType(
            KickstartFactory.lookupKickstartInstallTypeByLabel(KickstartInstallType.RHEL_4));
    assertFalse(ksdata.isRhel5());
    assertFalse(helper.verifyKickstartChannel(ksdata, user));

    PackageManagerTest.addPackageToChannel("rhn-kickstart", tools);
    assertFalse(helper.verifyKickstartChannel(ksdata, user));
    ksdata
        .getTree()
        .setInstallType(
            KickstartFactory.lookupKickstartInstallTypeByLabel(KickstartInstallType.RHEL_5));
    assertTrue(helper.verifyKickstartChannel(ksdata, user, false));
  }
  /**
   * Creates a new edit command, loading the key by the given description and user's org.
   *
   * @param currentUser used to identify the org under which the key is; cannot be <code>null</code>
   * @param description used to identify the key; cannot be <code>null</code>
   */
  public EditCryptoKeyCommand(User currentUser, String description) {
    super();

    if (currentUser == null) {
      throw new IllegalArgumentException("currentUser cannot be null");
    }

    if (description == null) {
      throw new IllegalArgumentException("description cannot be null");
    }

    this.key = KickstartFactory.lookupCryptoKey(description, currentUser.getOrg());
  }
 /**
  * Constructor for a kickstart where the host and the target may or may *not* be the same system.
  * If the target system does not yet exist, selectedTargetServer should be null. To be used when
  * you want to call the store() method.
  *
  * @param selectedHostServer server to host the kickstart
  * @param selectedTargetServer server to be kickstarted
  * @param ksid id of the KickstartData we are using
  * @param userIn user performing the kickstart
  * @param scheduleDateIn Date to schedule the KS.
  * @param kickstartServerNameIn the name of the server who is serving the kickstart
  */
 public KickstartScheduleCommand(
     Long selectedHostServer,
     Long selectedTargetServer,
     Long ksid,
     User userIn,
     Date scheduleDateIn,
     String kickstartServerNameIn) {
   this(
       selectedHostServer,
       selectedTargetServer,
       KickstartFactory.lookupKickstartDataByIdAndOrg(userIn.getOrg(), ksid),
       userIn,
       scheduleDateIn,
       kickstartServerNameIn);
 }
 /**
  * Constructor for a kickstart where the host and the target may or may *not* be the same system.
  * If the target system does not yet exist, selectedTargetServer should be null. To be used when
  * you want to call the store() method.
  *
  * @param selectedHostServer server to host the kickstart
  * @param selectedTargetServer server to be kickstarted
  * @param ksLabel label of the KickstartData we are using
  * @param userIn user performing the kickstart
  * @param scheduleDateIn Date to schedule the KS.
  * @param kickstartServerNameIn the name of the server who is serving the kickstart
  */
 public KickstartScheduleCommand(
     Long selectedHostServer,
     Long selectedTargetServer,
     String ksLabel,
     User userIn,
     Date scheduleDateIn,
     String kickstartServerNameIn) {
   this(
       selectedHostServer,
       selectedTargetServer,
       KickstartFactory.lookupKickstartDataByLabelAndOrgId(ksLabel, userIn.getOrg().getId()),
       userIn,
       scheduleDateIn,
       kickstartServerNameIn);
 }
  public void testCreate() throws Exception {
    // Setup
    String description = "CryptoKeysHandler.testCreate-Description";
    String content = MD5Crypt.md5Hex(RandomStringUtils.random(28));

    // Test
    CryptoKeysHandler handler = new CryptoKeysHandler();
    handler.create(adminKey, description, "GPG", content);

    // Verify
    CryptoKey cryptoKey = KickstartFactory.lookupCryptoKey(description, admin.getOrg());

    assertNotNull(cryptoKey);
    assertEquals(cryptoKey.getDescription(), description);
    assertEquals(cryptoKey.getCryptoKeyType().getLabel(), "GPG");
    assertEquals(cryptoKey.getKeyString(), content);
  }
  /**
   * Setup the system for provisioning with cobbler.
   *
   * @param mapping ActionMapping for struts
   * @param form DynaActionForm representing the form
   * @param ctx RequestContext request context
   * @param response HttpServletResponse response object
   * @param step WizardStep what step are we on?
   * @return ActionForward struts action forward
   * @throws Exception if something goes amiss
   */
  public ActionForward runFourth(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {

    log.debug("runFourth");
    if (!validateFirstSelections(form, ctx)) {
      return runFirst(mapping, form, ctx, response, step);
    }
    Long sid = (Long) form.get(RequestContext.SID);
    String cobblerId = form.getString(RequestContext.COBBLER_ID);

    log.debug("runFourth.cobblerId: " + cobblerId);

    User user = ctx.getCurrentUser();
    Server server = SystemManager.lookupByIdAndUser(sid, user);

    Map params = new HashMap();
    params.put(RequestContext.SID, sid);

    log.debug("Creating cobbler system record");
    org.cobbler.Profile profile =
        org.cobbler.Profile.lookupById(CobblerXMLRPCHelper.getConnection(user), cobblerId);

    KickstartData data =
        KickstartFactory.lookupKickstartDataByCobblerIdAndOrg(user.getOrg(), profile.getUid());

    if (showDiskWarning(data, form)) {
      form.set(NEXT_ACTION, "fourth");
      return mapping.findForward("fifth");
    }

    CobblerSystemCreateCommand cmd =
        new CobblerSystemCreateCommand(server, profile.getName(), data);
    cmd.store();
    log.debug("cobbler system record created.");
    String[] args = new String[2];
    args[0] = server.getName();
    args[1] = profile.getName();
    createMessage(ctx.getRequest(), "kickstart.schedule.cobblercreate", args);
    return getStrutsDelegate().forwardParams(mapping.findForward("cobbler-success"), params);
  }
  public void testKsSessionPathparse() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    KickstartSession session = KickstartSessionTest.createKickstartSession(ksdata, user);
    KickstartFactory.saveKickstartSession(session);
    session = (KickstartSession) reload(session);
    assertNotSame(session.getState(), KickstartFactory.SESSION_STATE_CONFIG_ACCESSED);

    String encodedSession = SessionSwap.encodeData(session.getId().toString());
    // URL: /kickstart/ks/session/2xb7d56e8958b0425e762cc74e8705d8e7
    String url = "http://rhn.redhat.com/session/ks/session/" + encodedSession;
    request.setAttribute(RequestContext.REQUESTED_URI, url);
    Map<String, Object> options = helper.parseKickstartUrl(url);
    assertNotNull(options);
    assertNotNull(options.get("org_id"));
    assertNotNull(options.get("ksdata"));
    assertNotNull(options.get("session"));
    assertNotNull(options.get("host"));
    assertEquals(session.getState(), KickstartFactory.SESSION_STATE_CONFIG_ACCESSED);
  }
  public void testDelete() throws Exception {
    CryptoKey key = CryptoTest.createTestKey(user.getOrg());
    KickstartFactory.saveCryptoKey(key);
    assertNotNull(KickstartFactory.lookupCryptoKeyById(key.getId(), key.getOrg()));
    flushAndEvict(key);
    KickstartFactory.removeCryptoKey(key);
    assertNull(KickstartFactory.lookupCryptoKeyById(key.getId(), key.getOrg()));

    // second method
    CryptoKey key2 = CryptoTest.createTestKey(user.getOrg());
    KickstartFactory.saveCryptoKey(key2);
    assertNotNull(KickstartFactory.lookupCryptoKeyById(key2.getId(), key2.getOrg()));
    flushAndEvict(key2);

    // CryptoKey will be deleted by the cmd.store command in setupKey
    setupKey(new DeleteCryptoKeyCommand(user, key2.getId()));
    assertNull(KickstartFactory.lookupCryptoKeyById(key2.getId(), key2.getOrg()));
  }
  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());
  }
 /**
  * Returns the kickstart schedule command
  *
  * @param form the dyna aciton form
  * @param ctx the request context
  * @param scheduleTime the schedule time
  * @param host the host url.
  * @return the Ks schedule command
  */
 protected KickstartScheduleCommand getScheduleCommand(
     DynaActionForm form, RequestContext ctx, Date scheduleTime, String host) {
   String cobblerId = form.getString(RequestContext.COBBLER_ID);
   User user = ctx.getCurrentUser();
   KickstartScheduleCommand cmd;
   KickstartData data =
       KickstartFactory.lookupKickstartDataByCobblerIdAndOrg(user.getOrg(), cobblerId);
   if (data != null) {
     cmd =
         new KickstartScheduleCommand(
             (Long) form.get(RequestContext.SID), data, ctx.getCurrentUser(), scheduleTime, host);
   } else {
     org.cobbler.Profile profile =
         org.cobbler.Profile.lookupById(CobblerXMLRPCHelper.getConnection(user), cobblerId);
     cmd =
         KickstartScheduleCommand.createCobblerScheduleCommand(
             (Long) form.get(RequestContext.SID), profile.getName(), user, scheduleTime, host);
   }
   return cmd;
 }
  private Profile processProfileType(String profileTypeIn) {
    log.debug("PROFILE_TYPE=" + profileTypeIn);

    if (profileTypeIn == null
        || profileTypeIn.length() == 0
        || // TODO: fix this hack
        profileTypeIn.equals(TARGET_PROFILE_TYPE_NONE)) {
      return null;
    }
    Profile retval = null;
    // Profile of this existing system's packages
    String pname =
        LocalizationService.getInstance()
            .getMessage("kickstart.session.newprofile", this.kickstartSession.getId().toString());
    if (profileTypeIn.equals(TARGET_PROFILE_TYPE_EXISTING)) {
      log.debug("    TARGET_PROFILE_TYPE_EXISTING");
      // "Profile for kickstart session "
      retval =
          ProfileManager.createProfile(
              ProfileFactory.TYPE_SYNC_PROFILE,
              this.user,
              getTargetServer().getBaseChannel(),
              pname,
              pname);
      ProfileManager.copyFrom(this.server, retval);
    }
    // Profile of 'stored profile'
    else if (profileTypeIn.equals(TARGET_PROFILE_TYPE_PACKAGE)) {
      log.debug("    TARGET_PROFILE_TYPE_PACKAGE");
      if (this.profileId == null) {
        throw new UnsupportedOperationException(
            "You specified a target profile type"
                + TARGET_PROFILE_TYPE_PACKAGE
                + " but this.profileId is null");
      }
      retval = ProfileManager.lookupByIdAndOrg(this.profileId, this.user.getOrg());
    }
    // Some other system's profile
    else if (profileTypeIn.equals(TARGET_PROFILE_TYPE_SYSTEM)) {
      Server otherServer = ServerFactory.lookupById(this.serverProfileId);
      log.debug("    TARGET_PROFILE_TYPE_SYSTEM");
      log.debug("    this.serverProfileId      : " + this.serverProfileId);
      log.debug("    otherServer               : " + otherServer);
      if (otherServer != null) {
        log.debug("otherServer.Id            : " + otherServer.getId());
        log.debug("otherServer.getBaseChannel: " + otherServer.getBaseChannel());
      }

      retval =
          ProfileManager.createProfile(
              ProfileFactory.TYPE_SYNC_PROFILE,
              this.user,
              otherServer.getBaseChannel(),
              pname,
              pname);
      ProfileManager.copyFrom(otherServer, retval);
    }
    this.kickstartSession.setServerProfile(retval);
    KickstartFactory.saveKickstartSession(this.kickstartSession);

    if (getTargetServer() != null) {
      HibernateFactory.getSession().refresh(getTargetServer());
    }

    // TODO: Compute missing packages and forward user to the missing page

    return retval;
  }
 /**
  * Create new Command and Key
  *
  * @param currentUser who wants to create the key
  * @param keyId of key to lookup.
  */
 public EditCryptoKeyCommand(User currentUser, Long keyId) {
   super();
   this.key = KickstartFactory.lookupCryptoKeyById(keyId, currentUser.getOrg());
 }