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

The following examples show how to use org.apache.struts.action.ActionMessage. 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
protected boolean validateActivation(HttpServletRequest request, MailingSendForm form, ActionMessages errors, ActionMessages messages) {
      if (WorkflowParametersHelper.isWorkflowDriven(request) &&
              (form.getMailingtype() == MailingTypes.DATE_BASED.getCode() ||
                      form.getMailingtype() == MailingTypes.ACTION_BASED.getCode())) {
          return false;
      } else {
      	Tuple<Long, Long> calculatedMaxMailingSizes = mailingBaseService.calculateMaxSize((ComMailing) form.getMailing());
          Long approximateMaxSizeWithoutImages = calculatedMaxMailingSizes.getFirst();
      	long maximumMailingSizeAllowed = configService.getLongValue(ConfigValue.MailingSizeErrorThresholdBytes, AgnUtils.getCompanyID(request));
      	if (approximateMaxSizeWithoutImages > maximumMailingSizeAllowed) {
      		errors.add("global", new ActionMessage("error.mailing.size.large", maximumMailingSizeAllowed));
       	return false;
       } else {
              Long approximateMaxSize = calculatedMaxMailingSizes.getSecond();
       	long warningMailingSize = configService.getLongValue(ConfigValue.MailingSizeWarningThresholdBytes, AgnUtils.getCompanyID(request));
       	if (approximateMaxSize > warningMailingSize) {
       		messages.add(GuiConstants.ACTIONMESSAGE_CONTAINER_WARNING, new ActionMessage("warning.mailing.size.large", warningMailingSize));
       	}
        return validateNeedTarget(request, form, errors);
       }
}
  }
 
Example 2
/**
 * This is the equivalent of the Action
 * Deletes an erratum
 * @param mapping ActionMapping
 * @param formIn ActionForm
 * @param request ServletRequest
 * @param response ServletResponse
 * @return The ActionForward to go to next.
 */
public ActionForward deleteErratum(ActionMapping mapping,
                                   ActionForm formIn,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);

    Errata errata = requestContext.lookupErratum();
    ErrataManager.deleteErratum(requestContext.getCurrentUser(), errata);
    ActionMessages msgs = new ActionMessages();
    msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("erratum.delete",
            errata.getAdvisoryName()));
    getStrutsDelegate().saveMessages(request, msgs);
    return mapping.findForward("deleted");
}
 
Example 3
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 4
private void saveTargetGroupIfNecessary(RecipientForm aForm, ActionMessages errors, ActionMessages messages, ComAdmin admin, ActionMessages rulesValidationErrors) throws Exception {
	if (aForm.isNeedSaveTargetGroup()) {
		if (!targetService.checkIfTargetNameIsValid(aForm.getTargetShortname())) {
			errors.clear();
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.target.namenotallowed"));
		} else if (targetService.checkIfTargetNameAlreadyExists(admin.getCompanyID(), aForm.getTargetShortname(), 0)) {
			errors.clear();
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.target.namealreadyexists"));
		} else if (saveTargetGroup(aForm, admin, errors, rulesValidationErrors) > 0) {
		   messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("default.changes_saved"));
		} else {
		   errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.target.saving"));
		}

		aForm.setNeedSaveTargetGroup(false);
	}
}
 
Example 5
private void startImportWorker(ActionMapping mapping, HttpServletRequest req, ActionMessages errors, ComImportWizardForm comImportWizardForm) {
	try {
		String key = FUTURE_TASK + "@" + req.getSession(false).getId();
		
		if (!futureHolder.containsKey(key)) {
			// Create new import worker
			Future<? extends Object> writeContentFuture = getWriteContentFuture(req, comImportWizardForm);
			futureHolder.put(key, writeContentFuture);
			comImportWizardForm.setFutureIsRuning(true);
			comImportWizardForm.setImportIsRunning(true);
		}
	} catch (Exception e) {
		logger.error("company: " + e, e);
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception", configService.getValue(ConfigValue.SupportEmergencyUrl)));
		comImportWizardForm.setError(true); // do not refresh when an error has been occurred
		comImportWizardForm.setImportIsRunning(false);
	}
}
 
