/** {@inheritDoc} */
  protected void render(User user, PageControl pc, HttpServletRequest request) {
    LocalizationService ls = LocalizationService.getInstance();
    DataResult<SystemOverview> isdr = SystemManager.inactiveListSortbyCheckinTime(user, pc);
    String inactiveSystemCSSTable = null;
    if (!isdr.isEmpty()) {
      for (Iterator<SystemOverview> i = isdr.iterator(); i.hasNext(); ) {
        SystemOverview so = i.next();
        StringBuilder buffer = new StringBuilder();
        Long lastCheckin = so.getLastCheckinDaysAgo();
        if (lastCheckin.compareTo(new Long(1)) < 0) {
          buffer.append(lastCheckin * 24);
          buffer.append(' ');

          buffer.append(ls.getMessage("filter-form.jspf.hours"));
        } else if (lastCheckin.compareTo(new Long(7)) < 0) {
          buffer.append(so.getLastCheckinDaysAgo().longValue());
          buffer.append(' ');
          buffer.append(ls.getMessage("filter-form.jspf.days"));
        } else if (lastCheckin.compareTo(new Long(7)) >= 0) {
          buffer.append(lastCheckin.longValue() / 7);
          buffer.append(' ');
          buffer.append(ls.getMessage("filter-form.jspf.weeks"));
        }

        so.setLastCheckinString(buffer.toString());
      }
      request.setAttribute(INACTIVE_SYSTEM_LIST, isdr);
    } else {
      inactiveSystemCSSTable =
          RendererHelper.makeEmptyTable(
              true, "inactivelist.jsp.header", "yourrhn.jsp.noinactivesystems");
      request.setAttribute(INACTIVE_SYSTEMS_EMPTY, inactiveSystemCSSTable);
    }
    RendererHelper.setTableStyle(request, INACTIVE_SYSTEMS_CLASS);
  }
Exemple #2
0
  /**
   * Gets details for a given user. These details include first names, last name, email, prefix,
   * last login date, and created on date.
   *
   * @param loggedInUser The current user
   * @param login The login for the user you want the details for
   * @return Returns a Map containing the details for the given user.
   * @throws FaultException A FaultException is thrown if the user doesn't have access to lookup the
   *     user corresponding to login or if the user does not exist.
   * @xmlrpc.doc Returns the details about a given user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "login", "User's login name.")
   * @xmlrpc.returntype #struct("user details") #prop_desc("string", "first_names", "deprecated, use
   *     first_name") #prop("string", "first_name") #prop("string", "last_name") #prop("string",
   *     "email") #prop("int", "org_id") #prop("string", "org_name") #prop("string", "prefix")
   *     #prop("string", "last_login_date") #prop("string", "created_date") #prop_desc("boolean",
   *     "enabled", "true if user is enabled, false if the user is disabled") #prop_desc("boolean",
   *     "use_pam", "true if user is configured to use PAM authentication") #struct_end()
   */
  public Map getDetails(User loggedInUser, String login) throws FaultException {
    User target = XmlRpcUserHelper.getInstance().lookupTargetUser(loggedInUser, login);
    LocalizationService ls = LocalizationService.getInstance();

    Map ret = new HashMap();
    ret.put("first_names", StringUtils.defaultString(target.getFirstNames()));
    ret.put("first_name", StringUtils.defaultString(target.getFirstNames()));
    ret.put("last_name", StringUtils.defaultString(target.getLastName()));
    ret.put("email", StringUtils.defaultString(target.getEmail()));
    ret.put("prefix", StringUtils.defaultString(target.getPrefix()));

    // Last login date
    String lastLoggedIn =
        target.getLastLoggedIn() == null ? "" : ls.formatDate(target.getLastLoggedIn());
    ret.put("last_login_date", lastLoggedIn);

    // Created date
    String created = target.getCreated() == null ? "" : ls.formatDate(target.getCreated());
    ret.put("created_date", created);
    ret.put("org_id", loggedInUser.getOrg().getId());
    ret.put("org_name", loggedInUser.getOrg().getName());

    if (target.isDisabled()) {
      ret.put("enabled", Boolean.FALSE);
    } else {
      ret.put("enabled", Boolean.TRUE);
    }
    ret.put("use_pam", target.getUsePamAuthentication());

    return ret;
  }
 /** @return returns the localized system count */
 public String getSystemCountString() {
   LocalizationService service = LocalizationService.getInstance();
   Integer count = getSystemCount();
   final Integer one = new Integer(1);
   if (one.equals(count)) {
     return service.getMessage("system.common.onesystem");
   }
   if (count == null) {
     count = new Integer(0);
   }
   return service.getMessage("system.common.numsystems", new Object[] {count});
 }
 /**
  * Util method to return the page size in a accessible way.
  *
  * @param totalSize the total size of page
  * @param descriptionKey the message key for description
  * @return the appropriate pagination message.
  */
 protected String makePaginationMessage(int end, int totalSize, String descriptionKey) {
   LocalizationService ls = LocalizationService.getInstance();
   int start = 0;
   if (totalSize > 0) {
     start = 1;
   }
   if (StringUtils.isBlank(descriptionKey)) {
     return ls.getMessage("message.range", start, end, totalSize);
   }
   return ls.getMessage(
       "message.range.withtypedescription", start, end, totalSize, ls.getMessage(descriptionKey));
 }
