Java Code Examples for org.apache.struts.action.DynaActionForm#getString()

The following examples show how to use org.apache.struts.action.DynaActionForm#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RhnWizardAction.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    synchronized (this) {
        if (this.steps.size() == 0) {
            generateWizardSteps(steps);
        }
    }
    RequestContext ctx = new RequestContext(request);
    DynaActionForm dynaForm = (DynaActionForm) form;
    String step = dynaForm.getString(STEP_PARAM);
    ActionForward retval = null;

    if (step != null) {
        log.debug("Step selected: " + step);
        retval = dispatch(step, mapping, form, ctx, response);
    }
    return retval;
}
 
Example 2
Source File: OrgDetailsAction.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 * @param mapping action mapping
 * @param dynaForm form for org details
 * @param request coming in
 * @param response going out
 * @param oid ID of Org we're operating on
 * @param org Org object for oid
 * @throws Exception to parent
 */
private void updateOrgDetails(ActionMapping mapping,
        DynaActionForm dynaForm,
        HttpServletRequest request,
        HttpServletResponse response,
        Long oid,
        Org org) throws Exception {

    RequestContext requestContext = new RequestContext(request);
    if (validateForm(request, dynaForm, oid, org)) {
        String name = dynaForm.getString("orgName");
        OrgManager.renameOrg(org, name);
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("message.org_name_updated",
                StringEscapeUtils.escapeHtml4(name)));
        getStrutsDelegate().saveMessages(request, msg);
    }
}
 
Example 3
Source File: BaseTreeAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected ValidatorError processCommandSetters(PersistOperation operation,
                                                        DynaActionForm form,
                                                        HttpServletRequest request) {
    BaseTreeEditOperation bte = (BaseTreeEditOperation) operation;

    String label = form.getString(LABEL);
    if (!label.equals(bte.getTree().getLabel())) {
        KickstartableTree tree = KickstartFactory.lookupKickstartTreeByLabel(
                label, bte.getUser().getOrg());
        if (tree != null) {
            return new ValidatorError("distribution.tree.exists", tree.getLabel());
        }
    }


    bte.setBasePath(form.getString(BASE_PATH));
    Long channelId = (Long) form.get(CHANNEL_ID);
    Channel c = ChannelFactory.lookupByIdAndUser(channelId, operation.getUser());
    bte.setChannel(c);
    bte.setLabel(form.getString(LABEL));
    KickstartInstallType type = KickstartFactory.
        lookupKickstartInstallTypeByLabel(form.getString(INSTALL_TYPE));
    bte.setInstallType(type);

    bte.setServerName(request.getLocalName());
    bte.setKernelOptions(form.getString(KERNEL_OPTS));
    bte.setKernelOptionsPost(form.getString(POST_KERNEL_OPTS));

    return null;

}
 
Example 4
Source File: AdvancedModeDetailsAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void validateInput(DynaActionForm form,
        RequestContext context) {
    String label = form.getString(KICKSTART_LABEL_PARAM);
    KickstartBuilder builder = new KickstartBuilder(context.getCurrentUser());
    if (isCreateMode(context.getRequest())) {
        builder.validateNewLabel(label);
    }
    else {
        KickstartRawData data = getKsData(context);
        if (!data.getLabel().equals(label)) {
            builder.validateNewLabel(label);
        }
    }
    ValidatorResult result = RhnValidationHelper.validate(this.getClass(),
            makeValidationMap(form), null,
            VALIDATION_XSD);
    if (!result.isEmpty()) {
        throw new ValidatorException(result);
    }

    FormFile file = (FormFile) form.get(FILE_UPLOAD);
    String contents = form.getString(CONTENTS);
    if (!file.getFileName().equals("") && !contents.equals("")) {
        ValidatorException.raiseException("kickstart.details.duplicatefile");
    }

    KickstartableTree tree =  KickstartFactory.lookupKickstartTreeByIdAndOrg(
            (Long) form.get(KSTREE_ID_PARAM),
            context.getCurrentUser().getOrg());
    KickstartVirtualizationType vType =
            KickstartFactory.lookupKickstartVirtualizationTypeByLabel(
                    form.getString(VIRTUALIZATION_TYPE_LABEL_PARAM));

    Distro distro = CobblerProfileCommand.getCobblerDistroForVirtType(tree, vType,
            context.getCurrentUser());
    if (distro == null) {
        ValidatorException.raiseException("kickstart.cobbler.profile.invalidvirt");
    }
}
 
