Java Code Examples for org.apache.struts.action.ActionMessages

The following examples show how to use org.apache.struts.action.ActionMessages. These examples are extracted from open source projects. 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
public ActionForward gradeSubmissionStepOne(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {

    MarkSheetTeacherGradeSubmissionBean submissionBean =
            (MarkSheetTeacherGradeSubmissionBean) RenderUtils.getViewState().getMetaObject().getObject();
    request.setAttribute("submissionBean", submissionBean);

    ActionMessages actionMessages = new ActionMessages();
    boolean canSubmitMarksAnyCurricularCourse =
            checkIfCanSubmitMarksToAnyCurricularCourse(submissionBean.getAllCurricularCourses(), submissionBean
                    .getExecutionCourse().getExecutionPeriod(), request, actionMessages);
    calculateMarksToSubmit(request, submissionBean);
    request.setAttribute("executionCourse", submissionBean.getExecutionCourse());
    if (submissionBean.getMarksToSubmit().isEmpty()) {
        addMessage(
                request,
                actionMessages,
                (!canSubmitMarksAnyCurricularCourse) ? "error.teacher.gradeSubmission.noStudentsToSubmitMarksInPeriods" : "error.teacher.gradeSubmission.noStudentsToSubmitMarks");
        return doForward(request, "/teacher/evaluation/gradeSubmission/gradeSubmissionStepOne.jsp");
    }

    return doForward(request, "/teacher/evaluation/gradeSubmission/gradeSubmissionStepTwo.jsp");
}
 
Example 2
Source Project: unitime   Source File: SessionRollForward.java    License: Apache License 2.0 6 votes vote down vote up
private void rollRoomGroupsForward(ActionMessages errors, Session fromSession, Session toSession) {
	RoomGroup fromRoomGroup = null;
	RoomGroup toRoomGroup = null;
	RoomGroupDAO rgDao = new RoomGroupDAO();
	Collection fromRoomGroups = RoomGroup.getAllRoomGroupsForSession(fromSession);
	try {
		if (fromRoomGroups != null && !fromRoomGroups.isEmpty()){
			for (Iterator it = fromRoomGroups.iterator(); it.hasNext();){
				fromRoomGroup = (RoomGroup) it.next();
				if (fromRoomGroup != null){
					toRoomGroup = (RoomGroup) fromRoomGroup.clone();
					toRoomGroup.setSession(toSession);
					if (fromRoomGroup.getDepartment() != null)
						toRoomGroup.setDepartment(fromRoomGroup.getDepartment().findSameDepartmentInSession(toSession));
					rgDao.saveOrUpdate(toRoomGroup);
				}
			}
		}
	} catch (Exception e) {
		iLog.error("Failed to roll all room groups forward.", e);
		errors.add("rollForward", new ActionMessage("errors.rollForward", "Room Groups", fromSession.getLabel(), toSession.getLabel(), "Failed to roll all room groups forward."));
	}
}
 
Example 3
private File checkTempRecipientExportFile(int companyID, String fileName, ActionMessages errors) {
	File companyCsvExportDirectory = new File(RecipientExportWorker.EXPORT_FILE_DIRECTORY + File.separator + companyID);
	if (!companyCsvExportDirectory.exists()) {
		companyCsvExportDirectory.mkdirs();
	}
	
	if (StringUtils.isNotBlank(fileName)) {
		String mandatoryExportTempFilePrefix = "RecipientExport_" + companyID + "_";
		
		if (!fileName.startsWith(mandatoryExportTempFilePrefix) || fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
			logger.error("Illegal temp file for export: " + fileName);
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied"));
			return null;
		} else {
			return new File(companyCsvExportDirectory, fileName);
		}
	} else {
		return null;
	}
}
 
Example 4
/**
 * Checks on a few conditions that would cause a warning message to be displayed on top of the Purchase Order page.
 *
 * @param po the PurchaseOrderDocument whose status and indicators are to be checked in the conditions
 * @return boolean true if the Purchase Order doesn't have any warnings and false otherwise.
 */
protected void checkForPOWarnings(PurchaseOrderDocument po, ActionMessages messages) {
    // "This is not the current version of this Purchase Order." (curr_ind = N and doc status is not enroute)
    if (!po.isPurchaseOrderCurrentIndicator() && !po.getDocumentHeader().getWorkflowDocument().isEnroute()) {
        KNSGlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_NOT_CURRENT);
    }
    // "This document is a pending action. This is not the current version of this Purchase Order" (curr_ind = N and doc status
    // is enroute)
    if (!po.isPurchaseOrderCurrentIndicator() && po.getDocumentHeader().getWorkflowDocument().isEnroute()) {
        KNSGlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION_NOT_CURRENT);
    }
    // "There is a pending action on this Purchase Order." (pend_action = Y)
    if (po.isPendingActionIndicator()) {
        KNSGlobalVariables.getMessageList().add(PurapKeyConstants.WARNING_PURCHASE_ORDER_PENDING_ACTION);
    }

    if (!po.isPurchaseOrderCurrentIndicator()) {
        ActionMessage noteMessage = new ActionMessage(PurapKeyConstants.WARNING_PURCHASE_ORDER_ALL_NOTES);
        messages.add(PurapConstants.NOTE_TAB_WARNING, noteMessage);
    }
}
 