Example 6
public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)  {

	ComOptimizationForm optimizationForm = (ComOptimizationForm) form;
	ComOptimization deleteOptimization = optimizationService.get(optimizationForm.getOptimizationID(), optimizationForm.getCompanyID());
	ComAdmin admin = AgnUtils.getAdmin(request);
	ActionErrors errors = new ActionErrors();
	
	try {
		optimizationService.delete(deleteOptimization);
	} catch (MaildropDeleteException e) {
		logger.error("Could not delete optimization with ID: " + optimizationForm.getOptimizationID());
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("mailing.autooptimization.errors.delete", optimizationForm.getShortname() ));
	}
	saveErrors(request, errors);

	if (errors.isEmpty()) {
		ActionMessages actionMessages = new ActionMessages();
		actionMessages.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("default.selection.deleted"));
		saveMessages(request, actionMessages);
           writeUserActivityLog(admin, "delete Auto-Optimization", getOptimizationDescription(deleteOptimization));
	}
			
	return list(mapping, form, request, response);
}
 
Example 7
Source Project: uyuni   Source File: SsmKSScheduleAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Saves a success message in the Struts delegate.
 * @param context current request context
 * @param message message to save
 * @param result a result object
 */
private void saveSuccessMessage(RequestContext context, String message,
    ScheduleActionResult result) {
    String errorString = "";
    List<ValidatorError> errors = result.getErrors();
    if (!errors.isEmpty()) {
        LocalizationService ls = LocalizationService.getInstance();
        errorString = " " +
            ls.getPlainText("ssm.provision.errors", errors.size()) +
            "<ul>";
        for (ValidatorError error : errors) {
            errorString += "<li>" + error.getLocalizedMessage() + "</li>";
        }
        errorString += "</ul>";
    }

    ActionMessages msg = new ActionMessages();
    String[] params = {result.getSuccessCount() + "", errorString};
    msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(message, params));
    getStrutsDelegate().saveMessages(context.getRequest(), msg);
}
 
Example 8
Source Project: unitime   Source File: SettingsForm.java    License: Apache License 2.0 6 votes vote down vote up
/** 
 * Method validate
 * @param mapping
 * @param request
 * @return ActionErrors
 */
public ActionErrors validate(
    ActionMapping mapping,
    HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();
    
    if(key==null || key.trim().length()==0)
        errors.add("key", new ActionMessage("errors.required", ""));
    else {
        Settings setting = Settings.getSetting(key);
        if(op.equals("Save") && setting!=null && setting.getDefaultValue().toString().trim().length()>0)
            errors.add("key", new ActionMessage("errors.exists", key));
    }
    
    if(defaultValue==null || defaultValue.trim().length()==0)
        errors.add("defaultValue", new ActionMessage("errors.required", ""));
    
    if(allowedValues==null || allowedValues.trim().length()==0)
        errors.add("allowedValues", new ActionMessage("errors.required", ""));
    
    if(description==null || description.trim().length()==0)
        errors.add("description", new ActionMessage("errors.required", ""));
    
    return errors;
}
 
Example 9
/**
 * Removes profile from system with all its data using Dao
 *
 * @param aForm a form
 */
public void removeProfile(ImportProfileForm aForm, HttpServletRequest req, ActionMessages errors) {
    ImportProfile importProfile = importProfileService.getImportProfileById(aForm.getProfileId());
    
    if (importProfile != null) {
    	List<AutoImportLight> autoImportsList = autoImportService == null ? null : autoImportService.getListAutoImportsByProfileId(importProfile.getId());
    	if (autoImportsList != null && autoImportsList.size() > 0) {
    		AutoImportLight autoImport = autoImportsList.get(0);
    		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.profileStillUsed", autoImport.getShortname() + " (ID: " + autoImport.getAutoImportId() + ")"));
    	} else {
      importProfileService.deleteImportProfileById(aForm.getProfileId());
		
      writeUserActivityLog(AgnUtils.getAdmin(req), "delete import profile", getImportProfileDescription(importProfile));
    	}
    }
}
 
Example 10
Source Project: jivejdon   Source File: AccountFaceFileForm.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check to make sure the client hasn't exceeded the maximum allowed upload
 * size inside of this validate method.
 */
