/**
   * 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 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);
    }
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);

    if (request.getParameter("dispatch") != null) {
      if (requestContext.wasDispatched("installconfirm.jsp.confirm")) {
        return executePackageAction(mapping, formIn, request, response);
      }
    }

    List<PackageListItem> items = getDataResult(request);

    Server server = requestContext.lookupAndBindServer();

    /*
     * If we are removing a package that is not in a channel the server is
     *  subscribed to, then the rollback will not work, lets give the user
     *  a message telling them that.
     */
    if (this instanceof RemoveConfirmSetupAction
        && server.hasEntitlement(EntitlementManager.PROVISIONING)) {
      for (PackageListItem item : items) {
        Map<String, Long> map = item.getKeyMap();
        if (!SystemManager.hasPackageAvailable(
            server, map.get("name_id"), map.get("arch_id"), map.get("evr_id"))) {
          ActionMessages msgs = new ActionMessages();
          msgs.add(
              ActionMessages.GLOBAL_MESSAGE, new ActionMessage("package.remove.cant.rollback"));
          getStrutsDelegate().saveMessages(request, msgs);
          break;
        }
      }
    }

    DynaActionForm dynaForm = (DynaActionForm) formIn;
    DatePicker picker =
        getStrutsDelegate()
            .prepopulateDatePicker(request, dynaForm, "date", DatePicker.YEAR_RANGE_POSITIVE);
    request.setAttribute("date", picker);

    ActionChainHelper.prepopulateActionChains(request);

    request.setAttribute("system", server);
    requestContext.copyParamToAttributes(RequestContext.SID);
    request.setAttribute(
        ListTagHelper.PARENT_URL, request.getRequestURI() + "?sid=" + server.getId());
    request.setAttribute(WIDGET_SUMMARY, getWidgetSummary());
    request.setAttribute(HEADER_KEY, getHeaderKey());
    request.setAttribute(DATA_SET, items);

    return getStrutsDelegate()
        .forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD), request.getParameterMap());
  }
 public void testGetServerNeededUpdatePackageByName() throws Exception {
   user.addRole(RoleFactory.ORG_ADMIN);
   Server s = ServerFactoryTest.createTestServer(user);
   Channel c = ChannelFactoryTest.createTestChannel(user);
   addPackageToSystemAndChannel("some-test-package", s, c);
   // Not enough time actually test the results of this query for now
   // Just testing that it runs without SQL error. -mmccune
   assertNull(PackageManager.getServerNeededUpdatePackageByName(s.getId(), "some-test-package"));
 }
  /**
   * This method inserts a record into the rhnServerPackage mapping table to associate a given
   * Server with a particular Package. The web code doesn't actually create any of these records,
   * but this will be needed by the backend code.
   *
   * @param srvr Server to associate with the packages
   * @param p The package
   */
  public static void associateSystemToPackage(Server srvr, Package p) {
    try {
      WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPackageSimple");
      Map params = new HashMap();
      params.put("server_id", srvr.getId());
      params.put("name_id", p.getPackageName().getId());
      params.put("evr_id", p.getPackageEvr().getId());

      m.executeUpdate(params);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Get the id of the Package installed for this KS. Here we'll verify that the kickstart package
   * exists in the host server's tools channel. The host server will need it to perform necessary
   * actions on either itself or the target system (if different).
   *
   * @return Long id of Package used for this KS.
   */
  public ValidatorError validateKickstartPackage() {
    if (cobblerOnly) {
      return null;
    }

    Server hostServer = getHostServer();
    Set<Long> serverChannelIds = new HashSet<Long>();
    Iterator<Channel> i = hostServer.getChannels().iterator();
    while (i.hasNext()) {
      Channel c = i.next();
      serverChannelIds.add(c.getId());
    }

    // check for package among channels the server is subscribed to.
    // If one is found, return
    Map<String, Long> pkgToInstall = findKickstartPackageToInstall(hostServer, serverChannelIds);
    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      return null;
    }

    // otherwise search in channels that can be subscribed.
    // If one is found, subscribe channel and return
    Set<Long> subscribableChannelIds =
        SystemManager.subscribableChannelIds(
            hostServer.getId(), this.user.getId(), hostServer.getBaseChannel().getId());
    pkgToInstall = findKickstartPackageToInstall(hostServer, subscribableChannelIds);

    if (pkgToInstall != null) {
      this.packagesToInstall.add(pkgToInstall);
      log.debug("    packagesToInstall: " + packagesToInstall);
      Long cid = pkgToInstall.get("channel_id");
      log.debug("    Subscribing to: " + cid);
      Channel c = ChannelFactory.lookupById(cid);
      try {
        SystemManager.subscribeServerToChannel(this.user, server, c);
        log.debug("    Subscribed: " + cid);
      } catch (PermissionException pe) {
        return new ValidatorError("kickstart.schedule.cantsubscribe");
      } catch (Exception e) {
        return new ValidatorError(
            "kickstart.schedule.cantsubscribe.channel", c.getName(), server.getName());
      }
      return null;
    }

    return new ValidatorError(
        "kickstart.schedule.nopackage", this.getKsdata().getChannel().getName());
  }
 protected ActionForward handleSubmit(ActionMapping mapping, RequestContext ctx, Server server) {
   User user = ctx.getCurrentUser();
   RhnSet set = RhnSetDecl.setForSystemCrashes(server).get(user);
   // until we delete crash files from taskomatic, we have to delete them one by one
   for (Iterator<Long> iter =
           RhnSetDecl.setForSystemCrashes(server).get(user).getElementValues().iterator();
       iter.hasNext(); ) {
     CrashManager.deleteCrash(user, iter.next());
   }
   createSuccessMessage(ctx.getRequest(), "message.crashesdeleted", Integer.toString(set.size()));
   Map<String, Object> params = new HashMap<String, Object>();
   params.put("sid", server.getId());
   return getStrutsDelegate().forwardParams(mapping.findForward("delete"), params);
 }
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    Server server = requestContext.lookupAndBindServer();
    Long aid = requestContext.getRequiredParam("aid");

    request.setAttribute("aid", aid);
    request.setAttribute("referrerLink", "History.do");
    request.setAttribute("linkLabel", "system.event.return");
    request.setAttribute("headerLabel", "system.event.header");

    Action action;
    ServerAction serverAction;
    try {
      action = ActionManager.lookupAction(requestContext.getCurrentUser(), aid);
      serverAction = ActionFactory.getServerActionForServerAndAction(server, action);
    } catch (LookupException e) {
      ServerHistoryEvent event = ActionFactory.lookupHistoryEventById(aid);
      request.setAttribute("actiontype", event.getSummary());
      request.setAttribute("earliestaction", event.getCreated());
      request.setAttribute("actionnotes", event.getDetails());
      request.setAttribute("failed", false);
      return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
    }
    ActionFormatter af = action.getFormatter();
    request.setAttribute("actionname", af.getName());
    request.setAttribute("actiontype", af.getActionType());
    request.setAttribute("scheduler", af.getScheduler());
    request.setAttribute("earliestaction", af.getEarliestDate());
    request.setAttribute("actionnotes", af.getDetails(server, requestContext.getCurrentUser()));
    request.setAttribute("failed", serverAction.getStatus().equals(ActionFactory.STATUS_FAILED));
    if (!serverAction.getStatus().equals(ActionFactory.STATUS_COMPLETED)
        && !serverAction.getStatus().equals(ActionFactory.STATUS_FAILED)) {
      request.setAttribute("referrerLink", "Pending.do");
      request.setAttribute("linkLabel", "system.event.pendingReturn");
      request.setAttribute("headerLabel", "system.event.pendingHeader");
    }
    if (isSubmitted((DynaActionForm) formIn)) {
      createSuccessMessage(request, "system.event.rescheduled", action.getName());
      ActionFactory.rescheduleSingleServerAction(action, 5L, server.getId());
      return mapping.findForward("continue");
    }

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  /**
   * This method inserts a record into the rhnServerPackage mapping table to associate a given
   * Server with a particular Package. The web code doesn't actually create any of these records,
   * but this will be needed by the backend code.
   *
   * @param srvr Server to associate with the packages
   * @param pn The package name to associate
   * @param pe The package evr (version and release).
   */
  public static void associateSystemToPackage(Server srvr, PackageName pn, PackageEvr pe) {
    try {
      WriteMode m = ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPackage");
      Map params = new HashMap();
      params.put("server_id", srvr.getId());
      params.put("pn_id", pn.getId());
      params.put("p_epoch", pe.getEpoch());
      params.put("p_version", pe.getVersion());
      params.put("p_release", pe.getRelease());

      m.executeUpdate(params);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testExecute() throws Exception {
    // Create a config channel and a server
    ConfigChannel channel = ConfigTestUtils.createConfigChannel(user.getOrg());
    Server server =
        ServerFactoryTest.createTestServer(
            user, true, ServerConstants.getServerGroupTypeProvisioningEntitled());
    // associate the two.
    server.subscribe(channel);
    SystemManager.storeServer(server);

    setRequestPathInfo("/systems/details/configuration/ConfigChannelList");
    addRequestParameter("sid", server.getId().toString());
    actionPerform();
    verifyPageList(ConfigChannelDto.class);
  }
  private void showMessages(
      ActionMessages msgs, Action action, Server server, int pkgcnt, String mode) {
    String key = null;

    if (MODE_INSTALL.equals(mode)) {
      key = "message.packageinstall";
    } else if (MODE_REMOVAL.equals(mode)) {
      key = "message.packageremoval";
    } else { // must be upgrade
      key = "message.packageupgrade";
    }

    /**
     * If there was only one action archived, display the "action" archived message, else display
     * the "actions" archived message.
     */
    if (pkgcnt == 1) {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              key,
              LocalizationService.getInstance().formatNumber(new Integer(pkgcnt)),
              action.getId().toString(),
              server.getId().toString(),
              server.getName()));
    } else {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              key + "s",
              LocalizationService.getInstance().formatNumber(new Integer(pkgcnt)),
              action.getId().toString(),
              server.getId().toString(),
              server.getName()));
    }
  }
