/**
   * The second 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 runSecond(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {
    log.debug("runSecond");

    if (!StringUtils.isBlank(form.getString(HIDDEN_BOND_SLAVE_INTERFACES))) {
      form.set(BOND_SLAVE_INTERFACES, form.getString(HIDDEN_BOND_SLAVE_INTERFACES).split(","));
    }

    Long sid = (Long) form.get(RequestContext.SID);
    User user = ctx.getCurrentUser();

    if (!validateFirstSelections(form, ctx)) {
      return runFirst(mapping, form, ctx, response, step);
    }
    KickstartScheduleCommand cmd = getScheduleCommand(form, ctx, null, null);

    checkForKickstart(form, cmd, ctx);
    addRequestAttributes(ctx, cmd, form);
    if (!cmd.isCobblerOnly()) {
      List packageProfiles = cmd.getProfiles();
      form.set(SYNCH_PACKAGES, packageProfiles);
      List systemProfiles = cmd.getCompatibleSystems();
      form.set(SYNCH_SYSTEMS, systemProfiles);

      // Disable the package/system sync radio buttons if no profiles are
      // available:
      String syncPackageDisabled = "false";
      if (packageProfiles.size() == 0) {
        syncPackageDisabled = "true";
      }
      String syncSystemDisabled = "false";
      if (systemProfiles.size() == 0) {
        syncSystemDisabled = "true";
      }
      ctx.getRequest().setAttribute(SYNC_PACKAGE_DISABED, syncPackageDisabled);
      ctx.getRequest().setAttribute(SYNC_SYSTEM_DISABLED, syncSystemDisabled);

      if (StringUtils.isEmpty(form.getString(TARGET_PROFILE_TYPE))) {
        form.set(TARGET_PROFILE_TYPE, KickstartScheduleCommand.TARGET_PROFILE_TYPE_NONE);
      }
    } else {
      ctx.getRequest().setAttribute(COBBLER_ONLY_PROFILE, Boolean.TRUE);
    }

    if (StringUtils.isEmpty(form.getString(KERNEL_PARAMS_TYPE))) {
      form.set(KERNEL_PARAMS_TYPE, KERNEL_PARAMS_DISTRO);
    }

    if (StringUtils.isEmpty(form.getString(POST_KERNEL_PARAMS_TYPE))) {
      form.set(POST_KERNEL_PARAMS_TYPE, KERNEL_PARAMS_DISTRO);
    }

    SdcHelper.ssmCheck(ctx.getRequest(), sid, user);
    return mapping.findForward("second");
  }
  private PackageAction syncToVictim(
      RequestContext requestContext, Long sid, Set pkgIdCombos, String option) {

    PackageAction pa = null;
    Date time = new Date(requestContext.getParamAsLong("time"));

    if (isProfileSync(requestContext)) {
      Long prid = requestContext.getRequiredParam("prid");

      pa =
          ProfileManager.syncToProfile(
              requestContext.getCurrentUser(), sid, prid, pkgIdCombos, option, time);

      if (pa == null) {
        createMessage(requestContext.getRequest(), "message.nopackagestosync");
        return null;
      }

      List args = new ArrayList();
      args.add(sid.toString());
      args.add(pa.getId().toString());
      args.add(requestContext.lookupAndBindServer().getName());
      args.add(
          ProfileManager.lookupByIdAndOrg(prid, requestContext.getCurrentUser().getOrg())
              .getName());

      createMessage(requestContext.getRequest(), "message.syncpackages", args);
    } else if (isSystemSync(requestContext)) {
      Long sid1 = requestContext.getRequiredParam("sid_1");
      pa =
          ProfileManager.syncToSystem(
              requestContext.getCurrentUser(), sid, sid1, pkgIdCombos, option, time);

      if (pa == null) {
        createMessage(requestContext.getRequest(), "message.nopackagestosync");
        return null;
      }

      List args = new ArrayList();
      args.add(sid.toString());
      args.add(pa.getId().toString());
      args.add(requestContext.lookupAndBindServer().getName());
      args.add(SystemManager.lookupByIdAndUser(sid1, requestContext.getCurrentUser()).getName());

      createMessage(requestContext.getRequest(), "message.syncpackages", args);
    }

    addHardwareMessage(pa, requestContext);

    return pa;
  }
    /** {@inheritDoc} */
    public List getResult(RequestContext ctx) {
      Long sid = ctx.getParamAsLong(RequestContext.SID);
      User user = ctx.getCurrentUser();

      KickstartScheduleCommand cmd = getKickstartScheduleCommand(sid, user);
      DataResult profiles = cmd.getKickstartProfiles();
      if (profiles.size() == 0) {
        addMessage(ctx.getRequest(), "kickstart.schedule.noprofiles");
        ctx.getRequest().setAttribute(HAS_PROFILES, Boolean.FALSE.toString());
      } else {
        ctx.getRequest().setAttribute(HAS_PROFILES, Boolean.TRUE.toString());
      }
      return profiles;
    }
  protected boolean validateFirstSelections(DynaActionForm form, RequestContext ctx) {
    String cobblerId = ListTagHelper.getRadioSelection(ListHelper.LIST, ctx.getRequest());
    if (StringUtils.isBlank(cobblerId)) {
      cobblerId = ctx.getParam(RequestContext.COBBLER_ID, true);
    }

    boolean retval = false;
    form.set(RequestContext.COBBLER_ID, cobblerId);
    ctx.getRequest().setAttribute(RequestContext.COBBLER_ID, cobblerId);
    if (form.get("scheduleAsap") != null) {
      retval = true;
    } else if (form.get(RequestContext.COBBLER_ID) != null) {
      return true;
    }
    return retval;
  }
 /** {@inheritDoc} */
 protected DataResult getDataResult(RequestContext requestContext, ListControl lc) {
   User user = requestContext.getCurrentUser();
   DataResult dr =
       ChannelManager.popularChannelTree(
           user, (Long) requestContext.getRequest().getAttribute("count"), lc);
   return dr;
 }
 private void checkForKickstart(
     DynaActionForm form, KickstartScheduleCommand cmd, RequestContext ctx) {
   if (ActionFactory.doesServerHaveKickstartScheduled((Long) form.get(RequestContext.SID))) {
     String[] params = {cmd.getServer().getName()};
     getStrutsDelegate()
         .saveMessage("kickstart.schedule.already.scheduled.jsp", params, ctx.getRequest());
   }
 }
  /** {@inheritDoc} */
  protected void setupFormValues(
      RequestContext ctx, DynaActionForm form, BaseKickstartCommand cmdIn) {
    KickstartLocaleCommand cmd = (KickstartLocaleCommand) cmdIn;

    ArrayList timezones = cmd.getValidTimezones();
    ctx.getRequest().setAttribute(TIMEZONE_OPTIONS, timezones);

    form.set(TIMEZONE, cmd.getTimezone());
    form.set(USE_UTC, cmd.getKickstartData().isUsingUtc());
  }
  /** {@inheritDoc} */
  public List getResult(RequestContext context) {
    String searchString = (String) context.getRequest().getAttribute(SEARCH_STR);

    if (!StringUtils.isBlank(searchString)) {
      log.debug("SystemSearchSetupAction.getResult() calling performSearch()");
      return performSearch(context);
    }
    log.debug("SystemSearchSetupAction.getResult() returning Collections.EMPTY_LIST");
    return Collections.emptyList();
  }
  /**
   * Sets up the proxy information for the wizard. its public in this class because we reuse this in
   * SSM and only this class knows how to format the name nicely.
   *
   * @param ctx the request context needed for user info and things to bind to the request
   */
  public static void setupProxyInfo(RequestContext ctx) {
    List<OrgProxyServer> proxies = SystemManager.listProxies(ctx.getCurrentUser().getOrg());
    if (proxies != null && proxies.size() > 0) {
      List<LabelValueBean> formatted = new LinkedList<LabelValueBean>();

      formatted.add(lvl10n("kickstart.schedule.default.proxy.jsp", ""));
      Map cnames = new HashMap();
      for (OrgProxyServer serv : proxies) {
        formatted.add(lv(serv.getName() + " (" + serv.getCheckin() + ")", serv.getId().toString()));
        List proxyCnames = Config.get().getList(VALID_CNAMES + serv.getId().toString());
        if (!proxyCnames.isEmpty()) {
          cnames.put(serv.getId().toString(), proxyCnames);
        }
      }
      ctx.getRequest().setAttribute(HAS_PROXIES, Boolean.TRUE.toString());
      ctx.getRequest().setAttribute(PROXIES, formatted);
      ctx.getRequest().setAttribute(CNAMES, cnames);
    } else {
      ctx.getRequest().setAttribute(HAS_PROXIES, Boolean.FALSE.toString());
    }
  }
  private void prepDropdowns(RequestContext ctx) {
    User loggedInUser = ctx.getCurrentUser();
    // populate parent base channels
    List<Map<String, String>> baseChannels = new ArrayList<Map<String, String>>();
    List<Channel> bases = ChannelManager.findAllBaseChannelsForOrg(loggedInUser);

    LocalizationService ls = LocalizationService.getInstance();
    addOption(baseChannels, ls.getMessage("generic.jsp.none"), "");
    for (Channel c : bases) {
      addOption(baseChannels, c.getName(), c.getId().toString());
    }
    ctx.getRequest().setAttribute("parentChannels", baseChannels);

    Map<Long, String> parentChannelArches = new HashMap<Long, String>();
    for (Channel c : bases) {
      parentChannelArches.put(c.getId(), c.getChannelArch().getLabel());
    }
    ctx.getRequest().setAttribute("parentChannelArches", parentChannelArches);

    Map<Long, String> parentChannelChecksums = new HashMap<Long, String>();
    for (Channel c : bases) {
      parentChannelChecksums.put(c.getId(), c.getChecksumTypeLabel());
    }
    ctx.getRequest().setAttribute("parentChannelChecksums", parentChannelChecksums);

    // base channel arches
    List<Map<String, String>> channelArches = new ArrayList<Map<String, String>>();
    List<ChannelArch> arches = ChannelManager.getChannelArchitectures();
    for (ChannelArch arch : arches) {
      addOption(channelArches, arch.getName(), arch.getLabel());
    }
    ctx.getRequest().setAttribute("channelArches", channelArches);
    // set the list of yum supported checksums
    List<Map<String, String>> checksums = new ArrayList<Map<String, String>>();
    addOption(checksums, ls.getMessage("generic.jsp.none"), "");
    for (ChecksumType chType : ChannelFactory.listYumSupportedChecksums()) {
      addOption(checksums, chType.getLabel(), chType.getLabel());
    }
    ctx.getRequest().setAttribute("checksums", checksums);
  }
  protected DataResult performSearch(RequestContext context) {
    HttpServletRequest request = context.getRequest();
    String searchString = (String) request.getAttribute(SEARCH_STR);
    String viewMode = (String) request.getAttribute(VIEW_MODE);
    String whereToSearch = (String) request.getAttribute(WHERE_TO_SEARCH);
    Boolean invertResults =
        StringUtils.defaultString((String) request.getAttribute(INVERT_RESULTS)).equals("on");
    Boolean isFineGrained = (Boolean) request.getAttribute(FINE_GRAINED);

    ActionErrors errs = new ActionErrors();
    DataResult dr = null;
    try {
      dr =
          SystemSearchHelper.systemSearch(
              context, searchString, viewMode, invertResults, whereToSearch, isFineGrained);
    } catch (MalformedURLException e) {
      log.error("Caught Exception :" + e, e);
      errs.add(
          ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.connection_error"));
    } catch (XmlRpcFault e) {
      log.info("Caught Exception :" + e + ", code [" + e.getErrorCode() + "]", e);
      if (e.getErrorCode() == 100) {
        log.error("Invalid search query", e);
        errs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("packages.search.could_not_parse_query", searchString));
      } else if (e.getErrorCode() == 200) {
        log.error("Index files appear to be missing: ", e);
        errs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("packages.search.index_files_missing", searchString));
      } else {
        errs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("packages.search.could_not_execute_query", searchString));
      }
    } catch (XmlRpcException e) {
      log.error("Caught Exception :" + e, e);
      errs.add(
          ActionMessages.GLOBAL_MESSAGE, new ActionMessage("packages.search.connection_error"));
    }
    if (dr == null) {
      ActionMessages messages = new ActionMessages();
      messages.add(
          ActionMessages.GLOBAL_MESSAGE, new ActionMessage("systemsearch_no_matches_found"));
      getStrutsDelegate().saveMessages(request, messages);
    }
    if (!errs.isEmpty()) {
      addErrors(request, errs);
    }
    return dr;
  }
 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);
 }
 protected void addHardwareMessage(PackageAction pa, RequestContext rctx) {
   // If we scheduled a hardware refresh too
   if (pa != null && pa.getPrerequisite() != null) {
     // NOTE: Hardware refresh has been scheduled for
     // cascade.sfbay.redhat.com to be run before the
     // package profile sync.  This is required to verify that the
     // system has the ability to compare packages.
     List hwargs = new ArrayList();
     hwargs.add(rctx.lookupAndBindServer().getId().toString());
     hwargs.add(pa.getPrerequisite().toString());
     hwargs.add(rctx.lookupAndBindServer().getName());
     createMessage(rctx.getRequest(), "message.hardwarerefresh", hwargs);
   }
 }
  protected void addRequestAttributes(
      RequestContext ctx, KickstartScheduleCommand cmd, DynaActionForm form) {
    ctx.getRequest().setAttribute(RequestContext.SYSTEM, cmd.getServer());
    ctx.getRequest().setAttribute(RequestContext.KICKSTART, cmd.getKsdata());
    if (cmd.getKsdata() != null) {
      ctx.getRequest().setAttribute("profile", cmd.getKsdata());
      ctx.getRequest().setAttribute("distro", cmd.getKsdata().getTree());
      CobblerConnection con = CobblerXMLRPCHelper.getConnection(ctx.getCurrentUser());

      Distro distro = Distro.lookupById(con, cmd.getKsdata().getTree().getCobblerId());

      ctx.getRequest().setAttribute("distro_kernel_params", distro.getKernelOptionsString());
      ctx.getRequest()
          .setAttribute("distro_post_kernel_params", distro.getKernelPostOptionsString());

      org.cobbler.Profile profile =
          org.cobbler.Profile.lookupById(con, cmd.getKsdata().getCobblerId());
      ctx.getRequest().setAttribute("profile_kernel_params", profile.getKernelOptionsString());
      ctx.getRequest()
          .setAttribute("profile_post_kernel_params", profile.getKernelPostOptionsString());
      if (cmd.getServer().getCobblerId() != null) {
        SystemRecord rec = SystemRecord.lookupById(con, cmd.getServer().getCobblerId());
        if (rec != null && profile.getName().equals(rec.getProfile().getName())) {
          if (StringUtils.isBlank(form.getString(KERNEL_PARAMS_TYPE))) {
            form.set(KERNEL_PARAMS_TYPE, KERNEL_PARAMS_CUSTOM);
            form.set(KERNEL_PARAMS, rec.getKernelOptionsString());
          }
          if (StringUtils.isBlank(form.getString(POST_KERNEL_PARAMS_TYPE))) {
            form.set(POST_KERNEL_PARAMS_TYPE, KERNEL_PARAMS_CUSTOM);
            form.set(POST_KERNEL_PARAMS, rec.getKernelPostOptionsString());
          }
        }
      }
    }
    setupNetworkInfo(form, ctx, cmd);
    setupBondInfo(form, ctx, cmd);
  }
  /**
   * 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);
  }
 /** {@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);
 }
  private void setupNetworkInfo(
      DynaActionForm form, RequestContext context, KickstartScheduleCommand cmd) {
    Server server = cmd.getServer();
    List<NetworkInterface> nics = getPublicNetworkInterfaces(server);

    if (nics.isEmpty()) {
      return;
    }

    context.getRequest().setAttribute(NETWORK_INTERFACES, nics);

    if (StringUtils.isBlank(form.getString(NETWORK_INTERFACE))) {
      String defaultInterface = ConfigDefaults.get().getDefaultKickstartNetworkInterface();
      for (NetworkInterface nic : nics) {
        if (nic.getName().equals(defaultInterface)) {
          form.set(NETWORK_INTERFACE, ConfigDefaults.get().getDefaultKickstartNetworkInterface());
        }
      }
      if (StringUtils.isBlank(form.getString(NETWORK_INTERFACE))) {
        form.set(NETWORK_INTERFACE, server.findPrimaryNetworkInterface().getName());
      }
    }
  }
 /** {@inheritDoc} */
 public String getParentUrl(RequestContext ctx) {
   return ctx.getRequest().getRequestURI() + "?cid=" + ctx.getParamAsLong("cid");
 }
 /** {@inheritDoc} */
 protected DataResult getDataResult(User u, ActionForm formIn, HttpServletRequest request) {
   RequestContext ctx = new RequestContext(request);
   ConfigChannel cc = ConfigActionHelper.getChannel(ctx.getRequest());
   DataResult dr = ConfigurationManager.getInstance().listSystemInfoForChannel(u, cc, null);
   return dr;
 }
  private void setupBondInfo(
      DynaActionForm form, RequestContext context, KickstartScheduleCommand cmd) {
    Server server = cmd.getServer();
    List<NetworkInterface> nics = new LinkedList<NetworkInterface>(server.getNetworkInterfaces());

    if (nics.isEmpty()) {
      return;
    }

    for (Iterator<NetworkInterface> itr = nics.iterator(); itr.hasNext(); ) {
      NetworkInterface nic = itr.next();
      if ("127.0.0.1".equals(nic.getIpaddr())) {
        itr.remove();
      }
    }

    context.getRequest().setAttribute(ALL_NETWORK_INTERFACES, nics);

    if (StringUtils.isBlank(form.getString(BOND_TYPE))) {
      form.set(BOND_TYPE, DONT_CREATE_BOND_VALUE);
    }

    NetworkInterface oldBond = null;
    for (NetworkInterface nic : nics) {
      if (nic.isBond()) {
        oldBond = nic;
        break;
      }
    }

    if (oldBond != null) {
      if (StringUtils.isBlank(form.getString(BOND_INTERFACE))) {
        form.set(BOND_INTERFACE, oldBond.getName());
      }

      if (StringUtils.isBlank(form.getString(BOND_IP_ADDRESS))) {
        form.set(BOND_IP_ADDRESS, oldBond.getIpaddr());
      }

      if (StringUtils.isBlank(form.getString(BOND_NETMASK))) {
        form.set(BOND_NETMASK, oldBond.getNetmask());
      }
    }

    String[] slaves = (String[]) form.get(BOND_SLAVE_INTERFACES);
    if (slaves == null || slaves.length == 0) {
      List<String> slavesList = new ArrayList<String>();
      // if there is a bonded interface on the system
      if (!StringUtils.isBlank(form.getString(BOND_INTERFACE))) {
        for (NetworkInterface nic : nics) {
          // if the nic does not have an IP address it is probably a
          // slave to the bond, add it to the default selected list
          if (StringUtils.isBlank(nic.getIpaddr())) {
            slavesList.add(nic.getName());
          }
        }
      }

      form.set(BOND_SLAVE_INTERFACES, convertToStringArray(slavesList.toArray()));
    }
  }
  /**
   * 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;
  }
  protected boolean validateBondSelections(DynaActionForm form, RequestContext ctx) {
    if (!StringUtils.isBlank(form.getString(HIDDEN_BOND_SLAVE_INTERFACES))) {
      form.set(BOND_SLAVE_INTERFACES, form.getString(HIDDEN_BOND_SLAVE_INTERFACES).split(","));
    }

    String[] slaves = (String[]) form.get(BOND_SLAVE_INTERFACES);
    ActionErrors errors = new ActionErrors();

    // if we are trying to create a bond but have not specified a name or at
    // least one slave interface
    if (form.getString(BOND_TYPE).equals(CREATE_BOND_VALUE)
        && (StringUtils.isBlank(form.getString(BOND_INTERFACE))
            || slaves.length < 1
            || StringUtils.isBlank(slaves[0]))) {
      errors.add(
          ActionMessages.GLOBAL_MESSAGE, new ActionMessage("kickstart.bond.not.defined.jsp"));
    }

    final String ipv4addressPattern =
        "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
            + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
            + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
            + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    /*
     * The IPv6 address regex was created by Stephen Ryan at Dartware
     * and taken from this forum: http://forums.intermapper.com/viewtopic.php?t=452
     * It is licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported
     * License. We can freely use it in (even in commercial products) as long as
     * we attribute its creation to him, so don't remove this message.
     */
    final String ipv6addressPattern =
        "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-"
            + "F]{1,4}::?){0,5}|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$))"
            + "{0,2}|((25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,"
            + "4}:[0-9A-F]{1,4})(?<![^:]:|\\.)\\z";

    if (form.getString(BOND_STATIC).equals(STATIC_BOND_VALUE)) {
      String address = form.getString(BOND_IP_ADDRESS);
      String netmask = form.getString(BOND_NETMASK);
      String gateway = form.getString(BOND_GATEWAY);

      if (!address.matches(ipv4addressPattern) && !address.matches(ipv6addressPattern)) {
        errors.add(
            ActionMessages.GLOBAL_MESSAGE, new ActionMessage("kickstart.bond.bad.ip.address.jsp"));
      }

      if (!netmask.matches(ipv4addressPattern) && !netmask.matches(ipv6addressPattern)) {
        errors.add(
            ActionMessages.GLOBAL_MESSAGE, new ActionMessage("kickstart.bond.bad.netmask.jsp"));
      }

      if (!gateway.matches(ipv4addressPattern) && !gateway.matches(ipv6addressPattern)) {
        errors.add(
            ActionMessages.GLOBAL_MESSAGE, new ActionMessage("kickstart.bond.bad.ip.address.jsp"));
      }
    }

    if (errors.size() > 0) {
      addErrors(ctx.getRequest(), errors);
      return false;
    }
    return true;
  }
  /**
   * The third 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 runThird(
      ActionMapping mapping,
      DynaActionForm form,
      RequestContext ctx,
      HttpServletResponse response,
      WizardStep step)
      throws Exception {
    log.debug("runThird");
    if (!validateBondSelections(form, ctx)) {
      return runSecond(mapping, form, ctx, response, step);
    }
    if (!validateFirstSelections(form, ctx)) {
      return runFirst(mapping, form, ctx, response, step);
    }
    String scheduleAsap = form.getString("scheduleAsap");
    Date scheduleTime = null;
    if (scheduleAsap != null && scheduleAsap.equals("false")) {
      scheduleTime =
          getStrutsDelegate().readDatePicker(form, "date", DatePicker.YEAR_RANGE_POSITIVE);
    } else {
      scheduleTime = new Date();
    }
    KickstartHelper helper = new KickstartHelper(ctx.getRequest());
    KickstartScheduleCommand cmd =
        getScheduleCommand(form, ctx, scheduleTime, helper.getKickstartHost());

    if (showDiskWarning(cmd.getKsdata(), form)) {
      form.set(NEXT_ACTION, "third");
      addRequestAttributes(ctx, cmd, form);
      return mapping.findForward("fifth");
    }
    cmd.setNetworkDevice(form.getString(NETWORK_TYPE), form.getString(NETWORK_INTERFACE));

    if (CREATE_BOND_VALUE.equals(form.getString(BOND_TYPE))) {
      cmd.setCreateBond(true);
      cmd.setBondInterface(form.getString(BOND_INTERFACE));
      cmd.setBondOptions(form.getString(BOND_OPTIONS));
      String[] slaves = (String[]) form.get(BOND_SLAVE_INTERFACES);
      List<String> tmp = new ArrayList<String>();
      for (String slave : slaves) {
        tmp.add(slave);
      }
      cmd.setBondSlaveInterfaces(tmp);
      if (STATIC_BOND_VALUE.equals(form.getString(BOND_STATIC))) {
        cmd.setBondDhcp(false);
        cmd.setBondAddress(form.getString(BOND_IP_ADDRESS));
        cmd.setBondNetmask(form.getString(BOND_NETMASK));
        cmd.setBondGateway(form.getString(BOND_GATEWAY));
      } else {
        cmd.setBondDhcp(true);
      }
    }

    if (form.getString(USE_IPV6_GATEWAY).equals("1")) {
      cmd.setIpv6Gateway();
    }
    cmd.setKernelOptions(
        parseKernelOptions(
            form, ctx.getRequest(), form.getString(RequestContext.COBBLER_ID), false));
    cmd.setPostKernelOptions(
        parseKernelOptions(
            form, ctx.getRequest(), form.getString(RequestContext.COBBLER_ID), true));

    if (!cmd.isCobblerOnly()) {
      // now setup system/package profiles for kickstart to sync
      Profile pkgProfile = cmd.getKsdata().getKickstartDefaults().getProfile();
      Long packageProfileId = pkgProfile != null ? pkgProfile.getId() : null;

      // if user did not override package profile, then grab from ks
      // profile if avail
      if (packageProfileId != null) {
        cmd.setProfileId(packageProfileId);
        cmd.setProfileType(KickstartScheduleCommand.TARGET_PROFILE_TYPE_PACKAGE);
      } else {
        /*
         * NOTE: these values are essentially ignored if user did not go
         * through advanced config and there is no package profile to
         * sync in the kickstart profile
         */
        cmd.setProfileType(form.getString(TARGET_PROFILE_TYPE));
        cmd.setServerProfileId((Long) form.get("targetServerProfile"));
        cmd.setProfileId((Long) form.get("targetProfile"));
      }
    }

    storeProxyInfo(form, ctx, cmd);

    // Store the new KickstartSession to the DB.
    ValidatorError ve = cmd.store();
    if (ve != null) {
      ActionErrors errors = RhnValidationHelper.validatorErrorToActionErrors(ve);
      if (!errors.isEmpty()) {
        getStrutsDelegate().saveMessages(ctx.getRequest(), errors);
        return runFirst(mapping, form, ctx, response, step);
      }
    }
    Map params = new HashMap();
    params.put(RequestContext.SID, form.get(RequestContext.SID));

    if (cmd.isCobblerOnly()) {
      createSuccessMessage(
          ctx.getRequest(),
          "kickstart.cobbler.schedule.success",
          LocalizationService.getInstance().formatDate(scheduleTime));
      return getStrutsDelegate().forwardParams(mapping.findForward("cobbler-success"), params);
    }
    createSuccessMessage(
        ctx.getRequest(),
        "kickstart.schedule.success",
        LocalizationService.getInstance().formatDate(scheduleTime));
    return getStrutsDelegate().forwardParams(mapping.findForward("success"), params);
  }