Example 5
Source Project: unitime   Source File: PreferencesAction.java    License: Apache License 2.0 6 votes vote down vote up
protected void addInstructorPref(
        HttpServletRequest request, 
        PreferencesForm frm,
        ActionMessages errors ) {
 
    List lst = frm.getInstructorPrefs();
    if(frm.checkPrefs(lst)) {
        for (int i=0; i<Constants.PREF_ROWS_ADDED; i++) {
         frm.addToInstructorPrefs(
                 Preference.BLANK_PREF_VALUE, 
                 Preference.BLANK_PREF_VALUE );
        }
        request.setAttribute(HASH_ATTR, HASH_INSTRUCTOR_PREF);
    }
    else {
        errors.add("instructorPrefs", 
                   new ActionMessage(
                           "errors.generic", 
                           MSG.errorInvalidAttributePreference()) );
        saveErrors(request, errors);
    }
}
 
Example 6
Source Project: uyuni   Source File: ActionChainEditAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Schedules an Action Chain.
 * @param mapping current mapping object
 * @param request current request object
 * @param form current form object
 * @param actionChain current Action Chain
 * @return
 */
private ActionForward schedule(ActionMapping mapping, HttpServletRequest request,
    DynaActionForm form, ActionChain actionChain) {
    Date date = getStrutsDelegate().readDatePicker(form, DATE_ATTRIBUTE,
        DatePicker.YEAR_RANGE_POSITIVE);
    try {
        ActionChainFactory.schedule(actionChain, date);
        ActionMessages messages = new ActionMessages();
        messages.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("actionchain.jsp.scheduled", actionChain.getLabel()));
        getStrutsDelegate().saveMessages(request, messages);
        return mapping.findForward(TO_LIST_FORWARD);
    }
    catch (TaskomaticApiException e) {
        ActionErrors errors = new ActionErrors();
        getStrutsDelegate().addError(errors, "taskscheduler.down");
        getStrutsDelegate().saveMessages(request, errors);
        HibernateFactory.getSession().clear();
        return mapping.findForward(TO_LIST_FORWARD);
    }
}
 
Example 7
Source Project: spacewalk   Source File: CreateUserAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
private User createIntoOrg(RequestContext requestContext,
                           CreateUserCommand command,
                           String password,
                           ActionMessages msgs) {

    User creator = requestContext.getCurrentUser();
    Org org = creator.getOrg();

    command.setOrg(org);
    command.setCompany(creator.getCompany());
    command.setMakeOrgAdmin(false);
    command.setMakeSatAdmin(false);
    command.storeNewUser();

    User newUser = command.getUser();

    msgs.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.userCreatedIntoOrg",
                    StringEscapeUtils.escapeHtml(newUser.getLogin()),
                    newUser.getEmail()));


    return newUser;
}
 
Example 8
/**
 *
 * {@inheritDoc}
 */
@Override
protected void processMessage(ActionMessages msg,
        String methodName,
        long successCount,
        long failureCount) {

    Object[] args = new Object [] {String.valueOf(successCount),
            String.valueOf(failureCount)
    };

    if (failureCount > 0) {
        addToMessage(msg, methodName, false, args);
    }
    else  if (successCount > 0) {
        addToMessage(msg, methodName, true, args);
    }
}
 