Exemple #5
0
  /**
   * set the Locale for this thread
   *
   * @param localeIn Locale for this thread.
   */
  public void setLocale(Locale localeIn) {
    this.locale = localeIn;
    LocalizationService ls = LocalizationService.getInstance();

    if (ls.hasMessage("preferences.jsp.lang." + localeIn.toString())) {
      activeLocaleLabel = ls.getMessage("preferences.jsp.lang." + localeIn.toString(), localeIn);
    } else {
      // default to en_US
      // the localeIn will be default to en_US if the LS doesn't
      // find a supported bundle, so we're safe there.
      activeLocaleLabel = ls.getMessage("preferences.jsp.lang.en_US", localeIn);
    }
  }
Exemple #6
0
  /**
   * Creates a new user
   *
   * @param loggedInUser The current user
   * @param desiredLogin The login for the new user
   * @param desiredPassword The password for the new user
   * @param firstName The first name of the new user
   * @param lastName The last name of the new user
   * @param email The email address for the new user
   * @param usePamAuth Should this user authenticate via PAM?
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the loggedInUser doesn't have permissions
   *     to create new users in thier org.
   * @xmlrpc.doc Create a new user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "desiredLogin", "Desired login name, will fail if already
   *     in use.")
   * @xmlrpc.param #param("string", "desiredPassword")
   * @xmlrpc.param #param("string", "firstName")
   * @xmlrpc.param #param("string", "lastName")
   * @xmlrpc.param #param_desc("string", "email", "User's e-mail address.")
   * @xmlrpc.param #param_desc("int", "usePamAuth", "1 if you wish to use PAM authentication for
   *     this user, 0 otherwise.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int create(
      User loggedInUser,
      String desiredLogin,
      String desiredPassword,
      String firstName,
      String lastName,
      String email,
      Integer usePamAuth)
      throws FaultException {
    // Logged in user must be an org admin and we must be on a sat to do this.
    ensureOrgAdmin(loggedInUser);
    ensurePasswordOrPamAuth(usePamAuth, desiredPassword);

    boolean pamAuth = BooleanUtils.toBoolean(usePamAuth, new Integer(1), new Integer(0));

    if (pamAuth) {
      desiredPassword = getDefaultPasswordForPamAuth();
    }

    CreateUserCommand command = new CreateUserCommand();
    command.setUsePamAuthentication(pamAuth);
    command.setLogin(desiredLogin);
    command.setPassword(desiredPassword);
    command.setFirstNames(firstName);
    command.setLastName(lastName);
    command.setEmail(email);
    command.setOrg(loggedInUser.getOrg());
    command.setCompany(loggedInUser.getCompany());

    // Validate the user to be
    ValidatorError[] errors = command.validate();
    if (errors.length > 0) {
      StringBuilder errorString = new StringBuilder();
      LocalizationService ls = LocalizationService.getInstance();
      // Build a sane error message here
      for (int i = 0; i < errors.length; i++) {
        ValidatorError err = errors[i];
        errorString.append(ls.getMessage(err.getKey(), err.getValues()));
        if (i != errors.length - 1) {
          errorString.append(" :: ");
        }
      }
      // Throw a BadParameterException with our message string
      throw new BadParameterException(errorString.toString());
    }

    command.storeNewUser();
    return 1;
  }
 /** {@inheritDoc} */
 @Override
 public void beforeList() throws JspException {
   // <script src="/javascript/tree.js" type="text/javascript"></script>
   ListTagUtil.write(pageContext, IMPORT_TREE_JS);
   ListTagUtil.write(pageContext, String.format(NEW_VAR_SCRIPT, listName));
   LocalizationService ls = LocalizationService.getInstance();
   ListTagUtil.write(
       pageContext,
       String.format(
           SHOW_ALL_SCRIPT,
           listName,
           ls.getMessage("show.all"),
           listName,
           ls.getMessage("hide.all")));
 }
 /**
  * Creates an empty YourRhn table
  *
  * @param isHalfTable is it a half table?
  * @param tableHeaderKey resource bundle token
  * @param tableMessageKey resource bundle token
  * @return markup for empty table
  */
 public static String makeEmptyTable(
     boolean isHalfTable, String tableHeaderKey, String tableMessageKey) {
   String header = null;
   String footer = null;
   String headerText = LocalizationService.getInstance().getMessage(tableHeaderKey);
   String messageText = LocalizationService.getInstance().getMessage(tableMessageKey);
   if (isHalfTable) {
     header = HALF_TABLE_HEADER;
     footer = HALF_TABLE_FOOTER;
   } else {
     header = FULL_TABLE_HEADER;
     footer = FULL_TABLE_FOOTER;
   }
   return header + headerText + TABLE_BODY + messageText + footer;
 }
 /**
  * Constructor
  *
  * @param attribute the attribute that was missing
  * @param cause the cause (which is saved for later retrieval by the Throwable.getCause() method).
  *     (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
  */
 public MissingErrataAttributeException(String attribute, Throwable cause) {
   super(
       2609,
       "invalidActionType",
       LocalizationService.getInstance().getMessage("api.errata.missingerrataaction", (attribute)),
       cause);
 }
  /**
   * 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"));
          }
        }
      }
    }
  }
 /**
  * Constructor
  *
  * @param tagName name of the tag
  */
 public NoSuchSnapshotTagException(String tagName) {
   super(
       1212,
       "NoSuchSnapshotTag",
       LocalizationService.getInstance()
           .getMessage("api.provisioning.snapshot.nosuchtag", new Object[] {tagName}));
 }