Example 5
Source File: DocSearchSetupAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected ActionForward doExecute(HttpServletRequest request, ActionMapping mapping,
                DynaActionForm form)
    throws MalformedURLException, XmlRpcFault {

    RequestContext ctx = new RequestContext(request);
    String searchString = form.getString(SEARCH_STR);
    String viewmode = form.getString(VIEW_MODE);

    List<Map<String, String>> searchOptions = new ArrayList<Map<String, String>>();
    addOption(searchOptions, "docsearch.content_title", OPT_CONTENT_TITLE);
    addOption(searchOptions, "docsearch.free_form", OPT_FREE_FORM);
    addOption(searchOptions, "docsearch.content", OPT_CONTENT_ONLY);
    addOption(searchOptions, "docsearch.title", OPT_TITLE_ONLY);

    request.setAttribute(SEARCH_STR, searchString);
    request.setAttribute(VIEW_MODE, viewmode);
    request.setAttribute(SEARCH_OPT, searchOptions);


    if (!StringUtils.isBlank(searchString)) {
        List results = performSearch(ctx.getWebSession().getId(),
                                     searchString,
                                     viewmode, request);
        log.debug("GET search: " + results);
        request.setAttribute(RequestContext.PAGE_LIST,
                results != null ? results : Collections.emptyList());
    }
    else {
        request.setAttribute(RequestContext.PAGE_LIST, Collections.emptyList());
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 6
Source File: EditGroupAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private void validate(DynaActionForm form, ActionErrors errors,
        RequestContext ctx) {

    String name = form.getString("name");
    String desc = form.getString("description");
    Long sgid = ctx.getParamAsLong("sgid");

    // Check if both values are entered
    if (StringUtils.isEmpty(name) || StringUtils.isEmpty(desc)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("systemgroup.create.requirements"));
    }

    // Check if sg already exists
    ManagedServerGroup newGroup = ServerGroupFactory.lookupByNameAndOrg(name,
            ctx.getCurrentUser().getOrg());

    // Ugly condition for two error cases:
    //     creating page + group name exists
    //     editing page + group name exists except our group
    if (((sgid == null) && (newGroup != null)) ||
            (sgid != null) && (newGroup != null) && (!sgid.equals(newGroup.getId()))) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("systemgroup.create.alreadyexists"));
    }

}
 
Example 7
Source File: XccdfSearchAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private String getRuleResultLabel(DynaActionForm form) {
    String resultFilter = form.getString("result_filter");
    if (resultFilter == null ||
            ANY_LABEL.equals(resultFilter) || "".equals(resultFilter)) {
        return null;
    }
    return resultFilter;
}
 