Example 9
Source Project: unitime   Source File: PreferencesAction.java    License: Apache License 2.0 6 votes vote down vote up
protected void addAttributePref(
        HttpServletRequest request, 
        PreferencesForm frm,
        ActionMessages errors ) {
 
    List lst = frm.getAttributePrefs();
    if(frm.checkPrefs(lst)) {
        for (int i=0; i<Constants.PREF_ROWS_ADDED; i++) {
         frm.addToAttributePrefs(
                 Preference.BLANK_PREF_VALUE, 
                 Preference.BLANK_PREF_VALUE );
        }
        request.setAttribute(HASH_ATTR, HASH_ATTRIBUTE_PREF);
    }
    else {
        errors.add("attributePrefs", 
                   new ActionMessage(
                           "errors.generic", 
                           MSG.errorInvalidAttributePreference()) );
        saveErrors(request, errors);
    }
}
 
Example 10
private ActionForward searchMarkSheets(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response, MarkSheetManagementSearchBean searchBean) throws FenixServiceException {

    ActionMessages actionMessages = createActionMessages();
    try {
        Map<EvaluationSeason, MarkSheetSearchResultBean> result = SearchMarkSheets.run(searchBean);

        request.setAttribute("edit", searchBean);
        request.setAttribute("searchResult", result);
        request.setAttribute("url", buildSearchUrl(searchBean));

    } catch (InvalidArgumentsServiceException e) {
        addMessage(request, actionMessages, e.getMessage());
    }
    return mapping.getInputForward();
}
 
Example 11
Source Project: uyuni   Source File: KickstartHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a message to the user about having a kickstart channel that is missing
 * required packages.
 * @param ksdata The kickstart data that contains the kickstart channel.
 * @return Messages to add to the request.
 */
public ActionMessages createInvalidChannelMsg(KickstartData ksdata) {
    ActionMessages msg = new ActionMessages();
    Object[] args = new Object[] {createPackageNameList(ksdata)};
    msg.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("kickstart.invalidchannel.message", args));
    if (ksdata.getChannel().getOrg() == null) { //if not a custom channel
        if (ksdata.isRhel8()) {
            //RHEL 8 - tell them to sync AppStream
            msg.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("kickstart.invalidchannel.satmessage.appstream"));
        }
        else {
            //Tell them that they should sync the RHN Tools channel.
            msg.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("kickstart.invalidchannel.satmessage"));
        }
    }
    return msg;
}
 
Example 12
Source Project: rice   Source File: MessageQueueAction.java    License: Educational Community License v2.0 6 votes vote down vote up
public ActionForward saveAndResubmit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
MessageQueueForm routeQueueForm = (MessageQueueForm) form;
PersistedMessageBO message = save(routeQueueForm);
KSBServiceLocator.getThreadPool().execute(new MessageServiceInvoker(message));

ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("routequeue.RouteQueueService.queued"));
saveMessages(request, messages);

routeQueueForm.setMessageId(null);
routeQueueForm.setMessageQueueFromDatabase(null);
routeQueueForm.setMessageQueueFromForm(null);
routeQueueForm.setShowEdit("yes");
routeQueueForm.setMethodToCall("");
establishRequiredState(request, form);
routeQueueForm.setMessageId(message.getRouteQueueId());
routeQueueForm.setMessageQueueFromForm(message);
routeQueueForm.setNewQueueDate(routeQueueForm.getExistingQueueDate());
routeQueueForm.getMessageQueueFromForm().setMethodCall(unwrapPayload(message));
return mapping.findForward("report");
   }
 
Example 13
private List<Message> adopt(ActionMessages messages, String property) {
    Iterator<ActionMessage> iterator = messages.get(property);
    List<Message> popups = new ArrayList<>();

    while (iterator.hasNext()) {
        popups.add(adopt(iterator.next()));
    }

    return popups;
}
 
Example 14
/**
 * A passthrough for deleting revisions so that affected config sets are also
 * cleared
 * @param mapping struts ActionMapping
 * @param form struts ActionForm
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return A forward to the Manage Revisions page.
 */
public ActionForward delete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    RequestContext requestContext = new RequestContext(request);
    checkAcl(requestContext);

    RhnSet set = updateSet(request);

    //if they chose no config revisions, return to the same page with a message
    if (set.isEmpty()) {
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("emptyselectionerror"));
        getStrutsDelegate().saveMessages(request, msg);

        Map params = makeParamMap(form, request);
        return getStrutsDelegate().forwardParams(
                mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
    }

    ActionForward forward = deleteRevisions(request, form, mapping, set);

    //now some of the sets may be invalid, so delete them.
    ConfigActionHelper.clearRhnSets(requestContext.getCurrentUser());

    return forward;
}
 