public void doValidate(ActionMapping mapping, HttpServletRequest request, List errors) {

	// has the maximum length been exceeded?
	Boolean maxLengthExceeded = (Boolean) request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
	if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {

		errors.add("exceed the upload max length");

	} else if (theFile != null) {
		// retrieve the file name
		String fileName = theFile.getFileName();
		if (!uploadHelper.canBeUpload(fileName))
			errors.add(new ActionMessage("illegal file type! "));
	}

}
 
Example 11
Source Project: unitime   Source File: SessionRollForward.java    License: Apache License 2.0 6 votes vote down vote up
public void rollLearningManagementSystemInfoForward(ActionMessages errors, RollForwardSessionForm rollForwardSessionForm) {
	Session toSession = Session.getSessionById(rollForwardSessionForm.getSessionToRollForwardTo());
	Session fromSession = Session.getSessionById(rollForwardSessionForm.getSessionToRollDatePatternsForwardFrom());
	List<LearningManagementSystemInfo> fromLearningManagementSystems = LearningManagementSystemInfo.findAll(fromSession.getUniqueId());
	LearningManagementSystemInfo fromLms = null;
	LearningManagementSystemInfo toLms = null;
	LearningManagementSystemInfoDAO lmsDao = new LearningManagementSystemInfoDAO();
	try {
		for(Iterator it = fromLearningManagementSystems.iterator(); it.hasNext();){
			fromLms = (LearningManagementSystemInfo) it.next();
			if (fromLms != null){
				toLms = (LearningManagementSystemInfo) fromLms.clone();
				toLms.setSession(toSession);
				lmsDao.saveOrUpdate(toLms);
				lmsDao.getSession().flush();
			}
		}
		
		lmsDao.getSession().flush();
		lmsDao.getSession().clear();
	} catch (Exception e) {
		iLog.error("Failed to roll all learning management system infos forward.", e);
		errors.add("rollForward", new ActionMessage("errors.rollForward", "Learning Management System Info", fromSession.getLabel(), toSession.getLabel(), "Failed to roll all learning management system infos forward."));
	}		
}
 
Example 12
private boolean isValidActions(EmmActionForm form, ActionMessages errors){
	List<AbstractActionOperationParameters> list =  form.getActions();
	
	if (list != null) {
 	for ( Object action : list) {
 		if (action instanceof ActionOperationExecuteScriptParameters) {
 			ActionOperationExecuteScriptParameters scriptAction = (ActionOperationExecuteScriptParameters) action;
                try {
                    this.velocityDirectiveScriptValidator.validateScript(scriptAction.getScript());
                } catch(ScriptValidationException e) {
                    String directive = ((IllegalVelocityDirectiveException) e).getDirective();
                    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "error.action.illegal_directive", directive));
                }
            }
 	}

 	if(isInvalidBcc(list)){
 	    errors.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.action.invalid.bbc"));
        }
	}

	return errors.isEmpty();
}
 
Example 13
/**
 * Stores uploaded csv file to temporary directory and the location is
 * store to session. So the file can be used later.
 *
 * @param request request
 * @param csvFile uploaded csv file
 * @return errors that happened
 * @throws IOException 
 * @throws FileNotFoundException 
 */
private ActionErrors storeCsvFile(HttpServletRequest request, FormFile csvFile) throws Exception {
    ActionErrors errors = new ActionErrors();
    HttpSession session = request.getSession();
    String savePath = generateSavePath(session);
    File file = new File(savePath);
    try (InputStream inputStream = csvFile.getInputStream()) {
     try (FileOutputStream outputStream = new FileOutputStream(file, false)) {
         IOUtils.copy(inputStream, outputStream);
         removeStoredCsvFile(request);
         session.setAttribute(CSV_FILE_PATH_KEY, savePath);
         session.setAttribute(CSV_ORIGINAL_FILE_NAME_KEY, csvFile.getFileName());
         fileUploadPerformed = true;
     } catch (IOException e) {
         errors.add("csvFile", new ActionMessage("error.import.cannotOpenFile", e.getMessage()));
         return errors;
     } finally {
     	IOUtils.closeQuietly(inputStream);
     }
    }
    return errors;
}
 
