Java Code Examples for org.apache.struts.action.ActionErrors#isEmpty()

The following examples show how to use org.apache.struts.action.ActionErrors#isEmpty() . 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: SsmScheduleXccdfAction.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ActionForward execute(ActionMapping mapping,
        ActionForm formIn,
        HttpServletRequest request,
        HttpServletResponse response) {
    DynaActionForm form = (DynaActionForm) formIn;

    if (isSubmitted(form)) {
        ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, form);
        if (errors.isEmpty()) {
            return getStrutsDelegate().forwardParams(mapping.findForward("submit"),
                    request.getParameterMap());
        }
        getStrutsDelegate().saveMessages(request, errors);
    }
    setupDatePicker(request, form);
    setupListHelper(request);
    return getStrutsDelegate().forwardParams(
        mapping.findForward(RhnHelper.DEFAULT_FORWARD),
        request.getParameterMap());
}
 
Example 2
Source File: EditGroupAction.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
private Long create(DynaActionForm form, ActionErrors errors,
        RequestContext ctx) {

    validate(form, errors, ctx);

    if (errors.isEmpty()) {
        ServerGroupManager manager = ServerGroupManager.getInstance();
        ManagedServerGroup sg = manager.create(ctx.getCurrentUser(),
                form.getString("name"), form.getString("description"));

        if (form.get("is_ssm") != null && (Boolean)form.get("is_ssm")) {
            List<SystemOverview> systems = SystemManager.inSet(ctx.getCurrentUser(),
                    RhnSetDecl.SYSTEMS.getLabel());
            List<Server> hibernateServers = new ArrayList<Server>();
            for (SystemOverview system : systems) {
                hibernateServers.add(ServerFactory.lookupById(system.getId()));
            }
            manager.addServers(sg, hibernateServers, ctx.getCurrentUser());
        }

        return sg.getId();
    }

    return null;
}
 
Example 3
Source File: EditGroupAction.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
private Long create(DynaActionForm form, ActionErrors errors,
        RequestContext ctx) {

    validate(form, errors, ctx);

    if (errors.isEmpty()) {
        ServerGroupManager manager = ServerGroupManager.getInstance();
        ManagedServerGroup sg = manager.create(ctx.getCurrentUser(),
                form.getString("name"), form.getString("description"));

        if (form.get("is_ssm") != null && (Boolean)form.get("is_ssm")) {
            List<SystemOverview> systems = SystemManager.inSet(ctx.getCurrentUser(),
                    RhnSetDecl.SYSTEMS.getLabel());
            List<Server> hibernateServers = new ArrayList<Server>();
            for (SystemOverview system : systems) {
                hibernateServers.add(ServerFactory.lookupById(system.getId()));
            }
            manager.addServers(sg, hibernateServers, ctx.getCurrentUser());
        }

        return sg.getId();
    }

    return null;
}
 
Example 4
Source File: JavaSecurityManagementForm.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This method is used to check for completeness of the form as well as verification of the desired password
 */
public ActionErrors validateGenerateClientKeystore(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    // check that all data is filled in
    if (StringUtils.isBlank(getAlias())) {
        errors.add("property", new ActionMessage("Alias must have a valid value.",false));
    }
    if (StringUtils.isBlank(getPassword()) || StringUtils.isBlank(getPasswordVerify()) ) {
        errors.add("property", new ActionMessage("Password must have a valid value in both fields.",false));
    }
    if (errors.isEmpty()) {
        // if password and passwordVerify are not equal error out
        if (!StringUtils.equals(getPassword(), getPasswordVerify())) {
            errors.add("property", new ActionMessage("Passwords do not match.",false));
        }
    }
    if (errors.isEmpty()) {
        try {
            if (KSBServiceLocator.getJavaSecurityManagementService().isAliasInKeystore(getAlias())) {
                errors.add("property", new ActionMessage("Alias '" + getAlias() + "' already exists in keystore.",false));
            }
        } catch (KeyStoreException e) {
            errors.add("property", new ActionMessage("Could not check keystore file for alias '" + getAlias(),false));
        }
    }
    return errors;
}
 