Example #12
0
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    User user = requestContext.getCurrentUser();
    Long sid = requestContext.getRequiredParam("sid");
    RhnSet set = getSetDecl(sid).get(user);

    ListRhnSetHelper help = new ListRhnSetHelper(this, request, getSetDecl(sid));
    help.setListName(LIST_NAME);
    String parentURL = request.getRequestURI() + "?sid=" + sid;
    help.setParentUrl(parentURL);

    help.execute();

    if (help.isDispatched()) {
      if (requestContext.wasDispatched("errata.jsp.apply")) {
        return applyErrata(mapping, formIn, request, response);
      }
    }

    String showButton = "true";
    // Show the "Apply Errata" button only when unapplied errata exist:
    if (!SystemManager.hasUnscheduledErrata(user, sid)) {
      showButton = "false";
    }

    Map params = new HashMap();
    Set keys = request.getParameterMap().keySet();
    for (Iterator i = keys.iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      params.put(key, request.getParameter(key));
    }

    Server server = SystemManager.lookupByIdAndUser(sid, user);
    SdcHelper.ssmCheck(request, server.getId(), user);
    request.setAttribute("showApplyErrata", showButton);
    request.setAttribute("set", set);
    request.setAttribute("system", server);
    request.setAttribute("combo", getComboList(request));
    request.setAttribute(SELECTOR, request.getParameter(SELECTOR));

    return getStrutsDelegate()
        .forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
  }
  /**
   * This method inserts a record into the rhnServerPackage mapping table to associate a given
   * Server with a particular Package. The web code doesn't actually create any of these records,
   * but this will be needed by the backend code.
   *
   * @param srvr Server to associate with the packages
   * @param p The package
   */
  public static void associateSystemToPackageWithArch(Server srvr, Package p) {
    try {
      WriteMode m =
          ModeFactory.getWriteMode("test_queries", "insert_into_rhnServerPackage_with_arch");

      Map<String, Long> params = new HashMap<String, Long>(4);
      params.put("server_id", srvr.getId());
      params.put("pn_id", p.getPackageName().getId());
      params.put("evr_id", p.getPackageEvr().getId());
      params.put("arch_id", p.getPackageArch().getId());

      m.executeUpdate(params);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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);
  }
 /** {@inheritDoc} */
 public ActionForward execute(
     ActionMapping mapping,
     ActionForm formIn,
     HttpServletRequest request,
     HttpServletResponse response) {
   RequestContext ctx = new RequestContext(request);
   Server server = ctx.lookupAndBindServer();
   User user = ctx.getCurrentUser();
   SdcHelper.ssmCheck(ctx.getRequest(), server.getId(), user);
   DynaActionForm form = (DynaActionForm) formIn;
   SystemRecord rec = (SystemRecord) getCobblerObject(server.getCobblerId(), user);
   if (isSubmitted(form)) {
     if (!Boolean.valueOf(rec.isNetbootEnabled()).equals(form.get(NETBOOT_ENABLED))) {
       rec.enableNetboot(Boolean.TRUE.equals(form.get(NETBOOT_ENABLED)));
       rec.save();
     }
   }
   form.set(NETBOOT_ENABLED, rec.isNetbootEnabled());
   return super.execute(mapping, formIn, request, response);
 }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext context = new RequestContext(request);
    context.copyParamToAttributes("sid");
    Server server = context.lookupAndBindServer();

    ListRhnSetHelper helper =
        new ListRhnSetHelper(this, request, RhnSetDecl.setForSystemCrashes(server));
    helper.execute();
    if (helper.isDispatched()) {
      return handleSubmit(mapping, context, server);
    }

    SdcHelper.ssmCheck(request, server.getId(), context.getCurrentUser());

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  /** {@inheritDoc} */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {
    RequestContext context = new RequestContext(request);
    User user = context.getCurrentUser();
    Long sid = context.getRequiredParam("sid");
    Server server = SystemManager.lookupByIdAndUser(sid, user);
    Long xid = context.getRequiredParam("xid");
    XccdfTestResult testResult = ScapFactory.lookupTestResultByIdAndSid(xid, server.getId());
    request.setAttribute("testResult", testResult);
    request.setAttribute("system", server);

    ListHelper helper = new ListHelper(this, request);
    helper.execute();

    request.setAttribute(
        ListTagHelper.PARENT_URL, request.getRequestURI() + "?sid=" + sid + "&xid=" + xid);
    SdcHelper.ssmCheck(request, sid, user);

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  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);
  }
  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());
  }