Example 8
Source File: XccdfSearchAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected ActionForward doExecute(HttpServletRequest request, ActionMapping mapping,
                DynaActionForm form)
        throws MalformedURLException, XmlRpcException, XmlRpcFault {
    RequestContext context = new RequestContext(request);
    String searchString = form.getString(SEARCH_STR);
    String whereToSearch = form.getString(WHERE_TO_SEARCH);

    DateRangePicker picker = setupDatePicker(form, request);

    if (!StringUtils.isBlank(searchString)) {
        picker.processDatePickers(getOptionScanDateSearch(request), false);
        DataResult results = XccdfSearchHelper.performSearch(searchString,
            whereToSearch, getPickerDate(request, "start"),
            getPickerDate(request, "end"), getRuleResultLabel(form),
            isTestestResultRequested(form), context);
        request.setAttribute(RequestContext.PAGE_LIST,
                results != null ? results : Collections.EMPTY_LIST);
        if (isTestestResultRequested(form) && results != null) {
            TagHelper.bindElaboratorTo("searchResultsTr", results.getElaborator(),
                    request);
        }
    }
    else {
        request.setAttribute(RequestContext.PAGE_LIST, Collections.EMPTY_LIST);
        picker.processDatePickers(false, false);
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 9
Source File: PackageSearchAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
protected ActionForward doExecute(HttpServletRequest request, ActionMapping mapping,
                DynaActionForm form)
    throws MalformedURLException, XmlRpcFault, SearchServerIndexException {

    RequestContext ctx = new RequestContext(request);
    String searchString = form.getString(SEARCH_STR);
    String viewmode = form.getString(VIEW_MODE);
    Boolean fineGrained = (Boolean) form.get(FINE_GRAINED);
    String searchCriteria = form.getString(WHERE_CRITERIA);
    String[] selectedArches = null;
    Long filterChannelId = null;
    boolean relevantFlag = false;

    // Default to relevant channels if no search criteria was specified
    if (searchCriteria == null || searchCriteria.equals("")) {
        searchCriteria = RELEVANT;
    }

    // Handle the radio button selection for channel filtering
    if (searchCriteria.equals(RELEVANT)) {
        relevantFlag = true;
    }
    else if (searchCriteria.equals(ARCHITECTURE)) {
        /* The search call will function as being scoped to architectures if the arch
           list isn't null. In order to actually get radio-button-like functionality
           we can't rely on the arch list coming in from the form to be null; the
           user may have selected an arch but *not* the radio button for arch. If we
           push off retrieving the arches until we know we want to use them, we can
           get the desired functionality described by the UI.
          */
        selectedArches = form.getStrings(CHANNEL_ARCH);
    }
    else if (searchCriteria.equals(CHANNEL)) {
        String sChannelId = form.getString(CHANNEL_FILTER);
        filterChannelId = Long.parseLong(sChannelId);
    }

    List<Map<String, String>> searchOptions = buildSearchOptions();
    List<Map<String, String>> channelArches = buildChannelArches();

    // Load list of available channels to select as filter
    List<Map<String, Object>> allChannels =
            ChannelManager.allChannelsTree(ctx.getCurrentUser());

    request.setAttribute(SEARCH_STR, searchString);
    request.setAttribute(VIEW_MODE, viewmode);
    request.setAttribute(SEARCH_OPT, searchOptions);
    request.setAttribute(CHANNEL_ARCHES, channelArches);
    request.setAttribute(CHANNEL_ARCH, selectedArches);
    request.setAttribute(ALL_CHANNELS, allChannels);
    request.setAttribute(CHANNEL_FILTER,
                    form.getString(CHANNEL_FILTER));
    request.setAttribute(RELEVANT, relevantFlag ? "yes" : "no");
    request.setAttribute(FINE_GRAINED, fineGrained);

    // Default where to search criteria
    request.setAttribute(WHERE_CRITERIA, searchCriteria);

    if (!StringUtils.isBlank(searchString)) {
        List<PackageOverview> results =
                performSearch(ctx, searchString, viewmode, fineGrained, selectedArches,
                        filterChannelId, relevantFlag, searchCriteria);

        request.setAttribute(RequestContext.PAGE_LIST,
                results != null ? results : Collections.emptyList());
    }
    else {
        request.setAttribute(RequestContext.PAGE_LIST, Collections.emptyList());
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 10
Source File: KickstartDetailsEditAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected ValidatorError processFormValues(HttpServletRequest request,
        DynaActionForm form,
        BaseKickstartCommand cmdIn) {

    ValidatorError error = null;
    KickstartEditCommand cmd = (KickstartEditCommand) cmdIn;
    RequestContext ctx = new RequestContext(request);
    KickstartBuilder builder = new KickstartBuilder(ctx.getCurrentUser());
    cmd.setComments(form.getString(COMMENTS));
    try {


        KickstartVirtualizationType vType =
            KickstartFactory.lookupKickstartVirtualizationTypeByLabel(
                form.getString(VIRTUALIZATION_TYPE_LABEL));

        Distro distro = CobblerProfileCommand.getCobblerDistroForVirtType(
                cmdIn.getKickstartData().getTree(), vType, ctx.getCurrentUser());
        if (distro == null) {
            ValidatorException.raiseException("kickstart.cobbler.profile.invalidvirt");
        }


        if (!cmdIn.getKickstartData().getLabel().equals(form.getString(LABEL))) {
            builder.validateNewLabel(form.getString(LABEL));
        }


        cmd.setLabel(form.getString(LABEL));
        cmd.setActive(Boolean.valueOf(
                BooleanUtils.toBoolean((Boolean) form.get(ACTIVE))));
        cmd.setIsOrgDefault(Boolean.valueOf(
                BooleanUtils.toBoolean((Boolean) form.get(ORG_DEFAULT))));
        cmd.getKickstartData().setPostLog(
                BooleanUtils.toBoolean((Boolean) form.get(POST_LOG)));
        cmd.getKickstartData().setPreLog(
                BooleanUtils.toBoolean((Boolean) form.get(PRE_LOG)));
        cmd.getKickstartData().setKsCfg(
                BooleanUtils.toBoolean((Boolean) form.get(KS_CFG)));

        processCobblerFormValues(cmd.getKickstartData(), form, ctx.getCurrentUser());

        String virtTypeLabel = form.getString(VIRTUALIZATION_TYPE_LABEL);
        KickstartVirtualizationType ksVirtType = KickstartFactory.
            lookupKickstartVirtualizationTypeByLabel(virtTypeLabel);
        if (ksVirtType == null) {
            throw new InvalidVirtualizationTypeException(virtTypeLabel);
        }
        cmd.setVirtualizationType(ksVirtType);



        return null;
    }
    catch (ValidatorException ve) {
        return ve.getResult().getErrors().get(0);
    }
}
 
Example 11
Source File: UserPrefAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
                             ActionForm formIn,
                             HttpServletRequest request,
                             HttpServletResponse response) {

    DynaActionForm form = (DynaActionForm)formIn;
    RequestContext requestContext = new RequestContext(request);
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    User user = UserManager.lookupUser(requestContext.getCurrentUser(),
            requestContext.getParamAsLong("uid"));
    request.setAttribute(RhnHelper.TARGET_USER, user);
    if (user == null) {
        user = requestContext.getCurrentUser();
    }

    String preferredLocale = form.getString("preferredLocale");
    if (preferredLocale != null && preferredLocale.equals("none")) {
        preferredLocale = null;
    }
    user.setTimeZone(UserManager.getTimeZone(((Integer) form.get("timezone")).intValue()));
    user.setPreferredLocale(preferredLocale);

    user.setEmailNotify(BooleanUtils.toInteger((Boolean) form
            .get("emailNotif"), 1, 0, 0));
    user.setTaskoNotify(BooleanUtils.toBoolean((Boolean) form.get("taskoNotify")));
    user.setPageSize(getAsInt(form, "pagesize", 5));
    user.setCsvSeparator((Character) form.get("csvSeparator"));

    handlePanes(form, user);

    UserManager.storeUser(user);

    ActionMessages msgs = new ActionMessages();
    msgs.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.preferencesModified"));
    strutsDelegate.saveMessages(request, msgs);

    return strutsDelegate.forwardParam(mapping.findForward("success"), "uid",
                                  String.valueOf(user.getId()));
}
 
Example 12
Source File: CreateAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ActionForward execute(ActionMapping mapping,
                             ActionForm formIn,
                             HttpServletRequest request,
                             HttpServletResponse response) {
    DynaActionForm form = (DynaActionForm) formIn;

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

    //Validate the form to make sure everything was filled out correctly
    ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, form);

    User user = requestContext.getCurrentUser();
    String advisoryNameFromForm = form.getString("advisoryName");
    //Make sure advisoryName is unique
    if (!ErrataManager.advisoryNameIsUnique(null, advisoryNameFromForm,
            user.getOrg())) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                   new ActionMessage("errata.edit.error.uniqueAdvisoryName"));
    }
    // Make sure advisoryName does not begin with RH
    if (advisoryNameFromForm.toUpperCase().startsWith("RH")) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                   new ActionMessage("errata.edit.error.rhAdvisoryName"));
    }
    if (!errors.isEmpty()) { // We've got errors. Forward to failure mapping.
        addErrors(request, errors);
        return mapping.findForward("failure");
    }

    //Create a new unpublished errata
    Errata e = ErrataManager.createNewErrata();
    e.setSynopsis(form.getString("synopsis"));
    e.setAdvisoryName(form.getString("advisoryName"));
    e.setAdvisoryRel(new Long(form.getString("advisoryRelease")));
    e.setAdvisoryType(form.getString("advisoryType"));
    e.setProduct(form.getString("product"));
    e.setErrataFrom(form.getString("errataFrom"));

    //Advisory = advisoryName-advisoryRelease
    e.setAdvisory(form.getString("advisoryName") + "-" +
                  form.getString("advisoryRelease"));

    //create a bug and add it to the set
    Bug bug = createBug(form);
    if (bug != null) {
        e.addBug(bug);
    }
    e.setTopic(form.getString("topic"));
    e.setDescription(form.getString("description"));
    e.setSolution(form.getString("solution"));
    if (ErrataFactory.ERRATA_TYPE_SECURITY.equals(e.getAdvisoryType())) {
        e.setSeverity(Severity.getById((Integer)form.get("advisorySeverity")));
    }


    //add keywords... split on commas and add separately to list
    String keywordsField = form.getString("keywords");
    if (keywordsField != null) {
        List keywords = Arrays.asList(keywordsField.split(","));
        Iterator keywordItr = keywords.iterator();
        while (keywordItr.hasNext()) {
            String keyword = (String) keywordItr.next();
            keyword = keyword.trim();
            if (keyword != null && keyword.length() > 0) {
                e.addKeyword(keyword);
            }
        }
    }
    e.setRefersTo(form.getString("refersTo"));
    e.setNotes(form.getString("notes"));

    //Set issueDate to now
    Date date = new Date(System.currentTimeMillis());
    e.setIssueDate(date);
    e.setUpdateDate(date);

    //Set the org for the errata to the logged in user's org
    e.setOrg(user.getOrg());

    ErrataManager.storeErrata(e);

    ActionMessages msgs = new ActionMessages();
    msgs.add(ActionMessages.GLOBAL_MESSAGE,
             new ActionMessage("errata.created",
                               e.getAdvisoryName(),
                               e.getAdvisoryRel().toString()));
    saveMessages(request, msgs);
    return strutsDelegate.forwardParam(mapping.findForward("success"),
                                  "eid",
                                  e.getId().toString());
}
 