Example 5
Source File: EditGroupAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
private void edit(DynaActionForm form, ActionErrors errors,
        RequestContext ctx) {

    validate(form, errors, ctx);

    if (errors.isEmpty()) {
        ManagedServerGroup sg = ctx.lookupAndBindServerGroup();
        sg.setName(form.getString("name"));
        sg.setDescription(form.getString("description"));
        ServerGroupFactory.save(sg);
    }
}
 
Example 6
Source File: ResetLinkAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm formIn,
                HttpServletRequest request, HttpServletResponse response) {

    log.debug("ResetLinkAction");
    RequestContext requestContext = new RequestContext(request);
    String token = requestContext.getRequiredParamAsString("token");

    // Does token exist, and is it valid?
    ResetPassword rp = ResetPasswordFactory.lookupByToken(token);

    ActionErrors errs = ResetPasswordFactory.findErrors(rp);
    if (!errs.isEmpty()) {
        addErrors(request, errs);
        return mapping.findForward(INVALID);
    }

    // Check for disabled user
    User u = UserFactory.lookupById(rp.getUserId());
    if (u.isDisabled()) {
        log.debug("findErrors: disabled user found");
        errs.add(ActionMessages.GLOBAL_MESSAGE,
                 new ActionMessage("resetpassword.jsp.error.disabled_user"));
        return mapping.findForward(INVALID);
    }

    // Everything looks good - send us to the next step
    return mapping.findForward(VALID);
}
 
Example 7
Source File: EditGroupAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void edit(DynaActionForm form, ActionErrors errors,
        RequestContext ctx) {

    validate(form, errors, ctx);

    if (errors.isEmpty()) {
        ManagedServerGroup sg = ctx.lookupAndBindServerGroup();
        sg.setName(form.getString("name"));
        sg.setDescription(form.getString("description"));
        ServerGroupFactory.save(sg);
    }
}
 
Example 8
Source File: ActivationKeyCloneAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public final ActionForward execute(ActionMapping mapping,
        ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {

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

    if (isSubmitted(form)) {
        ActionErrors errors = RhnValidationHelper.validateDynaActionForm(
                this, form);
        if (!errors.isEmpty()) {
            strutsDelegate.saveMessages(request, errors);
        }
        else {
            String cloneDescription = form.getString("label");
            String sdesc = (String) request.getSession().getAttribute(
                    "sdesc");
            if (StringUtils.isBlank(cloneDescription)) {
                cloneDescription = "clone-" + sdesc;
            }
            String sak = (String) request.getSession().getAttribute("sak");
            ActivationKeyCloneCommand cak = new ActivationKeyCloneCommand(
                    ctx.getCurrentUser(), sak, cloneDescription);

            createSuccessMessage(request, "activation-key.java.cloned",
                    sdesc);
            return mapping.findForward("success");
        }
    }

    ActivationKey key = ctx.lookupAndBindActivationKey();
    request.setAttribute("stoken", key.getToken());
    request.getSession().setAttribute("sak", key.getKey());
    request.getSession().setAttribute("sdesc", key.getNote());
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 9
Source File: CreateCustomKeyAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
        ActionForm formIn,
        HttpServletRequest request,
        HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    User user =  requestContext.getCurrentUser();

    if (requestContext.isSubmitted()) {
        String label = request.getParameter(LABEL_PARAM);
        String description = request.getParameter(DESC_PARAM);

        ActionErrors errors = validateLabelAndDescription(label, description, user);
        if (!errors.isEmpty()) {
            request.setAttribute("old_label", label);
            request.setAttribute("old_description", description);
            addErrors(request, errors);
            return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
        }

        CustomDataKey key = new CustomDataKey();
        key.setLabel(label);
        key.setDescription(description);
        key.setCreator(user);
        key.setOrg(user.getOrg());
        key.setLastModifier(user);
        ServerFactory.saveCustomKey(key);
        bindMessage(requestContext, "system.customkey.addsuccess");
        return mapping.findForward("created");
    }

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 10
Source File: ChangeEmailAction.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;

    ActionErrors errors = new ActionErrors();
    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 email = user.getEmail();
    String newEmail = (String)form.get("email");

    if (!email.equals(newEmail)) {
        try {
            validateAddress(newEmail, errors);
            if (errors.isEmpty()) {
                user.setEmail(newEmail);
                UserManager.storeUser(user);
                ActionMessages msgs = new ActionMessages();
                msgs.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("email.verified"));
                strutsDelegate.saveMessages(request, msgs);

                return strutsDelegate.forwardParam(mapping.findForward("updated"),
                    "uid", user.getId().toString());
           }
        }
        catch (AddressException e) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("error.addr_invalid", newEmail));
        }
    }
    else if (email.equals(newEmail)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                   new ActionMessage("error.same_email"));
    }

    //If it got this far, something went wrong
    addErrors(request, errors);
    return strutsDelegate.forwardParam(mapping.findForward("failure"),
            "uid", user.getId().toString());
}
 
