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

The following examples show how to use org.apache.struts.action.ActionErrors#add() . 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: SpecialUseRoomForm.java    From unitime with 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 (deptSize != 1) {
		if (deptCode== null || deptCode.equals("")) {
			errors.add("dept",
					new ActionMessage("errors.required", "Department"));
		}
	}

       if(bldgId==null || bldgId.equalsIgnoreCase("")) {
       	errors.add("bldg", 
                   new ActionMessage("errors.required", "Building") );
       }
       
       if(roomNum==null || roomNum.equalsIgnoreCase("")) {
       	errors.add("roomNum", 
                   new ActionMessage("errors.required", "Room Number") );
       }
       
       return errors;
       
}
 
Example 2
Source File: SolverInfoDefForm.java    From unitime with Apache License 2.0 6 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

		ActionErrors errors = new ActionErrors();
        
        if(name==null || name.trim().length()==0)
            errors.add("name", new ActionMessage("errors.required", ""));
        else {
        	if ("Add New".equals(op)) {
        		SolverInfoDef info = SolverInfoDef.findByName(name);
        		if (info!=null)
        			errors.add("name", new ActionMessage("errors.exists", name));
        	}
        }
        
        if(description==null || description.trim().length()==0)
            errors.add("description", new ActionMessage("errors.required", ""));
        
        if(implementation==null || implementation.trim().length()==0)
            errors.add("implementation", new ActionMessage("errors.required", ""));

        return errors;
	}
 
Example 3
Source File: ManageLessonDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward prepareCreate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    DynaActionForm manageLessonForm = (DynaActionForm) form;

    InfoShift infoShift = (InfoShift) request.getAttribute(PresentationConstants.SHIFT);
    Shift shift = FenixFramework.getDomainObject(infoShift.getExternalId());
    GenericPair<YearMonthDay, YearMonthDay> maxLessonsPeriod = shift.getExecutionCourse().getMaxLessonsPeriod();

    if (maxLessonsPeriod != null) {
        request.setAttribute("executionDegreeLessonsStartDate", maxLessonsPeriod.getLeft().toString("dd/MM/yyyy"));
        request.setAttribute("executionDegreeLessonsEndDate", maxLessonsPeriod.getRight().toString("dd/MM/yyyy"));
        manageLessonForm.set("newBeginDate", maxLessonsPeriod.getLeft().toString("dd/MM/yyyy"));
        manageLessonForm.set("newEndDate", maxLessonsPeriod.getRight().toString("dd/MM/yyyy"));
        manageLessonForm.set("createLessonInstances", Boolean.TRUE);

    } else {
        ActionErrors actionErrors = new ActionErrors();
        actionErrors.add("error.executionDegree.empty.lessonsPeriod", new ActionError(
                "error.executionDegree.empty.lessonsPeriod"));
        saveErrors(request, actionErrors);
        return mapping.findForward("EditShift");
    }

    return mapping.findForward("ShowLessonForm");
}
 
Example 4
Source File: ExamSolverForm.java    From unitime with Apache License 2.0 6 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
       ActionErrors errors = new ActionErrors();

       if(iSetting==null || iSetting.intValue()<0)
           errors.add("setting", new ActionMessage("errors.lookup.config.required", ""));
       
       for (Iterator i=iParamValues.entrySet().iterator();i.hasNext();) {
       	Map.Entry entry = (Map.Entry)i.next();
        	Long parm = (Long)entry.getKey();
       	String val = (String)entry.getValue();
       	if (val==null || val.trim().length()==0)
       		errors.add("parameterValue["+parm+"]", new ActionMessage("errors.required", ""));
       }
       
       return errors;
}
 
Example 5
Source File: RhnValidationHelper.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Converts an array of Strings into a set of ActionError messages
 *
 * @param errors Array of ValidatorErrors you want to convert
 * @return ActionErrors object with set of messages
 */
public static ActionErrors validatorErrorToActionErrors(
        ValidatorError... errors) {
    ActionErrors messages = new ActionErrors();

    for (int i = 0; i < errors.length; i++) {
        messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                errors[i].getKey(), errors[i].getValues()));
    }
    return messages;
}
 
Example 6
Source File: InstructorSearchForm.java    From unitime with Apache License 2.0 5 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
  
    if(deptUniqueId==null || deptUniqueId.equalsIgnoreCase("")) {
    	errors.add("deptUniqueId", 
                new ActionMessage("errors.generic", MSG.errorRequiredDepartment()) );
    }
   
    return errors;
}
 