Example 13
Source File: SystemSearchAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
@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);
}
 
Example 14
Source File: XccdfSearchAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
private boolean isTestestResultRequested(DynaActionForm form) {
    String showAs = form.getString(SHOW_AS);
    return showAs != null && !RULERESULT_ID.equals(showAs) && !"".equals(showAs);
}
 
Example 15
Source File: KickstartSoftwareEditAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ValidatorError processFormValues(HttpServletRequest request,
        DynaActionForm form,
        BaseKickstartCommand cmdIn) {

    KickstartData ksdata = cmdIn.getKickstartData();
    boolean wasRhel5OrLess = ksdata.isRHEL5OrLess();
    RequestContext ctx = new RequestContext(request);
    KickstartTreeUpdateType updateType = null;
    KickstartableTree tree = null;
    Long channelId = (Long) form.get(CHANNEL);
    String url = form.getString(URL);
    Org org = ctx.getCurrentUser().getOrg();

    if (form.get(USE_NEWEST_KSTREE_PARAM) != null) {
        updateType = KickstartTreeUpdateType.ALL;
        tree = KickstartFactory.getNewestTree(updateType, channelId, org);
    }
    else if (form.get(USE_NEWEST_RH_KSTREE_PARAM) != null) {
        updateType = KickstartTreeUpdateType.RED_HAT;
        tree = KickstartFactory.getNewestTree(updateType, channelId, org);
    }
    else {
        updateType = KickstartTreeUpdateType.NONE;
        tree = KickstartFactory.lookupKickstartTreeByIdAndOrg(
                (Long) form.get(TREE), org);
    }

    if (tree == null) {
        return new ValidatorError("kickstart.softwaredit.tree.required");
    }

    Distro distro = CobblerProfileCommand.getCobblerDistroForVirtType(tree,
            ksdata.getKickstartDefaults().getVirtualizationType(),
            ctx.getCurrentUser());
    if (distro == null) {
        return new ValidatorError("kickstart.cobbler.profile.invalidtreeforvirt");
    }

    KickstartEditCommand cmd = (KickstartEditCommand) cmdIn;
    ValidatorError ve = cmd.updateKickstartableTree(channelId, org.getId(),
            tree.getId(), url);

    if (ve == null) {
        String [] repos = form.getStrings(SELECTED_REPOS);
        cmd.updateRepos(repos);
    }

    ksdata.setRealUpdateType(updateType);

    // need to reset auth field
    if (wasRhel5OrLess != cmd.getKickstartData().isRHEL5OrLess()) {
        KickstartCommand auth = cmd.getKickstartData().getCommand("auth");
        if (auth != null) {
            auth.setArguments(cmd.getKickstartData().defaultAuthArgs());
        }
    }

    CobblerProfileEditCommand cpec = new CobblerProfileEditCommand(ksdata,
            ctx.getCurrentUser());
    cpec.store();

    // Process the selected child channels
    String[] childchannelIds = request.getParameterValues(CHILD_CHANNELS);
    cmd.updateChildChannels(childchannelIds);

    if (ve != null) {
        return ve;
    }
    return null;
}
 