Example 11
Source File: AdminUserEditAction.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();

    //We could be editing ourself, we could be editing another user...
    User targetUser = UserManager.lookupUser(requestContext.getCurrentUser(),
                                       requestContext.getParamAsLong("uid"));
    request.setAttribute(RhnHelper.TARGET_USER, targetUser);

    //Make sure we got a user, if not, we must have gotten a bad uid
    if (targetUser == null) {
        throw new BadParameterException("Invalid uid, targetUser not found");
    }
    User loggedInUser = requestContext.getCurrentUser();

    //Update the users details with info entered on the form
    ActionErrors errors = updateDetails(loggedInUser, targetUser, form);
    //If we have validation/form errors, return now and let the user fix those first
    if (!errors.isEmpty()) {
        return returnFailure(mapping, request, errors, targetUser.getId());
    }

    //Create the user info updated success message
    createSuccessMessage(request, "message.userInfoUpdated", null);

    //Now we need to update user roles. If we get errors here, return failure
    errors = updateRoles(request, targetUser, loggedInUser);
    if (!errors.isEmpty()) {
        return returnFailure(mapping, request, errors, targetUser.getId());
    }

    //Everything must have gone smoothly
    UserManager.storeUser(targetUser);

    ActionForward dest = mapping.findForward("success");
    /*
     * Does the user still have the roles needed to see /users/UserDetails.do?
     * Check here and make a decision so user doesn't go to a permission error page.
     */
    //If the logged in user is the same as the target user and we have removed the
    //target users org admin status, forward to noaccess instead
    if (loggedInUser.equals(targetUser) &&
        !targetUser.hasRole(RoleFactory.ORG_ADMIN)) {
        dest = mapping.findForward("noaccess");
    }

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

    RequestContext rctx = new RequestContext(request);
    DynaActionForm daForm = (DynaActionForm)form;
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    ActionForward forward = null;
    Map<String, Object> params = new HashMap<String, Object>();

    Long nid = null;
    if (!(request.getParameter("nid") == null)) {
        nid = Long.parseLong(request.getParameter("nid"));
    }

    Note note = new Note();
    User loggedInUser = rctx.getCurrentUser();
    Long sid = rctx.getRequiredParam(RequestContext.SID);
    Server server = SystemManager.lookupByIdAndUser(sid, loggedInUser);

    if (nid != null) {
        request.setAttribute("id", nid);
        note = SystemManager.lookupNoteByIdAndSystem(loggedInUser, nid, sid);
    }

    params.put(RequestContext.SID, request.getParameter(RequestContext.SID));
    forward = strutsDelegate.forwardParams(
            mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);

    if (isSubmitted(daForm)) {
        ActionErrors errors = new ActionErrors();

        if (daForm.getString("subject").length() > 80) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.subjecttoolong"));
        }

        if (daForm.getString("subject").length() == 0) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.subjecttooshort"));
        }

        if (daForm.getString("note").length() > 4000) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.notetoolong"));
        }

        note.setSubject(daForm.getString("subject"));
        note.setNote(daForm.getString("note"));

        if (rctx.hasParam("create_button")) {
            if (errors.isEmpty()) {
                createSuccessMessage(request, "message.notecreated", "");
                note.setCreator(loggedInUser);
                server.addNote(note);
            }
        }
        else {
            if (errors.isEmpty()) {
                    createSuccessMessage(request, "message.noteupdated", "");
            }
        }
        if (!errors.isEmpty()) {
            addErrors(request, errors);
            forward = strutsDelegate.forwardParams(mapping.findForward("error"),
                    params);
        }
        else {
            ServerNoteFactory.save(note);
            forward = strutsDelegate.forwardParams(mapping.findForward("success"),
                    params);
        }
    }

    setupPageAndFormValues(rctx.getRequest(), daForm, server, note);
    return forward;
}
 