Example 7
Source File: SystemsController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
protected void createErrorMessage(HttpServletRequest req, String beanKey,
                                  String param) {
    ActionErrors errs = new ActionErrors();
    String escParam = StringEscapeUtils.escapeHtml4(param);
    errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(beanKey, escParam));
    StrutsDelegate.getInstance().saveMessages(req, errs);
}
 
Example 8
Source File: ForgotCredentialsAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
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 = setupEmailBody("email.forgotten.logins",
                email, logins.toString(), ConfigDefaults.get().getHostname());
        sendEmail(email, LocalizationService.getInstance().
                getMessage("help.credentials.jsp.logininfo"), 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 9
Source File: RhnAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add an error message to the request with argument array
 * @param req to add the message to
 * @param beanKey resource key to lookup
 * @param args String array to fill in for the message parameters
 */
protected void createErrorMessageWithMultipleArgs(HttpServletRequest req,
        String beanKey, String[] args) {
    ActionErrors errs = new ActionErrors();
    String[] escArgs = new String[args.length];
    for (int i = 0; i < args.length; i++) {
        escArgs[i] = StringEscapeUtils.escapeHtml(args[i]);
    }
    errs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(beanKey, escArgs));
    saveMessages(req, errs);
}
 
Example 10
Source File: ComAdminForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 11
Source File: RollForwardSessionForm.java    From unitime with 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 12
Source File: SystemRemoteCommandAction.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate form has required fields.
 *
 * @param form
 * @param errorMessages
 * @return
 */
private boolean validate(DynaActionForm form,
                        ActionErrors errorMessages) {
    boolean formValid = true;
    for (String fid : SystemRemoteCommandAction.FormData.MANDATORY_FIELDS) {
        if (StringUtil.nullOrValue(form.getString(fid)) == null) {
            if (formValid) {
                formValid = false;
            }
            errorMessages.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage(String.format(
                            "ssm.operations.provisioning." +
                            "remotecommand.form.%s.missing", fid)));
        }
    }

    // Check if Script looks legit :-)
    if (StringUtil.nullOrValue(form.getString(FormData.SCRIPT)) != null) {
        ScriptCheckResult checkResult = StringUtil.scriptPrematureCheck(
                form.getString(FormData.SCRIPT));
        if (checkResult != null) {
            formValid = false;
            errorMessages.add(ActionMessages.GLOBAL_MESSAGE,
                              new ActionMessage(checkResult.getMessageKey()));
        }
    }

    // Check if timeout exceeds the XMLRPC integer type max
    if ((Long) form.get(FormData.TIMEOUT) > FormData.MAX_TIMEOUT) {
      formValid = false;
      errorMessages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage(String.format(
                             "ssm.operations.provisioning.remotecommand." +
                             "form.timeout.max")));
    }

    return formValid;
}
 
Example 13
Source File: ImportFileSubmitAction.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate all the written paths.  Add all of the chosen paths
 * to an RhnSet and forward to the confirm page.
 * @param mapping struts ActionMapping
 * @param formIn struts ActionForm
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return an ActionForward to the confirm page. To the same page
 *         if errors are found.
 */
public ActionForward importFile(ActionMapping mapping,
                                ActionForm formIn,
                                HttpServletRequest request,
                                HttpServletResponse response) {
    Map params = makeParamMap(formIn, request);

    //read the file names from the textbox and add them to the import set
    //return to the same page if there are any validation errors.
    if (readTextBox(formIn, request)) {
        return getStrutsDelegate().forwardParams(
                mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
    }

    //read the selected file names from the form and add them to the import
    //set.  Find out how many we have selected
    int totalFiles = importSelected(request);

    //go to the confirm page.
    if (totalFiles > 0) {
        return getStrutsDelegate().forwardParams(
                mapping.findForward("success"), params);
    }
    ActionErrors errors = new ActionErrors();
    errors.add(ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("sdcimportfile.jsp.noSelected"));
    addErrors(request, errors);
    return getStrutsDelegate().forwardParams(
            mapping.findForward(RhnHelper.DEFAULT_FORWARD), params);
}
 
Example 14
Source File: ExamSolverLogForm.java    From unitime with Apache License 2.0 5 votes vote down vote up
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
       ActionErrors errors = new ActionErrors();

       if(iLevel==null || iLevel.trim().length()==0)
           errors.add("level", new ActionMessage("errors.required", ""));
       
       return errors;
}
 