Exemple #12
0
  private void renderEmptyList() throws JspException {
    ListTagUtil.write(pageContext, "<tr class=\"list-row-odd\"><td ");
    ListTagUtil.write(pageContext, "class=\"first-column last-column\" ");
    ListTagUtil.write(pageContext, "colspan=\"");
    ListTagUtil.write(pageContext, String.valueOf(columnCount));
    ListTagUtil.write(pageContext, "\">");

    if (emptyKey != null) {
      LocalizationService ls = LocalizationService.getInstance();
      String msg = ls.getMessage(emptyKey);
      ListTagUtil.write(pageContext, "<div class=\"list-empty-message\">");
      ListTagUtil.write(pageContext, msg);
      ListTagUtil.write(pageContext, "<br /></div>");
    }

    ListTagUtil.write(pageContext, "</td></tr>");
  }
  public void testRender() throws Exception {
    RequiredFieldTag tag = new RequiredFieldTag();
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    TagTestHelper tth = TagTestUtils.setupTagTest(tag, new URL("http://localhost"), request);
    tag.setPageContext(tth.getPageContext());
    String key = "getMessage";
    tag.setKey(key);
    // ok let's test the tag
    tth.assertDoStartTag(Tag.EVAL_BODY_INCLUDE);
    tth.assertDoEndTag(Tag.SKIP_BODY);

    RhnMockJspWriter rout = (RhnMockJspWriter) tth.getPageContext().getOut();
    assertTrue(rout.toString().indexOf("<span class") > -1);
    assertTrue(rout.toString().indexOf("</span>") > -1);
    assertTrue(rout.toString().indexOf("*") > -1);
    assertTrue(rout.toString().indexOf("\"" + RequiredFieldTag.REQUIRED_FIELD_CSS + "\"") > -1);
    LocalizationService ls = LocalizationService.getInstance();
    assertTrue(rout.toString().startsWith(ls.getMessage(key)));
  }
  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);
  }
  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()));
    }
  }