Example 16
Source File: ActivationKeyDetailsAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
private ActivationKey update(DynaActionForm form, RequestContext context) {
    User user = context.getCurrentUser();
    ActivationKeyManager manager = ActivationKeyManager.getInstance();
    ActivationKey key = context.lookupAndBindActivationKey();

    String[] selected = (String[])form.get(SELECTED_ENTS);
    List<String> selectedList = Arrays.asList(selected);
    if (selected != null) {
        manager.removeEntitlements(key, entitlementsToRemove(user.getOrg(),
            selectedList));
        manager.addEntitlements(key, selectedList);
    }

    if (StringUtils.isBlank(form.getString(DESCRIPTION))) {
        key.setNote(ActivationKeyFactory.DEFAULT_DESCRIPTION);
    }
    else {
        key.setNote(form.getString(DESCRIPTION));
    }

    key.setBaseChannel(lookupChannel(form, user));
    updateChildChannels(form, key);

    key.getToken().setOrgDefault(Boolean.TRUE.equals(form.get(ORG_DEFAULT)));

    Long usageLimit = null;
    if (!StringUtils.isBlank(form.getString(USAGE_LIMIT))) {
        usageLimit = Long.valueOf(form.getString(USAGE_LIMIT));
    }

    key.setDeployConfigs(Boolean.TRUE.equals(form.get(AUTO_DEPLOY)));

    key.setUsageLimit(usageLimit);

    // Set the contact method
    long contactId = (Long) form.get(CONTACT_METHOD);
    if (contactId != key.getContactMethod().getId()) {
        key.setContactMethod(ServerFactory.findContactMethodById(contactId));
    }

    ActivationKeyFactory.save(key);
    ActionMessages msg = new ActionMessages();
    addToMessage(msg, "activation-key.java.modified", key.getNote());

    String newKey = form.getString(KEY);
    if (StringUtils.isBlank(newKey)) {
        newKey = ActivationKeyFactory.generateKey();
    }
    newKey = ActivationKey.sanitize(key.getOrg(), newKey);
    String enteredKey = form.getString(KEY);
    if (!enteredKey.equals(key.getKey()) && !newKey.equals(key.getKey())) {
        manager.changeKey(newKey, key, user);
        if (!StringUtils.isBlank(enteredKey) &&
                    !enteredKey.equals(key.getKey())) {
            addToMessage(msg, "activation-key.java.org_prefixed",
                                                    key, newKey);
        }

    }
    getStrutsDelegate().saveMessages(context.getRequest(), msg);
    return key;
}
 