Example 13
Source File: EnableConfirmSetupAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Handles a dispatch action
 * Could be One of copy_to_sandbox,
 * copy_to_local, copy_to_global
 * &amp; delete_files
 * @param mapping the action mapping used for returning 'forward' url
 * @param context the request context
 * @return the forward url
 */
private ActionForward handleDispatchAction(ActionMapping mapping,
                                           RequestContext context) {

    User user = context.getCurrentUser();
    HttpServletRequest request = context.getRequest();
    // don't need the result, but we do need this to run.
    getDecl().get(user);
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    if (!user.hasRole(RoleFactory.ORG_ADMIN)) {
        //Throw an exception with a nice error message so the user
        //knows what went wrong.
        LocalizationService ls = LocalizationService.getInstance();
        PermissionException pex =
            new PermissionException("Only org admin's can reactivate users");
        pex.setLocalizedTitle(ls.getMessage("permission.jsp.title.enableuser"));
        pex.setLocalizedSummary(ls.getMessage("permission.jsp.summary.enableuser"));
        throw pex;
    }

    Iterator users = UserManager.usersInSet(user, "user_list", null).iterator();
    ActionErrors errors = new ActionErrors();
    int count = 0;

    while (users.hasNext()) {
        long id = ((UserOverview) users.next()).getId();
        User nextUser = UserManager.lookupUser(user, id);
        try {
             UserManager.enableUser(user, nextUser);
             count++;
             }
        catch (StateChangeException e) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage(e.getMessage(), nextUser.getLogin()));
        }
    }

    RhnSetDecl.USERS.clear(user);

    ActionMessages msg = new ActionMessages();
    StringBuilder messageKey = new StringBuilder("enable.confirmed");
    if (count > 1) {
        messageKey = messageKey.append(".plural");
    }

    msg.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage(messageKey.toString(), count));
    strutsDelegate.saveMessages(request, msg);

    if (errors.isEmpty()) {
        return mapping.findForward("enabled");
    }

    addErrors(request, errors);
    return strutsDelegate.forwardParams(mapping.findForward(RhnHelper.DEFAULT_FORWARD),
                                   makeParamMap(request));


}
 
Example 14
Source File: LoginAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ActionForward execute(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    ActionForward ret = null;
    DynaActionForm f = (DynaActionForm)form;

    // Validate the form
    ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, f);
    if (!errors.isEmpty()) {
        addErrors(request, errors);
        return mapping.findForward("failure");
    }

    ActionMessages messages = new ActionMessages();
    User user = LoginHelper.checkExternalAuthentication(request, messages, errors);
    // save stores msgs into the session (works for redirect)
    saveMessages(request, messages);
    addErrors(request, errors);
    errors.clear();

    // External-auth didn't return a user - try local-auth
    if (user == null) {
        user = loginUser(f.getString("username"), f.getString("password"),
                request, response, errors);
        if (errors.isEmpty()) {
            // No errors, log success
            log.info("LOCAL AUTH SUCCESS: [" + user.getLogin() + "]");
        }
        else {
            // Errors, log failure
            log.info("LOCAL AUTH FAILURE: [" + f.getString("username") + "]");
        }
    }
    // External-auth returned a user and no errors
    else if (errors.isEmpty()) {
        log.info("EXTERNAL AUTH SUCCESS: [" + user.getLogin() + "]");
    }

    if (errors.isEmpty()) {
        LoginHelper.successfulLogin(request, response, user);
    }
    else {
        addErrors(request, errors);

        ret = mapping.findForward("failure");
    }

    return ret;
}
 