Example 14
Source Project: uyuni   Source File: UserEditActionHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void validatePassword(ActionErrors errors, String pw) {
    // Validate the password
    if (pw.length() < UserDefaults.get().getMinPasswordLength()) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.minpassword",
                        UserDefaults.get().getMinPasswordLength()));
    }
    if (Pattern.compile("[\\t\\n]").matcher(pw).find()) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.invalidpasswordcharacters"));
    }
    if (pw.length() > UserDefaults.get().getMaxPasswordLength()) {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.maxpassword",
                                UserDefaults.get().getMaxPasswordLength()));
    }
}
 
Example 15
public ActionForward prepareEditProgram(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final ExecutionCourse executionCourse = (ExecutionCourse) request.getAttribute("executionCourse");

    final Teacher teacher = getUserView(request).getPerson().getTeacher();
    if (teacher.isResponsibleFor(executionCourse) == null) {
        ActionMessages messages = new ActionMessages();
        messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.teacherNotResponsibleOrNotCoordinator"));
        saveErrors(request, messages);
        return forward(request, "/teacher/executionCourse/program.jsp");
    }

    final String curriculumIDString = request.getParameter("curriculumID");
    if (executionCourse != null && curriculumIDString != null && curriculumIDString.length() > 0) {
        final Curriculum curriculum = findCurriculum(executionCourse, curriculumIDString);
        if (curriculum != null) {
            final DynaActionForm dynaActionForm = (DynaActionForm) form;
            dynaActionForm.set("program", curriculum.getProgram());
            dynaActionForm.set("programEn", curriculum.getProgramEn());
        }
        request.setAttribute("curriculum", curriculum);
    }
    return forward(request, "/teacher/executionCourse/editProgram.jsp");
}
 
Example 16
/**
 * Resechedules the action whose id is found in the aid formvar.
 * @param mapping actionmapping
 * @param formIn form containing input
 * @param request HTTP request
 * @param response HTTP response
 * @return the confirmation page.
 */
public ActionForward rescheduleActions(ActionMapping mapping,
                             ActionForm formIn,
                             HttpServletRequest request,
                             HttpServletResponse response) {

    RequestContext requestContext = new RequestContext(request);

    Long aid = requestContext.getParamAsLong("aid");
    Action action = ActionManager.lookupAction(requestContext.getCurrentUser(),
                                               aid);
    updateSet(request);
    ActionManager.rescheduleAction(action, true);

    ActionMessages msgs = new ActionMessages();

    msgs.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.actionrescheduled",
                    action.getActionType().getName()));
    getStrutsDelegate().saveMessages(request, msgs);

    return getStrutsDelegate().forwardParam(
            mapping.findForward("scheduled"), "aid", String.valueOf(aid));
}
 
Example 17
private final void checkAndCorrectFormData(final SupervisorGrantLoginPermissionForm loginPermissionForm, final ActionMessages errors) {
	// Correct data
	if(loginPermissionForm.getDepartmentID() < 0 && !OneOf.oneIntOf(loginPermissionForm.getDepartmentID(), ALL_DEPARTMENTS_ID)) {
		if(logger.isInfoEnabled()) {
			logger.info(String.format("Received invalid department ID %d. Changed it to 0", loginPermissionForm.getDepartmentID()));
		}
		
		loginPermissionForm.setDepartmentID(0);
	}
	
	// Check data
	if(loginPermissionForm.getDepartmentID() == 0) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.settings.supervisor.noDepartmentSelected"));
	}
	
	if(!OneOf.oneObjectOf(loginPermissionForm.getLimit(), "LIMITED", "UNLIMITED")) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.settings.supervisor.noLoginLimitSelected"));
	}
	
	if(LIMITED_LOGIN_PERMISSION.equals(loginPermissionForm.getLimit()) && StringUtils.isEmpty(loginPermissionForm.getExpireDateLocalized()) ) {
		errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.settings.supervisor.noExpireDate"));
	}
}
 