Example 17
Source File: CreateUserAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
                             ActionForm formIn,
                             HttpServletRequest request,
                             HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);

    DynaActionForm form = (DynaActionForm)formIn;

    /*
     * If the usepam checkbox has been checked, the password fields aren't required.
     * Since password is required in the db and since in all other cases it is required,
     * we'll trick the validation by doing all of the manipulation before validating
     * the form.
     *
     * Also, if the user for some reason does want to set a default password to stick
     * in the db (even though it won't be used), we'll just validate it like a regular
     * password and allow it.
     */
    if (form.get("usepam") != null && ((Boolean) form.get("usepam")).booleanValue()) {
        String hash = MD5Crypt.crypt("" + System.currentTimeMillis());
        if (form.get(UserActionHelper.DESIRED_PASS) == null ||
                form.get(UserActionHelper.DESIRED_PASS).equals("")) {
            form.set(UserActionHelper.DESIRED_PASS, hash);
        }
        if (form.get(UserActionHelper.DESIRED_PASS_CONFIRM) == null ||
                form.get(UserActionHelper.DESIRED_PASS_CONFIRM).equals("")) {
            form.set(UserActionHelper.DESIRED_PASS_CONFIRM, hash);
        }
    }

    // Validate the form
    ActionErrors verrors = RhnValidationHelper.validateDynaActionForm(this, form);
    if (!verrors.isEmpty()) {
        RhnValidationHelper.setFailedValidation(request);
        return returnError(mapping, request, verrors);
    }

    // Create the user and do some more validation
    CreateUserCommand command = getCommand();
    ActionErrors errors = populateCommand(form, command);
    if (!errors.isEmpty()) {
        return returnError(mapping, request, errors);
    }

    ActionMessages msgs = new ActionMessages();

    User user = createIntoOrg(requestContext, command,
            (String) form.get(UserActionHelper.DESIRED_PASS),
            msgs);
    User orgAdmin = requestContext.getCurrentUser();
    saveMessages(request, msgs);
    command.publishNewUserEvent(orgAdmin, orgAdmin.getOrg().getActiveOrgAdmins(),
            request.getServerName(),
            (String) form.get(UserActionHelper.DESIRED_PASS));

    user.setTimeZone(UserManager.getTimeZone(((Integer) form.get("timezone"))
        .intValue()));
    String preferredLocale = form.getString("preferredLocale");
    if (preferredLocale != null && preferredLocale.equals("none")) {
        preferredLocale = null;
    }
    user.setPreferredLocale(preferredLocale);
    user.setReadOnly(form.get("readonly") != null);
    UserManager.storeUser(user);

    return getStrutsDelegate().forwardParam(mapping.findForward(SUCCESS_INTO_ORG),
            "uid", String.valueOf(user.getId()));
}
 