Example 15
Source File: ExportWizardForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private void validateDate(String startDate, String endDate, String pattern, ActionErrors errors) {
    if (!StringUtils.isEmpty(startDate) && !AgnUtils.isDateValid(startDate, pattern)) {
        errors.add("global", new ActionMessage("error.date.format"));
    } else if (!StringUtils.isEmpty(endDate) && !AgnUtils.isDateValid(endDate, pattern)) {
        errors.add("global", new ActionMessage("error.date.format"));
    } else if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate) && !AgnUtils.isDatePeriodValid(startDate, endDate, pattern)) {
        errors.add("global", new ActionMessage("error.period.format"));
    }
}
 
Example 16
Source File: XccdfDiffSubmitAction.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping,
                              ActionForm formIn,
                              HttpServletRequest request,
                              HttpServletResponse response) {
    RequestContext context = new RequestContext(request);
    DynaActionForm form = (DynaActionForm) formIn;
    ActionErrors errors = RhnValidationHelper.validateDynaActionForm(this, form);
    if (!errors.isEmpty()) {
        getStrutsDelegate().saveMessages(request, errors);
        return getStrutsDelegate().forwardParams(
                mapping.findForward("error"), request.getParameterMap());
    }

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

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

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

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

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

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

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

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

    String email = user.getEmail();
    String newEmail = (String)form.get("email");

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

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

    //If it got this far, something went wrong
    addErrors(request, errors);
    return strutsDelegate.forwardParam(mapping.findForward("failure"),
            "uid", user.getId().toString());
}
 
Example 18
Source File: CreateUserAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
private ActionErrors populateCommand(DynaActionForm form, CreateUserCommand command) {
    ActionErrors errors = new ActionErrors();

    command.setEmail(form.getString("email"));
    command.setLogin(form.getString("login"));
    command.setPrefix(form.getString("prefix"));
    command.setFirstNames(form.getString("firstNames"));
    command.setLastName(form.getString("lastName"));

    //Should this user use pam authentication?
    if (form.get("usepam") != null && ((Boolean)form.get("usepam")).booleanValue()) {
        command.setUsePamAuthentication(true);
    }
    else {
        command.setUsePamAuthentication(false);
    }

    // Put any validationErrors into ActionErrors object
    ValidatorError[] validationErrors = command.validate();
    for (int i = 0; i < validationErrors.length; i++) {
        ValidatorError err = validationErrors[i];
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                   new ActionMessage(err.getKey(), err.getValues()));
    }

    Address addr = UserFactory.createAddress();
    fillOutAddress(form, addr);
    command.setAddress(addr);

    // Check passwords
    String passwd = (String)form.get(UserActionHelper.DESIRED_PASS);
    String passwdConfirm = (String)form.get(UserActionHelper.DESIRED_PASS_CONFIRM);

    if (passwd.equals(passwdConfirm)) {
        command.setPassword(passwd);
    }
    else {
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                   new ActionMessage("error.password_mismatch"));
    }

    return errors;
}
 
Example 19
Source File: ScheduleKickstartWizardAction.java    From spacewalk with GNU General Public License v2.0 4 votes vote down vote up
protected boolean validateBondSelections(DynaActionForm form,
        RequestContext ctx) {
    if (!StringUtils.isBlank(form.getString(HIDDEN_BOND_SLAVE_INTERFACES))) {
        form.set(BOND_SLAVE_INTERFACES,
                form.getString(HIDDEN_BOND_SLAVE_INTERFACES).split(","));
    }

    String[] slaves = (String[]) form.get(BOND_SLAVE_INTERFACES);
    ActionErrors errors = new ActionErrors();

    // if we are trying to create a bond but have not specified a name or at
    // least one slave interface
    if (form.getString(BOND_TYPE).equals(CREATE_BOND_VALUE) &&
            (StringUtils.isBlank(form.getString(BOND_INTERFACE)) ||
                    slaves.length < 1 || StringUtils.isBlank(slaves[0]))) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "kickstart.bond.not.defined.jsp"));
    }

    final String ipv4addressPattern = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    /*
     * The IPv6 address regex was created by Stephen Ryan at Dartware
     * and taken from this forum: http://forums.intermapper.com/viewtopic.php?t=452
     * It is licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported
     * License. We can freely use it in (even in commercial products) as long as
     * we attribute its creation to him, so don't remove this message.
     */
    final String ipv6addressPattern = "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-" +
            "F]{1,4}::?){0,5}|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$))" +
            "{0,2}|((25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1," +
            "4}:[0-9A-F]{1,4})(?<![^:]:|\\.)\\z";

    if (form.getString(BOND_STATIC).equals(STATIC_BOND_VALUE)) {
        String address = form.getString(BOND_IP_ADDRESS);
        String netmask = form.getString(BOND_NETMASK);
        String gateway = form.getString(BOND_GATEWAY);

        if (!address.matches(ipv4addressPattern) &&
                !address.matches(ipv6addressPattern)) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "kickstart.bond.bad.ip.address.jsp"));
        }

        if (!netmask.matches(ipv4addressPattern) &&
                !netmask.matches(ipv6addressPattern)) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "kickstart.bond.bad.netmask.jsp"));
        }

        if (!gateway.matches(ipv4addressPattern) &&
                !gateway.matches(ipv6addressPattern)) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "kickstart.bond.bad.ip.address.jsp"));
        }
    }

    if (errors.size() > 0) {
        addErrors(ctx.getRequest(), errors);
        return false;
    }
    return true;
}
 