Example #20
0
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext context = new RequestContext(request);
    User user = context.getCurrentUser();
    Server server = context.lookupAndBindServer();
    ListSessionSetHelper helper = new ListSessionSetHelper(this, request);
    helper.execute();

    if (helper.isDispatched()) {
      ServerGroupManager manager = ServerGroupManager.getInstance();
      List<Server> servers = new LinkedList<Server>();
      servers.add(server);

      for (String id : helper.getSet()) {
        ServerGroup group = manager.lookup(Long.valueOf(id), user);
        manager.addServers(group, servers, user);
      }
      helper.destroy();
      getStrutsDelegate()
          .saveMessage(
              "systems.groups.jsp.added",
              new String[] {String.valueOf(helper.getSet().size())},
              request);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put(RequestContext.SID, server.getId().toString());
      StrutsDelegate strutsDelegate = getStrutsDelegate();
      return strutsDelegate.forwardParams(mapping.findForward("success"), params);
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
  }
  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;
  }
  // Check to make sure up2date is 2.9.0
  protected ValidatorError validateUp2dateVersion() {
    Server hostServer = getHostServer();
    List packages = PackageManager.systemPackageList(hostServer.getId(), null);
    if (packages != null) {
      log.debug("    packages.size() : " + packages.size());
    }
    // PackageListItem
    Iterator i = packages.iterator();
    String up2dateepoch = null;
    String up2dateversion = null;
    String up2daterelease = null;

    while (i.hasNext()) {
      PackageListItem pli = (PackageListItem) i.next();
      if (pli.getName().equals("yum-rhn-plugin")) {
        // found yum-rhn-plugin - returning
        return null;
      }
      if (pli.getName().equals("zypp-plugin-spacewalk")) {
        // found zypp-plugin-spacewalk - returning
        return null;
      }

      if (pli.getName().equals("up2date")) {
        log.debug("    found up2date ...");
        up2dateepoch = pli.getEpoch();
        up2dateversion = pli.getVersion();
        up2daterelease = pli.getRelease();

        log.debug("    e: " + up2dateepoch + " v: " + up2dateversion + " r : " + up2daterelease);
      }
    }

    if (up2dateepoch == null && up2dateversion == null && up2daterelease == null) {
      Object[] args = new Object[2];
      args[0] = hostServer.getId();
      args[1] = hostServer.getName();
      return new ValidatorError("kickstart.schedule.noup2date", args);
    }

    up2dateepoch = up2dateepoch == null ? "0" : up2dateepoch;
    up2dateversion = up2dateversion == null ? "0" : up2dateversion;
    up2daterelease = up2daterelease == null ? "0" : up2daterelease;

    int comp =
        PackageManager.verCmp(
            up2dateepoch, up2dateversion, up2daterelease, "0", UP2DATE_VERSION, "0");
    log.debug("    Got back comp from verCmp: " + comp);
    if (comp < 0) {
      Long packageId =
          PackageManager.getServerNeededUpdatePackageByName(hostServer.getId(), "up2date");
      if (packageId == null) {
        Object[] args = new Object[2];
        args[0] = UP2DATE_VERSION;
        args[1] = up2dateversion;
        return new ValidatorError("kickstart.schedule.noup2dateinchannel", args);
      }
      Package p = PackageFactory.lookupByIdAndUser(packageId, this.user);

      Map evrmap = new HashMap();
      evrmap.put("name_id", p.getPackageName().getId());
      evrmap.put("evr_id", p.getPackageEvr().getId());
      evrmap.put("arch_id", p.getPackageArch().getId());
      packagesToInstall.add(evrmap);
    } else {
      return null;
    }

    return null;
  }
 @Override
 protected DataResult<PackageListItem> getDataResult(Server server) {
   return SystemManager.listExtraPackages(server.getId());
 }
  /**
   * The first step in the wizard
   *
   * @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 runFirst(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {
    log.debug("runFirst");
    Long sid = (Long) form.get(RequestContext.SID);
    User user = ctx.getCurrentUser();

    KickstartScheduleCommand cmd = getKickstartScheduleCommand(sid, user);

    Server system = SystemManager.lookupByIdAndUser(sid, user);
    if (system.isVirtualGuest()
        && VirtualInstanceFactory.getInstance()
            .getParaVirtType()
            .equals(system.getVirtualInstance().getType())) {
      ctx.getRequest().setAttribute(IS_VIRTUAL_GUEST, Boolean.TRUE.toString());

      ctx.getRequest().setAttribute(VIRT_HOST_IS_REGISTERED, Boolean.FALSE.toString());
      if (system.getVirtualInstance().getHostSystem() != null) {
        Long hostSid = system.getVirtualInstance().getHostSystem().getId();
        ctx.getRequest().setAttribute(VIRT_HOST_IS_REGISTERED, Boolean.TRUE.toString());
        ctx.getRequest().setAttribute(HOST_SID, hostSid);
      }
    } else {
      ctx.getRequest().setAttribute(IS_VIRTUAL_GUEST, Boolean.FALSE.toString());
    }

    addRequestAttributes(ctx, cmd, form);
    checkForKickstart(form, cmd, ctx);
    setupProxyInfo(ctx);
    if (StringUtils.isBlank(form.getString(PROXY_HOST))) {
      form.set(PROXY_HOST, "");
    }
    // create and prepopulate the date picker.
    getStrutsDelegate()
        .prepopulateDatePicker(ctx.getRequest(), form, "date", DatePicker.YEAR_RANGE_POSITIVE);

    SdcHelper.ssmCheck(ctx.getRequest(), system.getId(), user);
    Map params = new HashMap<String, String>();
    params.put(RequestContext.SID, sid);
    ListHelper helper = new ListHelper(new Profiles(), ctx.getRequest(), params);
    helper.execute();
    if (!StringUtils.isBlank(form.getString(RequestContext.COBBLER_ID))) {
      ListTagHelper.selectRadioValue(
          ListHelper.LIST, form.getString(RequestContext.COBBLER_ID), ctx.getRequest());
    } else if (system.getCobblerId() != null) {
      // if nothing is selected by the user yet, use the cobbler
      //  system record to pre-select something.
      SystemRecord rec =
          SystemRecord.lookupById(
              CobblerXMLRPCHelper.getConnection(ConfigDefaults.get().getCobblerAutomatedUser()),
              system.getCobblerId());
      if (rec != null) {
        ListTagHelper.selectRadioValue(ListHelper.LIST, rec.getProfile().getId(), ctx.getRequest());
      }
    }

    ActionForward retval = mapping.findForward("first");
    return retval;
  }