Example 18
Source File: SearchWrittenEvaluationsByDate.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private LocalDate getDate(final DynaActionForm dynaActionForm) throws ParseException {
    final String yearString = dynaActionForm.getString("year");
    final String monthString = dynaActionForm.getString("month");
    final String dayString = dynaActionForm.getString("day");
    return new LocalDate(Integer.parseInt(yearString), Integer.parseInt(monthString), Integer.parseInt(dayString));
}
 
Example 19
Source File: WeeklyWorkLoadDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String getExecutionPeriodID(final DynaActionForm dynaActionForm) {
    final String exeutionPeriodIDString = dynaActionForm.getString("executionPeriodID");
    return exeutionPeriodIDString == null || exeutionPeriodIDString.length() == 0 ? null : exeutionPeriodIDString;
}
 
Example 20
Source File: PowerManagementAction.java    From spacewalk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a CobblerPowerSettingsUpdateCommand from form data.
 * Empty form data means - clear the value in cobbler.
 * @param form the form
 * @param user currently logged in user
 * @param server server to update
 * @return the command
 */
public static CobblerPowerSettingsUpdateCommand getPowerSettingsUpdateCommand(
        DynaActionForm form, User user, Server server) {
    return new CobblerPowerSettingsUpdateCommand(
        user, server, form.getString(POWER_TYPE), form.getString(POWER_ADDRESS),
        form.getString(POWER_USERNAME), form.getString(POWER_PASSWORD),
        form.getString(POWER_ID));
}