Example 15
protected MailingsQueryWorker createMailingsQueryWorker(ActionMessages errors, MailingBaseForm mailingBaseForm, HttpServletRequest req, int companyId, int adminId, String types, boolean isTemplate, String sort, String direction, int page, int rownums, final boolean includeTargetGroups) throws Exception {
    MailingsListProperties props = new MailingsListProperties();
    props.setTypes(types);
    props.setTemplate(isTemplate);
    props.setSort(sort);
    props.setDirection(direction);
    props.setPage(page);
    props.setRownums(rownums);
    props.setIncludeTargetGroups(includeTargetGroups);
    props.setAdditionalColumns(getAdditionalColumns(mailingBaseForm));

    return new MailingsQueryWorker(mailingDao, companyId, adminId, props);
}
 
Example 16
Source Project: uyuni   Source File: EnableUserSetupAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
        ActionForm formIn,
        HttpServletRequest request,
        HttpServletResponse response) {

    if (!AclManager.hasAcl("user_role(org_admin)", request, null)) {
        //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;
    }

    RequestContext requestContext = new RequestContext(request);

    Long uid = requestContext.getRequiredParam("uid");

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

    if (!user.isDisabled()) {
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("userenable.error.usernotdisabled",
               StringEscapeUtils.escapeHtml4(user.getLogin())));
        getStrutsDelegate().saveMessages(request, msg);
    }

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}
 
Example 17
private void lookupLogins(String email,
        ActionErrors errors, ActionMessages msgs, HttpSession session) {

    // Check if time elapsed from last request
    if (!hasTimeElapsed(session, "logins", email, LOGINS_REQUEST_TIMEOUT)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("help.credentials.rerequest",
                        LOGINS_REQUEST_TIMEOUT));
        return;
    }

    List<User> users = UserFactory.lookupByEmail(email);

    if (!users.isEmpty()) {
        StringBuilder logins = new StringBuilder();

        for (User usr : users) {
            logins.append(usr.getLogin() + "\n");
        }

        String emailBody = MailHelper.composeEmailBody("email.forgotten.logins",
                email, logins.toString(), ConfigDefaults.get().getHostname());
        String subject = MailHelper.PRODUCT_PREFIX + LocalizationService.getInstance().
                getMessage("help.credentials.jsp.logininfo");
        String rhnHeader = "Requested " + subject + " for " + email;
        MailHelper.withSmtp().addRhnHeader(rhnHeader).sendEmail(email, subject, emailBody);

        // Save time and email to session
        saveRequestTime(session, "logins", email);

        msgs.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("help.credentials.loginssent", email));
    }
    else {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("help.credentials.nologins"));
    }
}
 
Example 18
/**
 *
 * Raises an error message saying javascript is required
 * to process this page
 * @param mapping struts ActionMapping
 * @param formIn struts ActionForm
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return An action forward to the default page with the error message
 */
public ActionForward handleNoScript(ActionMapping mapping,
                        ActionForm formIn,
                        HttpServletRequest request,
                        HttpServletResponse response) {
    StrutsDelegate strutsDelegate = getStrutsDelegate();
    ActionMessages msg = new ActionMessages();
    msg.add(ActionMessages.GLOBAL_MESSAGE, getNoScriptMessage());
    strutsDelegate.saveMessages(request, msg);

    Map params = makeParamMap(formIn, request);
    String forward = getForwardName(request);
    return strutsDelegate.forwardParams(mapping.findForward(forward), params);
}
 
Example 19
/**
 * This function checks if the user entered a valid e-mail, hostname,
 * and if the password and password confirmation fields match. Any
 * errors found are returned.
 * @param GeneralConfingForm to validate
 * @return errors that were found in the submitted form
 */
private ActionErrors validateForm(DynaActionForm form) {
    ActionErrors errors = new ActionErrors();

    // Check if proxy is given as host:port
    String proxy = (String) form.get(
            translateFormPropertyName("server.satellite.http_proxy"));
    HostPortValidator validator = HostPortValidator.getInstance();
    if (!(proxy.equals("") || validator.isValid(proxy))) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.proxy_invalid"));
    }

    String password = (String) form.get(
               translateFormPropertyName("server.satellite.http_proxy_password"));
    String confirmationPassword = (String) form.get(
       translateFormPropertyName("server.satellite.http_proxy_password_confirm"));

    if (!password.equals(confirmationPassword)) {
        form.set(
                translateFormPropertyName("server.satellite.http_proxy_password"),
                "");

        form.set(
                translateFormPropertyName
                ("server.satellite.http_proxy_password_confirm"),
                "");
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.password_mismatch"));
    }

    return errors;
}
 