Exemple #16
0
  private void setupManipulator() throws JspException {
    manip.setAlphaColumn(alphaBarColumn);
    manip.filter(filter, pageContext);
    if (!StringUtils.isBlank(ListTagHelper.getFilterValue(pageContext.getRequest(), uniqueName))) {
      LocalizationService ls = LocalizationService.getInstance();

      ListTagUtil.write(pageContext, "<div class=\"site-info\">");

      if (manip.getTotalDataSetSize() != manip.getUnfilteredDataSize()) {
        if (manip.getAllData().size() == 0) {
          ListTagUtil.write(
              pageContext,
              ls.getMessage(
                  "listtag.filteredmessageempty", new Integer(manip.getTotalDataSetSize())));
        } else {
          ListTagUtil.write(
              pageContext,
              ls.getMessage("listtag.filteredmessage", new Integer(manip.getTotalDataSetSize())));
        }

        ListTagUtil.write(pageContext, "<br /><a href=\"");
        List<String> excludeParams = new ArrayList<String>();
        excludeParams.add(ListTagUtil.makeSelectActionName(getUniqueName()));
        excludeParams.add(ListTagUtil.makeFilterByLabel(getUniqueName()));
        excludeParams.add(ListTagUtil.makeFilterValueByLabel(getUniqueName()));
        excludeParams.add(ListTagUtil.makeOldFilterValueByLabel(getUniqueName()));
        excludeParams.add(ListTagUtil.makeFilterSearchChildLabel(getUniqueName()));
        excludeParams.add(ListTagUtil.makeFilterSearchParentLabel(getUniqueName()));
        excludeParams.add(ListTagUtil.makeParentIsAnElementLabel(getUniqueName()));

        ListTagUtil.write(
            pageContext,
            ListTagUtil.makeParamsLink(
                pageContext.getRequest(), name, Collections.EMPTY_MAP, excludeParams));

        ListTagUtil.write(pageContext, "\">" + ls.getMessage("listtag.clearfilter"));
        ListTagUtil.write(
            pageContext,
            ls.getMessage("listtag.seeall", new Integer(manip.getUnfilteredDataSize())));
        ListTagUtil.write(pageContext, "</a>");
      } else {
        ListTagUtil.write(
            pageContext,
            ls.getMessage(
                "listtag.all_items_in_filter",
                ListTagHelper.getFilterValue(pageContext.getRequest(), uniqueName)));
      }

      ListTagUtil.write(pageContext, "</div>");
    }
  }
  private void setup(HttpServletRequest request, DynaActionForm form) {
    if (log.isDebugEnabled()) {
      log.debug("Setting up form with default values.");
    }

    form.set("run_script", "before");
    form.set("username", "root");
    form.set("group", "root");
    form.set("timeout", new Long(600));
    form.set("script", "#!/bin/sh");
    form.set("mode", request.getParameter("mode"));
    getStrutsDelegate()
        .prepopulateDatePicker(request, form, "date", DatePicker.YEAR_RANGE_POSITIVE);
    Date date = getStrutsDelegate().readDatePicker(form, "date", DatePicker.YEAR_RANGE_POSITIVE);

    request.setAttribute("scheduledDate", LocalizationService.getInstance().formatDate(date));
  }
  private void storeActivationKeyInfo() {
    // If the target system exists already, remove any existing activation keys
    // it might have associated with it.

    log.debug("** ActivationType : Existing profile..");
    if (getTargetServer() != null) {
      List oldkeys = ActivationKeyFactory.lookupByServer(getTargetServer());

      if (oldkeys != null) {
        log.debug("** Removing old tokens");
        Iterator i = oldkeys.iterator();
        while (i.hasNext()) {
          log.debug("removing key.");
          ActivationKey oldkey = (ActivationKey) i.next();
          ActivationKeyFactory.removeKey(oldkey);
        }
      }
    }

    String note = null;
    if (getTargetServer() != null) {
      note =
          LocalizationService.getInstance()
              .getMessage("kickstart.session.newtokennote", getTargetServer().getName());
    } else {
      // TODO: translate this
      note = "Automatically generated activation key.";
    }

    RegistrationType regType = getKsdata().getRegistrationType(user);

    if (regType.equals(RegistrationType.REACTIVATION)) {
      // Create a new activation key for the target system.
      boolean reactivation = RegistrationType.REACTIVATION.equals(regType);
      createKickstartActivationKey(
          this.user,
          this.ksdata,
          reactivation ? getTargetServer() : null,
          this.kickstartSession,
          1L,
          note);
    }
    this.createdProfile = processProfileType(this.profileType);
    log.debug("** profile created: " + createdProfile);
  }