Example 15
Source File: AdminUserEditAction.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();

    //We could be editing ourself, we could be editing another user...
    User targetUser = UserManager.lookupUser(requestContext.getCurrentUser(),
                                       requestContext.getParamAsLong("uid"));
    request.setAttribute(RhnHelper.TARGET_USER, targetUser);

    //Make sure we got a user, if not, we must have gotten a bad uid
    if (targetUser == null) {
        throw new BadParameterException("Invalid uid, targetUser not found");
    }
    User loggedInUser = requestContext.getCurrentUser();

    //Update the users details with info entered on the form
    ActionErrors errors = updateDetails(loggedInUser, targetUser, form);
    //If we have validation/form errors, return now and let the user fix those first
    if (!errors.isEmpty()) {
        return returnFailure(mapping, request, errors, targetUser.getId());
    }

    //Create the user info updated success message
    createSuccessMessage(request, "message.userInfoUpdated", null);

    //Now we need to update user roles. If we get errors here, return failure
    errors = updateRoles(request, targetUser, loggedInUser);
    if (!errors.isEmpty()) {
        return returnFailure(mapping, request, errors, targetUser.getId());
    }

    //Everything must have gone smoothly
    UserManager.storeUser(targetUser);

    ActionForward dest = mapping.findForward("success");
    /*
     * Does the user still have the roles needed to see /users/UserDetails.do?
     * Check here and make a decision so user doesn't go to a permission error page.
     */
    //If the logged in user is the same as the target user and we have removed the
    //target users org admin status, forward to noaccess instead
    if (loggedInUser.equals(targetUser) &&
        !targetUser.hasRole(RoleFactory.ORG_ADMIN)) {
        dest = mapping.findForward("noaccess");
    }

    return strutsDelegate.forwardParam(dest, "uid", String.valueOf(targetUser.getId()));
}
 
Example 16
Source File: CreateProfileAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {

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

    ActionForward forward = null;
    DynaActionForm f = (DynaActionForm)form;
    User user = requestContext.getCurrentUser();

    Server server = requestContext.lookupAndBindServer();
    request.setAttribute("system", server);

    if (!isSubmitted(f)) {
        setup(request, f);
        forward =  strutsDelegate.forwardParams(
                mapping.findForward(RhnHelper.DEFAULT_FORWARD),
                request.getParameterMap());
    }
    else {

        ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, f);
        if (errors.isEmpty()) {
            ActionMessages msgs = processForm(request, user, server, f);
            if (!msgs.isEmpty()) {
                strutsDelegate.saveMessages(request, msgs);

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("sid", request.getParameter("sid"));
                forward = strutsDelegate.forwardParams(mapping.findForward("created"),
                        params);
                if (log.isDebugEnabled() && (forward != null)) {
                    log.debug("Where are we going [" + forward.toString() + "]");
                }
            }
            else {
                forward =  strutsDelegate.forwardParams(
                        mapping.findForward(RhnHelper.DEFAULT_FORWARD),
                        request.getParameterMap());
            }
        }
        else {
            strutsDelegate.saveMessages(request, errors);
            setup(request, f);
            forward = mapping.findForward("error");
        }
    }

    return forward;
}
 