Example 20
private boolean checkNewAttachmentSize(ComMailingAttachmentsForm form, ActionMessages errors, ActionMessages messages) {
	if (form.getNewAttachment().getFileSize() > configService.getIntegerValue(ConfigValue.MaximumUploadAttachmentSize)) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("component.size.error", configService.getIntegerValue(ConfigValue.MaximumUploadAttachmentSize) / 1024f / 1024));
		return false;
	} else if (form.getNewAttachment().getFileSize() > configService.getIntegerValue(ConfigValue.MaximumWarningAttachmentSize)) {
		messages.add(GuiConstants.ACTIONMESSAGE_CONTAINER_WARNING, new ActionMessage("warning.component.size", configService.getIntegerValue(ConfigValue.MaximumWarningAttachmentSize) / 1024f / 1024));
	}
	return true;
}
 
Example 21
Source Project: spacewalk   Source File: RhnHelperTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testEmptySelectionError() {
    RhnMockHttpServletRequest request = new RhnMockHttpServletRequest();
    RhnHelper.handleEmptySelection(request);
    assertNotNull(request.getAttribute(Globals.MESSAGE_KEY));
    assertNotNull(request.getSession().getAttribute(Globals.MESSAGE_KEY));
    ActionMessages am = (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);
    assertEquals(1, am.size());
    ActionMessage key =   new ActionMessage(
                                        RhnHelper.DEFAULT_EMPTY_SELECTION_KEY);
    assertEquals(key.getKey(), ((ActionMessage)am.get().next()).getKey());
}
 
Example 22
public static boolean validateFloat(Object bean, ValidatorAction va, Field field, ActionMessages errors,
        HttpServletRequest request, ServletContext application) {

    String inputString = ValidatorUtils.getValueAsString(bean, field.getProperty());
    String lowerValueString = field.getVarValue("value");

    if ((inputString == null) || (inputString.length() == 0)) {
        return true;
    }
    Double input = null;
    Double lowerValue = null;

    try {
        input = new Double(inputString);
        lowerValue = new Double(lowerValueString);
    } catch (NumberFormatException e) {
        errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
        return false;
    }

    if (!GenericValidator.isBlankOrNull(inputString)) {
        if (input.floatValue() <= lowerValue.floatValue()) {
            errors.add(field.getKey(), Resources.getActionMessage(request, va, field));
        }
        return false;
    }

    return true;
}
 
Example 23
Source Project: uyuni   Source File: EditGroupAction.java    License: 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 24
Source Project: unitime   Source File: ClassEditAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add an instructor to the list (UI)
 * @param request
 * @param frm
 * @param errors
 */
protected void addInstructor(
        HttpServletRequest request,
        ClassEditForm frm,
        ActionMessages errors ) {

    if(request.getParameter("instrListTypeAction")!=null
            && request.getParameter("instrListTypeAction").toString().length()>0)
        return;

    frm.addToInstructors(null);
    request.setAttribute(HASH_ATTR, HASH_INSTRUCTORS);
}
 
Example 25
/**
 * Updates the System Groups permissions for the specified user.
 * @param mapping Struts ActionMapping
 * @param formIn Form containing submitted data.
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 */
public void updatePerm(ActionMapping mapping,
                                ActionForm formIn,
                                HttpServletRequest request,
                                HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);
    User user = UserManager.lookupUser(requestContext.getCurrentUser(),
            requestContext.getParamAsLong("uid"));
    if (user == null) {
        throw new BadParameterException("Invalid uid");
    }
    //request.setAttribute(RhnHelper.TARGET_USER, user);

    RhnSet set =  getSetDecl().get(requestContext.getCurrentUser());

    List<Long> serverGroupIds =
            set.getElements().stream().map(RhnSetElement::getElement).collect(toList());

    UserManager.updateServerGroupPermsForUser(user, serverGroupIds);

    ActionMessages msgs = new ActionMessages();
    msgs.add(ActionMessages.GLOBAL_MESSAGE,
         new ActionMessage("message.perms_updated",
         StringEscapeUtils.escapeHtml4(user.getLogin())));
    saveMessages(request, msgs);
}
 
Example 26
private void createMessage(HttpServletRequest request, int successes) {
    ActionMessages msg = new ActionMessages();
    if (successes == 1) {
        msg.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("unsubscribe.ssm.success"));
    }
    else {
        msg.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("unsubscribe.ssm.successes", new Integer(successes)));
    }
    getStrutsDelegate().saveMessages(request, msg);
}
 