Exemple #19
0
  /** ${@inheritDoc} */
  public int doEndTag() throws JspException {

    /* If a reference link was provided, it needs to be rendered on a separate
     * row within the table.
     */
    if ((refLink != null) && (!isEmpty())) {
      ListTagUtil.write(pageContext, "<tr");
      renderRowClassAndId();
      ListTagUtil.write(pageContext, ">");

      ListTagUtil.write(
          pageContext,
          "<td style=\"text-align: center;\" " + "class=\"first-column last-column\" ");

      ListTagUtil.write(pageContext, "colspan=" + String.valueOf(getColumnCount()) + ">");
      ListTagUtil.write(pageContext, "<a href=\"" + refLink + "\" >");

      /* Here we render the reflink and its key. If the key hasn't been set
       * we just display the link address itself.
       */
      if (refLinkKey != null) {
        Object[] args = new Object[2];
        args[0] = new Integer(getPageRowCount());
        args[1] = refLinkKeyArg0;
        String message = LocalizationService.getInstance().getMessage(refLinkKey, args);

        ListTagUtil.write(pageContext, message);
      } else {
        ListTagUtil.write(pageContext, refLink);
      }

      ListTagUtil.write(pageContext, "</a>");
      ListTagUtil.write(pageContext, "</td>");
      ListTagUtil.write(pageContext, "</tr>");
    }

    ListTagUtil.write(pageContext, "</table>");
    renderPaginationControls(true);
    ListTagUtil.write(pageContext, "<!-- END " + getUniqueName() + " -->");
    release();
    return BodyTagSupport.EVAL_PAGE;
  }
  /**
   * Set up the filter combo
   *
   * @param request the request
   * @return the map for the combo
   */
  protected List<Map<String, Object>> getComboList(HttpServletRequest request) {

    String selected = request.getParameter(SELECTOR);

    List<Map<String, Object>> combo = new ArrayList<Map<String, Object>>();

    LocalizationService ls = LocalizationService.getInstance();

    Map<String, Object> tmp = new HashMap<String, Object>();
    tmp.put("name", ALL);
    tmp.put("id", ALL);
    tmp.put("default", ls.getMessage(ALL).equals(selected));

    Map<String, Object> tmp1 = new HashMap<String, Object>();
    tmp1.put("name", NON_CRITICAL);
    tmp1.put("id", NON_CRITICAL);
    tmp1.put("default", ls.getMessage(NON_CRITICAL).equals(selected));

    Map<String, Object> tmp2 = new HashMap<String, Object>();
    tmp2.put("name", BUGFIX);
    tmp2.put("id", BUGFIX);
    tmp2.put("default", ls.getMessage(BUGFIX).equals(selected));

    Map<String, Object> tmp3 = new HashMap<String, Object>();
    tmp3.put("name", ENHANCE);
    tmp3.put("id", ENHANCE);
    tmp3.put("default", ls.getMessage(ENHANCE).equals(selected));

    Map<String, Object> tmp4 = new HashMap<String, Object>();
    tmp4.put("name", SECUR);
    tmp4.put("id", SECUR);
    tmp4.put("default", ls.getMessage(SECUR).equals(selected));

    combo.add(tmp);
    combo.add(tmp1);
    combo.add(tmp2);
    combo.add(tmp3);
    combo.add(tmp4);
    return combo;
  }
  /**
   * convert combo box types to ErrataFactory types
   *
   * @param type the type from the combo box
   * @return a list of types to get
   */
  protected List<String> getTypes(String type) {
    List<String> typeList = new ArrayList<String>();
    LocalizationService ls = LocalizationService.getInstance();

    if (ls.getMessage(BUGFIX).equals(type)) {
      typeList.add(ErrataFactory.ERRATA_TYPE_BUG);
    } else if (ls.getMessage(SECUR).equals(type)) {
      typeList.add(ErrataFactory.ERRATA_TYPE_SECURITY);
    } else if (ls.getMessage(ENHANCE).equals(type)) {
      typeList.add(ErrataFactory.ERRATA_TYPE_ENHANCEMENT);
    } else if (ls.getMessage(NON_CRITICAL).equals(type)) {
      typeList.add(ErrataFactory.ERRATA_TYPE_BUG);
      typeList.add(ErrataFactory.ERRATA_TYPE_ENHANCEMENT);
    } else { // ALL
      typeList.add(ErrataFactory.ERRATA_TYPE_BUG);
      typeList.add(ErrataFactory.ERRATA_TYPE_ENHANCEMENT);
      typeList.add(ErrataFactory.ERRATA_TYPE_SECURITY);
    }
    return typeList;
  }
  /** {@inheritDoc} */
  public List getResult(RequestContext context) {
    User user = context.getCurrentUser();
    Long sid = context.getRequiredParam("sid");
    String type = context.getParam(SELECTOR, false);
    String synopsis = "";
    Boolean currency = false;

    LocalizationService ls = LocalizationService.getInstance();

    String eType = new String();

    if (ls.getMessage(SECUR_CRIT).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "C";
      currency = true;
    } else if (ls.getMessage(SECUR_IMP).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "I";
      currency = true;
    } else if (ls.getMessage(SECUR_MOD).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "M";
      currency = true;
    } else if (ls.getMessage(SECUR_LOW).equals(type)) {
      eType = ErrataFactory.ERRATA_TYPE_SECURITY;
      synopsis = "L";
      currency = true;
    }

    if (currency) {
      return SystemManager.relevantCurrencyErrata(user, sid, eType, synopsis);
    }

    List<String> typeList = getTypes(type);
    return SystemManager.relevantErrata(user, sid, typeList);
  }
  /**
   * 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);
  }
  @Override
  protected void insureFormDefaults(HttpServletRequest request, DynaActionForm form) {
    String search = form.getString(SEARCH_STR).trim();
    String where = form.getString(WHERE_TO_SEARCH);
    String viewMode = form.getString(VIEW_MODE);

    if (where == null || viewMode == null) {
      throw new BadParameterException("An expected form var was null");
    }

    if ("".equals(viewMode)) { // first time viewing page
      viewMode = "systemsearch_name_and_description";
      form.set(VIEW_MODE, viewMode);
      request.setAttribute(VIEW_MODE, viewMode);
    }

    if ("".equals(where) || !VALID_WHERE_STRINGS.contains(where)) {
      form.set(WHERE_TO_SEARCH, "all");
      request.setAttribute(WHERE_TO_SEARCH, "all");
    }

    Boolean fineGrained = (Boolean) form.get(FINE_GRAINED);
    request.setAttribute(FINE_GRAINED, fineGrained == null ? false : fineGrained);

    Boolean invert = (Boolean) form.get(INVERT_RESULTS);
    if (invert == null) {
      invert = Boolean.FALSE;
      form.set(INVERT_RESULTS, invert);
    }

    if (invert) {
      request.setAttribute(INVERT_RESULTS, "on");
    } else {
      request.setAttribute(INVERT_RESULTS, "off");
    }

    /* Here we set up a hashmap using the string resources key for the various options
     * group as a key into the hash, and the string resources/database mode keys as
     * the values of the options that are contained within each opt group. The jsp
     * uses this hashmap to setup a dropdown box
     */
    boolean matchingViewModeFound = false;
    Map<String, List<Map<String, String>>> optGroupsMap =
        new HashMap<String, List<Map<String, String>>>();
    LocalizationService ls = LocalizationService.getInstance();
    for (int j = 0; j < OPT_GROUPS_TITLES.length; ++j) {
      List<Map<String, String>> options = new ArrayList<Map<String, String>>();

      for (int k = 0; k < OPT_GROUPS[j].length; ++k) {
        options.add(
            createDisplayMap(
                LocalizationService.getInstance().getMessage(OPT_GROUPS[j][k]), OPT_GROUPS[j][k]));
        if (OPT_GROUPS[j][k].equals(viewMode)) {
          matchingViewModeFound = true;
        }
      }
      optGroupsMap.put(OPT_GROUPS_TITLES[j], options);
    }
    if (viewMode != null && !matchingViewModeFound) {
      throw new BadParameterException("Bad viewMode passed in from form");
    }
    request.setAttribute(OPT_GROUPS_MAP, optGroupsMap);
    request.setAttribute(OPT_GROUPS_KEYS, optGroupsMap.keySet());
    request.setAttribute(SEARCH_STR, search);
    request.setAttribute(VIEW_MODE, viewMode);
    request.setAttribute(WHERE_TO_SEARCH, where);
  }
 /** @return a Localized and user-friendly display for the config channel type. */
 public String getTypeDisplay() {
   return LocalizationService.getInstance().getMessage("config_channel." + getType());
 }
  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;
  }
  /**
   * 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());
    }
  }
  /**
   * Executes the appropriate PackageAction
   *
   * @param mapping ActionMapping
   * @param formIn ActionForm
   * @param request ServletRequest
   * @param response ServletResponse
   * @return The ActionForward to go to next.
   */
  public ActionForward executePackageAction(
      ActionMapping mapping,
      ActionForm formIn,
      HttpServletRequest request,
      HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    Long sid = requestContext.getRequiredParam("sid");
    User user = requestContext.getCurrentUser();
    // updateList(newactions, user.getId());

    List<Map<String, Long>> data = PackageListItem.toKeyMaps(getDataResult(request));
    int numPackages = data.size();

    // Archive the actions
    Server server = SystemManager.lookupByIdAndUser(sid, user);

    // The earliest time to perform the action.
    DynaActionForm dynaActionForm = (DynaActionForm) formIn;
    Date earliest =
        getStrutsDelegate().readDatePicker(dynaActionForm, "date", DatePicker.YEAR_RANGE_POSITIVE);

    // The action chain to append this action to, if any
    ActionChain actionChain = ActionChainHelper.readActionChain(dynaActionForm, user);

    PackageAction pa = schedulePackageAction(formIn, requestContext, data, earliest, actionChain);

    // Remove the actions from the users set
    SessionSetHelper.obliterate(request, getDecl(sid));

    ActionMessages msgs = new ActionMessages();

    if (actionChain == null) {
      /**
       * If there was only one action archived, display the "action" archived message, else display
       * the "actions" archived message.
       */
      if (numPackages == 1) {
        msgs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage(
                getMessageKeyForOne(),
                LocalizationService.getInstance().formatNumber(numPackages),
                pa.getId().toString(),
                sid.toString(),
                StringUtil.htmlifyText(server.getName())));
      } else {
        msgs.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage(
                getMessageKeyForMany(),
                LocalizationService.getInstance().formatNumber(numPackages),
                pa.getId().toString(),
                sid.toString(),
                StringUtil.htmlifyText(server.getName())));
      }
    } else {
      msgs.add(
          ActionMessages.GLOBAL_MESSAGE,
          new ActionMessage(
              "message.addedtoactionchain",
              actionChain.getId(),
              StringUtil.htmlifyText(actionChain.getLabel())));
    }

    strutsDelegate.saveMessages(request, msgs);
    Map params = new HashMap();
    processParamMap(formIn, request, params);
    return strutsDelegate.forwardParams(mapping.findForward(RhnHelper.CONFIRM_FORWARD), params);
  }
  private void setupForm(HttpServletRequest request, DynaActionForm form) {
    RequestContext ctx = new RequestContext(request);
    prepDropdowns(ctx);
    Long cid = ctx.getParamAsLong("cid");

    if (cid != null) {
      Channel c = ChannelManager.lookupByIdAndUser(cid, ctx.getCurrentUser());
      if (!UserManager.verifyChannelAdmin(ctx.getCurrentUser(), c)) {
        throw new PermissionException(RoleFactory.CHANNEL_ADMIN);
      }

      form.set("name", c.getName());
      form.set("summary", c.getSummary());
      form.set("description", c.getDescription());
      form.set("org_sharing", c.getAccess());
      form.set("gpg_key_url", c.getGPGKeyUrl());
      form.set("gpg_key_id", c.getGPGKeyId());
      form.set("gpg_key_fingerprint", c.getGPGKeyFp());
      form.set("maintainer_name", c.getMaintainerName());
      form.set("maintainer_phone", c.getMaintainerPhone());
      form.set("maintainer_email", c.getMaintainerEmail());
      form.set("support_policy", c.getSupportPolicy());
      if (c.getChecksumTypeLabel() == null) {
        form.set("checksum", null);
      } else {
        form.set("checksum", c.getChecksumTypeLabel());
      }
      if (c.isGloballySubscribable(ctx.getCurrentUser().getOrg())) {
        form.set("per_user_subscriptions", "all");
      } else {
        form.set("per_user_subscriptions", "selected");
      }

      if (c.getParentChannel() != null) {
        request.setAttribute("parent_name", c.getParentChannel().getName());
        request.setAttribute("parent_id", c.getParentChannel().getId());
      } else {
        request.setAttribute(
            "parent_name", LocalizationService.getInstance().getMessage("generic.jsp.none"));
      }

      if (c.getSources().isEmpty()) {
        request.setAttribute("last_sync", "");
      } else {
        String lastSync =
            LocalizationService.getInstance().getMessage("channel.edit.repo.neversynced");
        if (c.getLastSynced() != null) {
          lastSync = LocalizationService.getInstance().formatCustomDate(c.getLastSynced());
        }
        request.setAttribute("last_sync", lastSync);
        if (!ChannelManager.getLatestSyncLogFiles(c).isEmpty()) {
          request.setAttribute(
              "log_url", DownloadManager.getChannelSyncLogDownloadPath(c, ctx.getCurrentUser()));
        }
      }

      request.setAttribute("channel_label", c.getLabel());
      request.setAttribute("channel_name", c.getName());
      request.setAttribute("channel_arch", c.getChannelArch().getName());
      request.setAttribute("channel_arch_label", c.getChannelArch().getLabel());

    } else {
      // default settings
      String channelName =
          LocalizationService.getInstance().getMessage("frontend.actions.channels.manager.create");
      request.setAttribute("channel_name", channelName);
      form.set("org_sharing", "private");
      form.set("per_user_subscriptions", "all");
      form.set("checksum", "sha1");
    }
  }
 /**
  * Constructor
  *
  * @param error error code
  * @param lbl error label
  * @param messageId the string resource message ID
  * @param args arguments to be passed to the localization service
  */
 public FaultException(int error, String lbl, String messageId, Object[] args) {
   super(LocalizationService.getInstance().getMessage(messageId, args));
   this.errorCode = error;
   this.label = lbl;
   this.arguments = args;
 }