Example 18
protected ActionForward modalDeliveryInfo(HttpServletRequest request, ActionMapping mapping, ComRecipientForm form, ActionMessages errors) {
    final ComAdmin admin = AgnUtils.getAdmin(request);
    final int companyID = admin.getCompanyID();
    try {
        final JSONArray deliveriesInfo = deliveryService.getDeliveriesInfo(companyID, form.getMailingId(), form.getRecipientID());

        request.setAttribute("mailingName", form.getMailingName());
        request.setAttribute("deliveriesInfo", deliveriesInfo);
        request.setAttribute("dateTimeFormatPattern", admin.getDateTimeFormat().toPattern());
        return mapping.findForward("mailing_delivery_info");
    } catch (Exception e) {
        logger.error("Could not load data to open deliveries info modal. Company Id: " + companyID + ".  Exception: ", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Error"));
        return mapping.findForward("messages");
    }
}
 
Example 19
protected void addToMessage(ActionMessages msg,
                            String methodName,
                            boolean success,
                            Object[] args) {

    String key = getSetDecl().getLabel();
    if (!DEFAULT_CALLBACK.equals(methodName)) {
        key = getSetDecl().getLabel() + "." + methodName;
    }

    if (success) {
        key += ".success";
    }
    else {
        key += ".failure";
    }
    ActionMessage temp =  new ActionMessage(key, args);
    msg.add(ActionMessages.GLOBAL_MESSAGE, temp);

}
 
Example 20
Source Project: uyuni   Source File: DeleteSlaveAction.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Long deleteSlave(ActionMapping mapping, DynaActionForm dynaForm,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    RequestContext requestContext = new RequestContext(request);
    Long sid = requestContext.getParamAsLong(IssSlave.SID);

    boolean isNew = (IssSlave.NEW_SLAVE_ID == sid);

    IssSlave slave = null;
    if (!isNew) {
        slave = IssFactory.lookupSlaveById(sid);
        IssFactory.remove(slave);
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "message.iss_slave_removed", slave.getSlave()));
        getStrutsDelegate().saveMessages(request, msg);
    }
    return sid;
}
 
Example 21
public ActionForward createMessage(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws FenixServiceException {

    CreateConversationMessageBean createConversationMessageBean =
            (CreateConversationMessageBean) RenderUtils.getViewState("createMessage").getMetaObject().getObject();

    try {
        CreateConversationMessage.runCreateConversationMessage(createConversationMessageBean);
    } catch (DomainException e) {
        ActionMessages actionMessages = new ActionMessages();
        actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getKey()));

        saveMessages(request, actionMessages);

        return prepareCreateMessage(mapping, actionForm, request, response);
    }

    return viewThreadOnPage(mapping, actionForm, request, response,
            computeNumberOfPages(DEFAULT_PAGE_SIZE, getRequestedThread(request).getMessageSet().size()));
}
 
Example 22
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 23
Source Project: unitime   Source File: RoomListForm.java    License: Apache License 2.0 5 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
  
    if(deptCode==null || deptCode.equalsIgnoreCase("")) {
    	errors.add("deptCode", 
                new ActionMessage("errors.required", "Department") );
    }
   
    return errors;
}
 
Example 24
/**
 * prepare form for "list" destination
 */
protected void processListDestination(ActionForward destination, CampaignForm form, HttpServletRequest req, ActionMessages errors) {
    if (destination != null && "list".equals(destination.getName())) {
        try {
            FormUtils.syncNumberOfRows(webStorage, WebStorage.ARCHIVE_OVERVIEW, form);

            req.setAttribute("campaignlist", getCampaignList(req));
        } catch (Exception e) {
            logger.error("getCampaignList: "+e, e);
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.exception", configService.getValue(ConfigValue.SupportEmergencyUrl)));
        }
    }
}
 
Example 25
private void makeMessage(Action action, HttpServletRequest request) {
    if (action != null) {
        //get how many servers this action was created for.
        int successes = action.getServerActions().size();
        String number = LocalizationService.getInstance()
                .formatNumber(new Integer(successes));

        //build the url for the action we have created.
        String url = "/rhn/schedule/ActionDetails.do?aid=" + action.getId();

        //create the success message
        ActionMessages msg = new ActionMessages();
        String key;
        if (successes == 1) {
            key = "configdiff.schedule.success.singular";
        }
        else {
            key = "configdiff.schedule.success";
        }

        Object[] args = new Object[2];
        args[0] = StringEscapeUtils.escapeHtml(url);
        args[1] = StringEscapeUtils.escapeHtml(number);

        //add in the success message
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(key, args));
        getStrutsDelegate().saveMessages(request, msg);
    }
    else {
        //Something went wrong, tell user!
        ActionErrors errors = new ActionErrors();
        getStrutsDelegate().addError("configdiff.schedule.selection_error",
                errors);
        getStrutsDelegate().saveMessages(request, errors);
    }
}
 