Example 27
Source Project: unitime   Source File: CourseNumberSuggestBox.java    License: Apache License 2.0 5 votes vote down vote up
public int doStartTag() throws JspException {
       ActionMessages errors = null;

       try {
           errors = TagUtils.getInstance().getActionMessages(pageContext, Globals.ERROR_KEY);
       } catch (JspException e) {
           TagUtils.getInstance().saveException(pageContext, e);
           throw e;
       }
       
       String hint = null;
       if (errors != null && !errors.isEmpty()) {
       	 String message = null;
            Iterator reports = (getProperty() == null ? errors.get() : errors.get(getProperty()));
            while (reports.hasNext()) {
           	 ActionMessage report = (ActionMessage) reports.next();
           	 if (report.isResource()) {
           		 message = TagUtils.getInstance().message(pageContext, null, Globals.LOCALE_KEY, report.getKey(), report.getValues());
           	 } else {
           		 message = report.getKey();
           	 }
           	 if (message != null && !message.isEmpty()) {
           		 hint = (hint == null ? "" : hint + "<br>") + message;
           	 }
            }
       }
       
	// setStyleClass("unitime-DateSelectionBox");
	String onchange = getOnchange(); setOnchange(null);
	TagUtils.getInstance().write(pageContext, "<span name='UniTimeGWT:CourseNumberSuggestBox' configuration=\"" + getConfiguration() + "\"" +
			(hint == null ? "" : " error=\"" + hint + "\"") +
			(onchange == null ? "" : " onchange=\"" + onchange + "\"") +
			(getOuterStyle() == null ? "" : " style=\"" + getOuterStyle() + "\"" ) +
			">");
	super.doStartTag();
	TagUtils.getInstance().write(pageContext, "</span>");
	return EVAL_BODY_BUFFERED;
}
 
Example 28
Source Project: uyuni   Source File: BaseSubscribeAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ActionForward handleDataHasChanged(ActionMapping mapping,
        HttpServletRequest request) {
    log.debug("Base channels have changed due previous action");

    StrutsDelegate strutsDelegate = getStrutsDelegate();
    ActionMessages msgs = new ActionMessages();
    msgs.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("basesub.jsp.dataHasChanged"));
    strutsDelegate.saveMessages(request, msgs);

    return strutsDelegate.forwardParams(mapping.findForward("success"),
            new HashMap());
}
 
Example 29
Source Project: uyuni   Source File: AffectedSystemsAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Applies the selected errata
 * @param mapping ActionMapping
 * @param formIn ActionForm
 * @param request ServletRequest
 * @param response ServletResponse
 * @return The ActionForward to go to next.
 */
public ActionForward applyErrata(ActionMapping mapping,
                                  ActionForm formIn,
                                  HttpServletRequest request,
                                  HttpServletResponse response) {
    RhnSet set = updateSet(request);
    Map<String, Object> params = new HashMap<String, Object>();

    StrutsDelegate strutsDelegate = getStrutsDelegate();

    //if they chose no systems, return to the same page with a message
    if (set.isEmpty()) {
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("affectedsystems.applynone"));
        params = makeParamMap(formIn, request);
        strutsDelegate.saveMessages(request, msg);
        return strutsDelegate.forwardParams(
                mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
    }

    //if they chose systems, send them to the confirmation page
    Long eid = new RequestContext(request).getParamAsLong("eid");
    if (eid != null) {
        params.put("eid", eid);
    }
    return strutsDelegate.forwardParams(
                            mapping.findForward(RhnHelper.CONFIRM_FORWARD), params);
}
 
Example 30
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
    RequestContext rctx = new RequestContext(request);
    Long sid = rctx.getRequiredParam("sid");
    User user = rctx.getCurrentUser();
    Server s  = SystemManager.lookupByIdAndUser(sid, user);

    if (s.hasEntitlement(EntitlementManager.MANAGEMENT)) {
        RhnSet set = RhnSetDecl.SYSTEMS.get(user);

        if (set.getElementValues().contains(s.getId())) {
            set.removeElement(s.getId());
            RhnSetManager.store(set);

            ActionMessages msg = new ActionMessages();
            msg.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("system.sdc.removefromssm"));
            getStrutsDelegate().saveMessages(request, msg);

        }

    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("sid", sid);
    return getStrutsDelegate().forwardParams(
            mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
}