Example 17
Source File: SystemNoteEditAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) {

    RequestContext rctx = new RequestContext(request);
    DynaActionForm daForm = (DynaActionForm)form;
    StrutsDelegate strutsDelegate = getStrutsDelegate();

    ActionForward forward = null;
    Map<String, Object> params = new HashMap<String, Object>();

    Long nid = null;
    if (!(request.getParameter("nid") == null)) {
        nid = Long.parseLong(request.getParameter("nid"));
    }

    Note note = new Note();
    User loggedInUser = rctx.getCurrentUser();
    Long sid = rctx.getRequiredParam(RequestContext.SID);
    Server server = SystemManager.lookupByIdAndUser(sid, loggedInUser);

    if (nid != null) {
        request.setAttribute("id", nid);
        note = SystemManager.lookupNoteByIdAndSystem(loggedInUser, nid, sid);
    }

    params.put(RequestContext.SID, request.getParameter(RequestContext.SID));
    forward = strutsDelegate.forwardParams(
            mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);

    if (isSubmitted(daForm)) {
        ActionErrors errors = new ActionErrors();

        if (daForm.getString("subject").length() > 80) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.subjecttoolong"));
        }

        if (daForm.getString("subject").length() == 0) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.subjecttooshort"));
        }

        if (daForm.getString("note").length() > 4000) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("edit.note.notetoolong"));
        }

        note.setSubject(daForm.getString("subject"));
        note.setNote(daForm.getString("note"));

        if (rctx.hasParam("create_button")) {
            if (errors.isEmpty()) {
                createSuccessMessage(request, "message.notecreated", "");
                note.setCreator(loggedInUser);
                server.addNote(note);
            }
        }
        else {
            if (errors.isEmpty()) {
                    createSuccessMessage(request, "message.noteupdated", "");
            }
        }
        if (!errors.isEmpty()) {
            addErrors(request, errors);
            forward = strutsDelegate.forwardParams(mapping.findForward("error"),
                    params);
        }
        else {
            ServerNoteFactory.save(note);
            forward = strutsDelegate.forwardParams(mapping.findForward("success"),
                    params);
        }
    }

    setupPageAndFormValues(rctx.getRequest(), daForm, server, note);
    return forward;
}
 