Example 20
Source File: DistributionPrefsForm.java    From unitime with Apache License 2.0 4 votes vote down vote up
/** 
 * Method validate
 * @param mapping
 * @param request
 * @return ActionErrors
 */
public ActionErrors validate(
    ActionMapping mapping,
    HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();

    // Distribution Type must be selected
    if(distType==null || distType.equals(Preference.BLANK_PREF_VALUE)) {
     errors.add("distType", 
             new ActionMessage(
                     "errors.generic", MSG.errorSelectDistributionType()) );
    }
    
    /*
    // Distribution Type must be selected
    if(grouping==null || grouping.equals(Preference.BLANK_PREF_VALUE)) {
     errors.add("grouping", 
             new ActionMessage(
                     "errors.generic", "Select a structure. ") );
    }
    */

    // Distribution Pref Level must be selected
    if(prefLevel==null || prefLevel.equals(Preference.BLANK_PREF_VALUE)) {
     errors.add("prefLevel", 
             new ActionMessage(
                     "errors.generic", 
                     MSG.errorSelectDistributionPreferenceLevel()) );
    }
    
    // Check duplicate / blank selections
    if(!checkClasses()) {
     errors.add("classes", 
             new ActionMessage(
                     "errors.generic", 
                     MSG.errorInvalidClassSelectionDP()) );
    }
    
    // Save/Update clicked
    if(op.equals(MSG.accessSaveNewDistributionPreference())
            || op.equals(MSG.accessUpdateDistributionPreference()) ) {
        
        // At least one row of subpart should exist
        if(subjectArea.size()==0)
	        errors.add("classes", 
	                new ActionMessage(
	                        "errors.generic", 
	                        MSG.errorInvalidClassSelectionDPSubpart()) );

        // At least 2 rows should exist if one is a class
        if(subjectArea.size()==1 && !classNumber.get(0).toString().equals(ALL_CLASSES_SELECT))
	        errors.add("classes", 
	                new ActionMessage(
	                        "errors.generic", 
	                        MSG.errorInvalidClassSelectionDPMinTwoClasses()) );
        
        // Class cannot be specified if its subpart is already specified
        if(subjectArea.size()>1) {
            HashMap mapSubparts = new HashMap();
            HashMap mapClasses = new HashMap();
            for (int i=0; i<subjectArea.size(); i++) {
                String subpart = itype.get(i).toString();
                String classNum = classNumber.get(i).toString();
                if(classNum.equals(ALL_CLASSES_SELECT)) {
                    if(mapClasses.get(subpart)!=null) {
            	        errors.add("classes", 
            	                new ActionMessage(
            	                        "errors.generic", 
            	                        MSG.errorInvalidClassSelectionDPIndividualClass()) );
            	        break;
                    }
                    else 
                        mapSubparts.put(subpart, classNum);
                }
                else {
                    if(mapSubparts.get(subpart)!=null) {
            	        errors.add("classes", 
            	                new ActionMessage(
            	                        "errors.generic", 
            	                        MSG.errorInvalidClassSelectionDPIndividualClass()) );
            	        break;
                    }
                    else 
                        mapClasses.put(subpart, classNum);
                }
            }
        }
    }

    return errors;
}