org.apache.struts.action.ActionMessage Java Examples
The following examples show how to use
org.apache.struts.action.ActionMessage.
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: ImportBaseFileAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 #2
Source File: PreferencesAction.java From unitime with Apache License 2.0 | 6 votes |
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 #3
Source File: RecipientAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #4
Source File: ForunsManagement.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 6 votes |
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 #5
Source File: ComImportWizardAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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
Source File: DeleteSlaveAction.java From uyuni with GNU General Public License v2.0 | 6 votes |
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 #7
Source File: DeleteErratumAction.java From spacewalk with GNU General Public License v2.0 | 6 votes |
/** * 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 #8
Source File: MailingSendAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #9
Source File: BaseSetOperateOnSelectedItemsAction.java From uyuni with GNU General Public License v2.0 | 6 votes |
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 #10
Source File: ComOptimizationAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #11
Source File: SettingsForm.java From unitime with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: ComUserSelfServiceGrantSupervisorLoginPermissionAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #13
Source File: ImportProfileAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
/** * 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 #14
Source File: ComRecipientAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #15
Source File: AccountFaceFileForm.java From jivejdon with Apache License 2.0 | 6 votes |
/** * 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 #16
Source File: SessionRollForward.java From unitime with Apache License 2.0 | 6 votes |
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 #17
Source File: SsmKSScheduleAction.java From uyuni with GNU General Public License v2.0 | 6 votes |
/** * 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 #18
Source File: EmmActionAction.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
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 #19
Source File: FailedSystemsAction.java From spacewalk with GNU General Public License v2.0 | 6 votes |
/** * 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 #20
Source File: ExecutionCourseProgramDA.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 6 votes |
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 #21
Source File: UserEditActionHelper.java From uyuni with GNU General Public License v2.0 | 6 votes |
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 #22
Source File: EditGroupAction.java From uyuni with GNU General Public License v2.0 | 5 votes |
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 File: TestUtils.java From spacewalk with GNU General Public License v2.0 | 5 votes |
/** * Check the request in the ActionHelper to validate that there is a UI * message in the session. Useful for struts actions where you want to * verify that it put something in the session. * @param ah actionhelper used in the test * @param key to the i18n resource * @return boolean if it was found or not */ public static boolean validateUIMessage(ActionHelper ah, String key) { ActionMessages mess = (ActionMessages) ah.getRequest().getSession().getAttribute(Globals.MESSAGE_KEY); if (mess == null) { return false; } ActionMessage am = (ActionMessage) mess.get().next(); String value = am.getKey(); if (StringUtils.isEmpty(value)) { return false; } return value.equals(key); }
Example #24
Source File: ForgotCredentialsAction.java From uyuni with GNU General Public License v2.0 | 5 votes |
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 #25
Source File: SystemDetailsEditAction.java From spacewalk with GNU General Public License v2.0 | 5 votes |
/** * Processes form submission and displays updated data * @param mapping Struts action mapping * @param dynaForm related form instance * @param request related request * @param response related response * @return jsp to render * @throws Exception when error occurs - this should be handled by the app * framework */ public ActionForward updateSystemDetails(ActionMapping mapping, DynaActionForm dynaForm, HttpServletRequest request, HttpServletResponse response) throws Exception { RequestContext ctx = new RequestContext(request); KickstartData ksdata = lookupKickstart(ctx, dynaForm); request.setAttribute("ksdata", ksdata); try { transferEdits(dynaForm, ksdata, ctx); ActionMessages msg = new ActionMessages(); msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "kickstart.systemdetails.update.confirm")); getStrutsDelegate().saveMessages(request, msg); Map<String, Object> params = new HashMap<String, Object>(); params.put("ksid", ctx .getRequiredParam(RequestContext.KICKSTART_ID)); return getStrutsDelegate().forwardParams( mapping.findForward("display"), params); } catch (ValidatorException ve) { RhnValidationHelper.setFailedValidation(request); getStrutsDelegate().saveMessages(request, ve.getResult()); request.setAttribute(RequestContext.KICKSTART, ksdata); return mapping.findForward("display"); } }
Example #26
Source File: FormComponentsAction.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
public ActionForward uploadArchive(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); ActionMessages actionMessages = new ActionMessages(); if (!AgnUtils.isUserLoggedIn(request)) { return mapping.findForward("logon"); } FormComponentsForm actionForm = (FormComponentsForm) form; if (!AgnUtils.allowed(request, Permission.MAILING_COMPONENTS_CHANGE)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.permissionDenied")); } else { List<String> errorneousFiles = saveComponentsFromZipArchive(actionForm, request, actionForm.isOverwriteExisting()); if (!errorneousFiles.isEmpty()) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("FilesWithError", StringUtils.join(errorneousFiles, ", "))); } else { actionMessages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("default.changes_saved")); } loadImagesData(actionForm, request); // Set overwrite default value (is reseted in form when sending actionForm.setOverwriteExisting(true); } if (!errors.isEmpty()) { saveErrors(request, errors); } if (!actionMessages.isEmpty()) { saveMessages(request, actionMessages); } loadFormData(actionForm, request); AgnUtils.setAdminDateTimeFormatPatterns(request); return mapping.findForward("list"); }
Example #27
Source File: ComAdminForm.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
/** * Validate the properties that have been set from this HTTP request, and * return an <code>ActionMessages</code> object that encapsulates any * validation errors that have been found. If no errors are found, return * <code>null</code> or an <code>ActionMessages</code> object with no * recorded error messages. * * @param mapping * The mapping used to select this instance * @param request * The servlet request we are processing * @return errors */ @Override public ActionErrors formSpecificValidate(ActionMapping mapping, HttpServletRequest request) { ActionErrors actionErrors = new ActionErrors(); boolean doNotDelete = request.getParameter("delete") == null || request.getParameter("delete").isEmpty(); if (doNotDelete && "save".equals(action)) { if (username == null || username.length() < 3) { actionErrors.add("username", new ActionMessage("error.username.tooShort")); } else if(username.length() > 180) { actionErrors.add("username", new ActionMessage("error.username.tooLong")); } if (!StringUtils.equals(password, passwordConfirm)) { actionErrors.add("password", new ActionMessage("error.password.mismatch")); } if (StringUtils.isBlank(fullname) || fullname.length() < 2) { actionErrors.add("fullname", new ActionMessage("error.name.too.short")); } else if (fullname.length() > 100) { actionErrors.add("fullname", new ActionMessage("error.username.tooLong")); } if (StringUtils.isBlank(firstname) || firstname.length() < 2) { actionErrors.add("firstname", new ActionMessage("error.name.too.short")); } else if (firstname.length() > 100) { actionErrors.add("firstname", new ActionMessage("error.username.tooLong")); } if (StringUtils.isBlank(companyName) || companyName.length() < 2) { actionErrors.add("companyName", new ActionMessage("error.company.tooShort")); } else if (companyName.length() > 100) { actionErrors.add("companyName", new ActionMessage("error.company.tooLong")); } if (GenericValidator.isBlankOrNull(this.email) || !AgnitasEmailValidator.getInstance().isValid(email)) { actionErrors.add("mailForReport", new ActionMessage("error.invalid.email")); } } return actionErrors; }
Example #28
Source File: AddPackagesConfirmAction.java From spacewalk with GNU General Public License v2.0 | 5 votes |
/** * Helper method that gets the correct success action message depending on how * many packages were successfully added to the errata. * * @param packagesAdded The number of packages added to the errata * @param advisory The advisory for the errata (displayed in the message) * @return ActionMessages object containing the correct success message. */ private ActionMessages getMessages(int packagesAdded, String advisory) { ActionMessages msgs = new ActionMessages(); if (packagesAdded < 2) { msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errata.edit.packages.add.success.singular", String.valueOf(packagesAdded), advisory)); } else { msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errata.edit.packages.add.success.plural", String.valueOf(packagesAdded), advisory)); } return msgs; }
Example #29
Source File: PackageIndexAction.java From uyuni with GNU General Public License v2.0 | 5 votes |
/** * Schedule a package profile refresh * @param mapping ActionMapping * @param formIn ActionForm * @param request ServletRequest * @param response ServletResponse * @return The ActionForward to go to next. */ public ActionForward update(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) { RequestContext requestContext = new RequestContext(request); User user = requestContext.getCurrentUser(); Long sid = requestContext.getRequiredParam("sid"); Server server = SystemManager.lookupByIdAndUser(sid, user); try { PackageAction pa = ActionManager.schedulePackageRefresh(user, server); ActionMessages msg = new ActionMessages(); Object[] args = new Object[3]; args[0] = pa.getId().toString(); args[1] = sid.toString(); args[2] = StringUtil.htmlifyText(server.getName()); msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.packagerefresh", args)); getStrutsDelegate().saveMessages(request, msg); SdcHelper.ssmCheck(request, sid, user); } catch (TaskomaticApiException e) { log.error("Could not schedule package refresh action:"); log.error(e); ActionErrors errors = new ActionErrors(); getStrutsDelegate().addError("taskscheduler.down", errors); getStrutsDelegate().saveMessages(request, errors); } request.setAttribute("system", server); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); }
Example #30
Source File: TargetSystemsConfirmAction.java From uyuni with GNU General Public License v2.0 | 5 votes |
private void scheduleSubscribeChannels(DynaActionForm form, User user, List<Server> servers, Channel channel, HttpServletRequest request) throws TaskomaticApiException { if (channel.isBaseChannel()) { LOG.error("Subscribing to base channel not allowed"); getStrutsDelegate().saveMessage("base.channel.subscribe.not.allowed", request); return; } Date scheduleDate = getStrutsDelegate().readDatePicker( form, "date", DatePicker.YEAR_RANGE_POSITIVE); ActionChain actionChain = ActionChainHelper.readActionChain(form, user); for (Server server : servers) { Set<Channel> childChannels = new HashSet<>(); childChannels.addAll(server.getChildChannels()); childChannels.add(channel); ActionChainManager.scheduleSubscribeChannelsAction(user, singleton(server.getId()), Optional.ofNullable(server.getBaseChannel()), !channel.isBaseChannel() ? childChannels : emptySet(), scheduleDate, actionChain); } ActionMessages msgs = new ActionMessages(); if (actionChain == null && servers.size() > 0) { msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("channels.subscribe.target.systems.channel.scheduled", servers.size(), channel.getName())); getStrutsDelegate().saveMessages(request, msgs); } else { msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.addedtoactionchain", actionChain.getId(), StringUtil.htmlifyText(actionChain.getLabel()))); getStrutsDelegate().saveMessages(request, msgs); } }