Example 18
Source File: XccdfDiffSubmitAction.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 context = new RequestContext(request);
    DynaActionForm form = (DynaActionForm) formIn;
    ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, form);
    if (!errors.isEmpty()) {
        getStrutsDelegate().saveMessages(request, errors);
        return getStrutsDelegate().forwardParams(
                mapping.findForward("error"), request.getParameterMap());
    }

    Long first = (Long) form.get(FIRST);
    Long second = (Long) form.get(SECOND);
    User user = context.getCurrentUser();
    String view = getView(request);

    if (!ScapManager.isAvailableToUser(user, first)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
            MISSING_MSG, first, user.getLogin()));
    }
    if (!ScapManager.isAvailableToUser(user, second)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
            MISSING_MSG, second, user.getLogin()));
    }
    if (!errors.isEmpty()) {
        getStrutsDelegate().saveMessages(request, errors);
        return getStrutsDelegate().forwardParams(
                mapping.findForward("error"), request.getParameterMap());
    }

    XccdfTestResult firstTr = ScapFactory.lookupTestResultById(first);
    XccdfTestResult secondTr = ScapFactory.lookupTestResultById(second);
    request.setAttribute("metadataList", FULL.equals(view) ?
            TestResultDiffer.diff(firstTr, secondTr) :
            TestResultDiffer.diff(firstTr, secondTr, CHANGED.equals(view)));
    request.setAttribute(VIEW, view);

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

    request.setAttribute(ListTagHelper.PARENT_URL, request.getRequestURI() +
            "?" + FIRST + "=" + first + "&" + SECOND + "=" + second +
            "&" + VIEW + "=" + view);

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 19
Source File: BootstrapConfigAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ActionForward execute(ActionMapping mapping,
                             ActionForm formIn,
                             HttpServletRequest request,
                             HttpServletResponse response) {

    DynaActionForm form = (DynaActionForm) formIn;
    RequestContext requestContext = new RequestContext(request);

    StrutsDelegate strutsDelegate = getStrutsDelegate();

    request.setAttribute(CSRF_TOKEN, request.getSession().getAttribute("csrf_token"));

    if (isSubmitted(form)) {
        ActionErrors errors = RhnValidationHelper.validateDynaActionForm(
                          this, form);
        if (!errors.isEmpty()) {
            strutsDelegate.saveMessages(request, errors);
        }
        else {

            ConfigureBootstrapCommand cmd = (ConfigureBootstrapCommand)
            getCommand(requestContext.getCurrentUser());
            cmd.setHostname(IDN.toASCII(form.getString(HOSTNAME)));
            cmd.setSslPath(form.getString(SSL_CERT));
            cmd.setSaltEnabled((Boolean) form.get(SALT));
            cmd.setEnableSsl((Boolean) form.get(ENABLE_SSL));
            cmd.setEnableGpg((Boolean) form.get(ENABLE_GPG));
            cmd.setAllowConfigActions((Boolean) form.get(ALLOW_CONFIG_ACTIONS));
            cmd.setAllowRemoteCommands((Boolean) form.get(ALLOW_REMOTE_COMMANDS));
            cmd.setHttpProxy(form.getString(HTTP_PROXY));
            cmd.setHttpProxyUsername(form.getString(HTTP_PROXY_USERNAME));
            cmd.setHttpProxyPassword(form.getString(HTTP_PROXY_PASSWORD));
            ValidatorError[] verrors = cmd.storeConfiguration();

            if (verrors != null) {
                errors = RhnValidationHelper.validatorErrorToActionErrors(verrors);
                strutsDelegate.saveMessages(request, errors);
            }
            else {
                createSuccessMessage(request, "bootstrap.config.success",
                                     addProtocolToHostname(cmd.getHostname(),
                                           (Boolean) form.get(ENABLE_SSL)));
            }
        }
    }
    else {
        String caCertPath = CACertPathUtil.processCACertPath();
        form.set(HOSTNAME, IDN.toUnicode(
            Config.get().getString(ConfigDefaults.JABBER_SERVER)));
        form.set(SSL_CERT, caCertPath);
        form.set(SALT, Boolean.TRUE);
        form.set(ENABLE_SSL, Boolean.TRUE);
        form.set(ENABLE_GPG, Boolean.TRUE);
        form.set(ALLOW_CONFIG_ACTIONS, Boolean.FALSE);
        form.set(ALLOW_REMOTE_COMMANDS, Boolean.FALSE);
    }
    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 20
Source File: EditAddressAction.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;

    /* Validate the form. We don't do this on satellite since none of
     * the fields are required */
    ActionErrors verrors = RhnValidationHelper.validateDynaActionForm(this, form);
    if (!verrors.isEmpty()) {
        RhnValidationHelper.setFailedValidation(request);
        addErrors(request, verrors);
        return mapping.findForward("failure");
    }

    RequestContext requestContext = new RequestContext(request);

    User targetUser = UserManager.lookupUser(requestContext.getCurrentUser(),
            requestContext.getParamAsLong("uid"));
    request.setAttribute(RhnHelper.TARGET_USER, targetUser);

    if (targetUser == null) {
        LocalizationService ls = LocalizationService.getInstance();
        LookupException e = new LookupException("Could not find user");
        e.setLocalizedTitle(ls.getMessage("lookup.jsp.title.user"));
        e.setLocalizedReason1(ls.getMessage("lookup.jsp.reason1.user"));
        e.setLocalizedReason2(ls.getMessage("lookup.jsp.reason2.user"));
        throw e;
    }
    String addrType = (String) form.get("type");
    if (addrType == null) {
        throw new IllegalArgumentException("Invalid type");
    }

    targetUser.setPhone((String) form.get("phone"));
    targetUser.setFax((String) form.get("fax"));
    targetUser.setAddress1((String) form.get("address1"));
    targetUser.setAddress2((String) form.get("address2"));
    targetUser.setCity((String) form.get("city"));
    targetUser.setState((String) form.get("state"));
    targetUser.setZip((String) form.get("zip"));
    targetUser.setCountry((String) form.get("country"));

    UserManager.storeUser(targetUser);

    ActionForward base = mapping.findForward("success");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("uid", String.valueOf(targetUser.getId()));
    params.put("type", addrType);

    String newPath = ServletUtils.pathWithParams(base.getPath(), params);

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

    ActionForward fwd = new ActionForward(newPath,
                                         base.getRedirect());
    fwd.setName("success");
    return fwd;
}