Example 26
Source Project: unitime   Source File: DataImportForm.java    License: Apache License 2.0 5 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
	ActionErrors errors = new ActionErrors();
	
       if ("Import".equals(iOp) && (iFile == null || iFile.getFileSize()<=0)) {
       	errors.add("name", new ActionMessage("errors.required", "File") );
       }
       
       if ("Export".equals(iOp) && getExportType() == null) {
       	errors.add("export", new ActionMessage("errors.generic", "Nothing to export") );
       }
       
       return errors;
}
 
Example 27
Source Project: uyuni   Source File: OrgDeleteAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @param oidIn Organization Id to delete
 * @return Success or Failure in form of Boolean
 */
private void deleteOrg(Long oidIn, HttpServletRequest request) {
    Org org = OrgFactory.lookupById(oidIn);
    String name = org.getName();
    RequestContext requestContext = new RequestContext(request);

    OrgFactory.deleteOrgAndDependencies(oidIn, requestContext.getCurrentUser());
    ActionMessages msg = new ActionMessages();
    msg.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.org_deleted",
            StringEscapeUtils.escapeHtml4(name)));
    getStrutsDelegate().saveMessages(request, msg);
}
 
Example 28
Source Project: unitime   Source File: RollForwardSessionForm.java    License: Apache License 2.0 5 votes vote down vote up
public void validateTeachingRequestsRollForward(Session toAcadSession, ActionErrors errors){
	if (getRollForwardTeachingRequests().booleanValue()) {
		if (getRollForwardOfferingCoordinatorsSubjectIds() == null || getRollForwardOfferingCoordinatorsSubjectIds().length == 0) {
			errors.add("mustSelectDepartment", new ActionMessage("errors.rollForward.generic", "Teaching Requests", "No subject area selected."));
		} else {
			validateRollForward(errors, toAcadSession, getSessionToRollInstructorDataForwardFrom(), "Teaching Requests",
				TeachingRequestDAO.getInstance().getQuery("select tr from TeachingRequest tr inner join tr.offering.courseOfferings co where co.isControl = true and co.subjectArea.uniqueId in :subjectIds")
				.setParameterList("subjectIds", getRollForwardOfferingCoordinatorsSubjectIds(), new StringType()).list());
		}
	}
}
 
Example 29
/**
 * Archives the actions.
 * @param mapping ActionMapping
 * @param formIn ActionForm
 * @param request ServletRequest
 * @param response ServletResponse
 * @return The ActionForward to go to next.
 */
public ActionForward archiveAction(ActionMapping mapping,
                                   ActionForm formIn,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {

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

    User user = requestContext.getCurrentUser();
    //Update the set first and get the size so we know
    //how many actions we have archived.
    RhnSet set = getSetDecl().get(user);

    //Archive the actions
    ActionManager.archiveActions(user, getSetDecl().getLabel());


    ActionMessages msgs = new ActionMessages();
    /**
     * If there was only one action archived, display the "action" archived
     * message, else display the "actions" archived message.
     */
    if (set.size() == 1) {
        msgs.add(ActionMessages.GLOBAL_MESSAGE,
                 new ActionMessage("message.actionArchived",
                         LocalizationService.getInstance()
                                            .formatNumber(new Integer(set.size()))));
    }
    else {
        msgs.add(ActionMessages.GLOBAL_MESSAGE,
                 new ActionMessage("message.actionsArchived",
                         LocalizationService.getInstance()
                                            .formatNumber(new Integer(set.size()))));
    }
    strutsDelegate.saveMessages(request, msgs);

    return mapping.findForward("archive");
}
 
Example 30
private void addIntMessage(int number, String key, ActionMessages msgs) {
    if (number > 0) {
        if (number == 1) {
            key = key + ".singular";
        }
        ActionMessage message = new ActionMessage(key, String.valueOf(number));
        msgs.add(ActionMessages.GLOBAL_MESSAGE, message);
    }
}