Example usage for org.apache.wicket.markup.html.form.validation EqualInputValidator EqualInputValidator

List of usage examples for org.apache.wicket.markup.html.form.validation EqualInputValidator EqualInputValidator

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.form.validation EqualInputValidator EqualInputValidator.

Prototype

public EqualInputValidator(FormComponent<?> formComponent1, FormComponent<?> formComponent2) 

Source Link

Document

Construct.

Usage

From source file:dk.teachus.frontend.components.person.PersonPanel.java

License:Apache License

public PersonPanel(String id, final PersonModel<? extends Person> personModel) {
    super(id, personModel);

    if (allowUserEditing(TeachUsSession.get().getPerson(), personModel.getObject()) == false) {
        throw new RestartResponseAtInterceptPageException(Application.get().getHomePage());
    }/* ww w  .j  a v a 2  s  . c o m*/

    FormPanel formPanel = new FormPanel("form"); //$NON-NLS-1$
    add(formPanel);

    // Name
    StringTextFieldElement nameField = new StringTextFieldElement(
            TeachUsSession.get().getString("General.name"), new PropertyModel<String>(personModel, "name"), //$NON-NLS-1$//$NON-NLS-2$
            true, 32);
    nameField.add(StringValidator.lengthBetween(2, 100));
    formPanel.addElement(nameField);

    // Email
    StringTextFieldElement emailField = new StringTextFieldElement(
            TeachUsSession.get().getString("General.email"), new PropertyModel<String>(personModel, "email"), //$NON-NLS-1$//$NON-NLS-2$
            true, 50);
    emailField.add(EmailAddressValidator.getInstance());
    formPanel.addElement(emailField);

    // Phone number
    formPanel.addElement(new IntegerFieldElement(TeachUsSession.get().getString("General.phoneNumber"), //$NON-NLS-1$
            new PropertyModel<Integer>(personModel, "phoneNumber"), 10)); //$NON-NLS-1$

    // Username
    if (isUsernameEnabled()) {
        StringTextFieldElement usernameField = new StringTextFieldElement(
                TeachUsSession.get().getString("General.username"), //$NON-NLS-1$
                new PropertyModel<String>(personModel, "username"), true); //$NON-NLS-1$
        usernameField.add(StringValidator.lengthBetween(3, 50));

        // Validate the username for correct content
        usernameField.add(new PatternValidator("^[a-zA-Z0-9-_]+$") { //$NON-NLS-1$
            private static final long serialVersionUID = 1L;

            @Override
            public void error(IValidatable<String> validatable) {
                ValidationError validationError = new ValidationError();
                validationError.setMessage(TeachUsSession.get().getString("PersonPanel.usernameCharacters"));
                validatable.error(validationError); //$NON-NLS-1$
            }
        });

        // validate the username checking for dublicates
        usernameField.add(new IValidator<String>() {
            private static final long serialVersionUID = 1L;

            public void validate(IValidatable<String> validatable) {
                PersonDAO personDAO = TeachUsApplication.get().getPersonDAO();
                String username = validatable.getValue();

                Person existingPerson = personDAO.usernameExists(username);

                if (existingPerson != null
                        && existingPerson.getId().equals(personModel.getPersonId()) == false) {
                    String localeString = TeachUsSession.get().getString("PersonPanel.userAlreadyExists"); //$NON-NLS-1$
                    localeString = localeString.replace("${username}", username); //$NON-NLS-1$
                    ValidationError validationError = new ValidationError();
                    validationError.setMessage(localeString);
                    validatable.error(validationError);
                }
            }
        });
        formPanel.addElement(usernameField);
    } else {
        formPanel.addElement(new ReadOnlyElement(TeachUsSession.get().getString("General.username"), //$NON-NLS-1$
                new PropertyModel<Object>(personModel, "username"))); //$NON-NLS-1$
    }

    // Password 1
    if (isPasswordVisible()) {
        final PasswordFieldElement password1Field = new PasswordFieldElement(
                TeachUsSession.get().getString("General.password"), //$NON-NLS-1$
                new PropertyModel<String>(this, "password1"), personModel.getPersonId() == null); //$NON-NLS-1$
        password1Field.add(StringValidator.lengthBetween(4, 32));
        formPanel.addElement(password1Field);

        // Password 2
        final PasswordFieldElement password2Field = new PasswordFieldElement(
                TeachUsSession.get().getString("PersonPanel.repeatPassword"), //$NON-NLS-1$
                new PropertyModel<String>(this, "password2")); //$NON-NLS-1$
        formPanel.addElement(password2Field);

        // Password validator
        formPanel.addValidator(new FormValidator() {
            private static final long serialVersionUID = 1L;

            public IFormValidator getFormValidator() {
                return new EqualInputValidator(password1Field.getFormComponent(),
                        password2Field.getFormComponent());
            }
        });
    }

    // Locale
    if (isLocaleVisible()) {
        List<Locale> availableLocales = TeachUsApplication.get().getAvailableLocales();
        formPanel.addElement(new DropDownElement<Locale>(TeachUsSession.get().getString("General.locale"), //$NON-NLS-1$
                new PropertyModel<Locale>(personModel, "locale"), availableLocales, //$NON-NLS-1$
                new LocaleChoiceRenderer()));
    }

    if (isCurrencyVisible()) {
        StringTextFieldElement currencyField = new StringTextFieldElement(
                TeachUsSession.get().getString("General.currency"), //$NON-NLS-1$
                new PropertyModel<String>(personModel, "currency"), 4); //$NON-NLS-1$
        currencyField.add(StringValidator.lengthBetween(0, 10));
        formPanel.addElement(currencyField); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Theme
    if (isThemeVisible()) {
        List<Theme> themes = Arrays.asList(Theme.values());
        formPanel.addElement(new DropDownElement<Theme>(TeachUsSession.get().getString("General.theme"), //$NON-NLS-1$
                new PropertyModel<Theme>(personModel, "theme"), themes, new ThemeChoiceRenderer())); //$NON-NLS-1$
    }

    // Teacher
    if (isTeacherVisible()) {
        formPanel.addElement(new ReadOnlyElement(TeachUsSession.get().getString("General.teacher"), //$NON-NLS-1$
                new PropertyModel<Object>(personModel, "teacher.name"))); //$NON-NLS-1$
    }

    // iCalendar URL
    formPanel.addElement(
            new ReadOnlyElement(TeachUsSession.get().getString("Ical.label"), new IcalUrlModel(personModel)));

    // Additional elements
    appendElements(formPanel);

    // Notes
    if (isNotesVisible()) {
        formPanel.addElement(new TextAreaElement("Notes", new PropertyModel<String>(personModel, "notes")));
    }

    // Buttons
    formPanel.addElement(new ButtonPanelElement() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onCancel() {
            getRequestCycle().setResponsePage(getPersonsPageClass());
        }

        @Override
        protected void onSave(AjaxRequestTarget target) {
            if (Strings.isEmpty(password1) == false) {
                personModel.setPassword(password1);
            }

            personModel.save();

            PersonPanel.this.onSave(personModel.getObject());

            getRequestCycle().setResponsePage(getPersonsPageClass());
        }
    });
}

From source file:dk.teachus.frontend.pages.messages.SendNewPasswordPage.java

License:Apache License

public SendNewPasswordPage(Long pupilId) {
    super(UserLevel.TEACHER, true);

    if (pupilId == null) {
        throw new IllegalArgumentException("Must provide a valid pupilId"); //$NON-NLS-1$
    }/* www  .  j ava 2s.  co m*/

    final PupilModel pupilModel = new PupilModel(pupilId);

    // Find intro message from teachers attributes
    WelcomeIntroductionTeacherAttribute welcomeIntroduction = TeachUsSession.get()
            .getTeacherAttribute(WelcomeIntroductionTeacherAttribute.class);
    if (welcomeIntroduction != null) {
        setIntroMessage(welcomeIntroduction.getValue());
    }

    String title = TeachUsSession.get().getString("SendNewPasswordPage.title"); //$NON-NLS-1$
    title = title.replace("{pupilname}", pupilModel.getObject().getName()); //$NON-NLS-1$
    add(new Label("newPasswordTitle", title)); //$NON-NLS-1$

    FormPanel formPanel = new FormPanel("passwordForm"); //$NON-NLS-1$
    add(formPanel);

    // Password 1
    final PasswordFieldElement password1Field = new PasswordFieldElement(
            TeachUsSession.get().getString("General.password"), new PropertyModel(this, "password1"), true); //$NON-NLS-1$ //$NON-NLS-2$
    password1Field.add(StringValidator.lengthBetween(4, 32));
    formPanel.addElement(password1Field);

    // Password 2
    final PasswordFieldElement password2Field = new PasswordFieldElement(
            TeachUsSession.get().getString("PersonPanel.repeatPassword"), new PropertyModel(this, "password2"), //$NON-NLS-1$//$NON-NLS-2$
            true);
    formPanel.addElement(password2Field);

    // Password validator
    formPanel.addValidator(new FormValidator() {
        private static final long serialVersionUID = 1L;

        public IFormValidator getFormValidator() {
            return new EqualInputValidator(password1Field.getFormComponent(),
                    password2Field.getFormComponent());
        }
    });

    // Password generator
    formPanel.addElement(new GeneratePasswordElement("", pupilModel.getObject().getUsername()) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        protected void passwordGenerated(AjaxRequestTarget target, String password) {
            setPassword1(password);
            setPassword2(password);

            target.addComponent(password1Field.getFormComponent());
            target.addComponent(password1Field.getFeedbackPanel());
            target.addComponent(password2Field.getFormComponent());
            target.addComponent(password2Field.getFeedbackPanel());
        }
    });

    // Text
    formPanel.addElement(new TextAreaElement(TeachUsSession.get().getString("SendNewPasswordPage.introMessage"), //$NON-NLS-1$
            new PropertyModel(this, "introMessage"))); //$NON-NLS-1$

    // Buttons
    formPanel.addElement(new ButtonPanelElement(TeachUsSession.get().getString("General.send")) { //$NON-NLS-1$
        private static final long serialVersionUID = 1L;

        @Override
        protected void onCancel() {
            getRequestCycle().setResponsePage(PupilsPage.class);
        }

        @Override
        protected void onSave(AjaxRequestTarget target) {
            PersonDAO personDAO = TeachUsApplication.get().getPersonDAO();
            MessageDAO messageDAO = TeachUsApplication.get().getMessageDAO();

            // Update pupil
            final Pupil pupil = pupilModel.getObject();
            pupil.setPassword(getPassword1());
            personDAO.save(pupil);

            // Create mail message
            Message message = new MailMessage();
            message.setSender(pupil.getTeacher());
            message.setRecipient(pupil);
            message.setState(MessageState.FINAL);

            String subject = TeachUsSession.get().getString("NewPasswordMail.subject"); //$NON-NLS-1$
            message.setSubject(subject);

            String body = TeachUsSession.get().getString("NewPasswordMail.body"); //$NON-NLS-1$
            body = body.replace("${username}", pupil.getUsername()); //$NON-NLS-1$
            body = body.replace("${password}", getPassword1()); //$NON-NLS-1$
            String serverUrl = TeachUsApplication.get().getServerUrl();
            body = body.replace("${server}", serverUrl); //$NON-NLS-1$
            String im = getIntroMessage();
            if (Strings.isEmpty(im) == false) {
                im += "\n\n"; //$NON-NLS-1$
            }
            body = body.replace("${introMessage}", im); //$NON-NLS-1$
            message.setBody(body);

            messageDAO.save(message);

            getRequestCycle().setResponsePage(PupilsPage.class);
        }
    });
}

From source file:org.geoserver.security.web.user.AbstractUserPage.java

License:Open Source License

protected AbstractUserPage(String ugServiceName, final GeoServerUser user) {
    this.ugServiceName = ugServiceName;

    GeoServerUserGroupService ugService = getUserGroupService(ugServiceName);
    boolean emptyPasswd = getSecurityManager()
            .loadPasswordEncoder(ugService.getPasswordEncoderName()) instanceof GeoServerEmptyPasswordEncoder;
    boolean hasUserGroupStore = ugService.canCreateStore();
    boolean hasRoleStore = hasRoleStore(getSecurityManager().getActiveRoleService().getName());

    // build the form
    Form form = new Form<Serializable>("form", new CompoundPropertyModel(user));
    add(form);/*from ww  w.ja  v a  2  s. c  o m*/

    form.add(new TextField("username").setEnabled(hasUserGroupStore));
    form.add(new CheckBox("enabled").setEnabled(hasUserGroupStore));

    PasswordTextField pw1 = new PasswordTextField("password") {
        @Override
        public boolean isRequired() {
            return isFinalSubmit(this);
        }
    };
    form.add(pw1);
    pw1.setResetPassword(false);
    pw1.setEnabled(hasUserGroupStore && !emptyPasswd);

    PasswordTextField pw2 = new PasswordTextField("confirmPassword", new Model(user.getPassword())) {
        @Override
        public boolean isRequired() {
            return isFinalSubmit(this);
        }
    };
    form.add(pw2);
    pw2.setResetPassword(false);
    pw2.setEnabled(hasUserGroupStore && !emptyPasswd);

    form.add(new PropertyEditorFormComponent("properties").setEnabled(hasUserGroupStore));

    form.add(userGroupPalette = new UserGroupPaletteFormComponent("groups", ugServiceName, user));
    userGroupPalette.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            updateCalculatedRoles(target);
        }
    });
    userGroupPalette.setEnabled(hasUserGroupStore);

    List<GeoServerRole> roles;
    try {
        roles = new ArrayList(getSecurityManager().getActiveRoleService().getRolesForUser(user.getUsername()));
    } catch (IOException e) {
        throw new WicketRuntimeException(e);
    }

    form.add(rolePalette = new RolePaletteFormComponent("roles", new ListModel(roles)));
    rolePalette.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            updateCalculatedRoles(target);
            updateGroupAdminList(target);
        }
    });
    rolePalette.setOutputMarkupId(true);
    rolePalette.setEnabled(hasRoleStore);

    boolean isGroupAdmin = roles.contains(GeoServerRole.GROUP_ADMIN_ROLE);
    List<GeoServerUserGroup> adminGroups = new ArrayList();
    if (isGroupAdmin) {
        for (String groupName : GroupAdminProperty.get(user.getProperties())) {
            try {
                adminGroups.add(ugService.getGroupByGroupname(groupName));
            } catch (IOException e) {
                throw new WicketRuntimeException(e);
            }
        }
    }

    form.add(adminGroupChoice = new UserGroupListMultipleChoice("adminGroups", new ListModel(adminGroups),
            new GroupsModel(ugServiceName)));
    adminGroupChoice.setOutputMarkupId(true);
    adminGroupChoice.setEnabled(hasUserGroupStore && isGroupAdmin);

    WebMarkupContainer container = new WebMarkupContainer("calculatedRolesContainer");
    form.add(container);
    container.setOutputMarkupId(true);

    container.add(
            calculatedRoles = new ListView<GeoServerRole>("calculatedRoles", new CalculatedRoleModel(user)) {
                @Override
                @SuppressWarnings("unchecked")
                protected void populateItem(ListItem<GeoServerRole> item) {
                    IModel<GeoServerRole> model = item.getModel();
                    item.add(new SimpleAjaxLink("role", model, RoleListProvider.ROLENAME.getModel(model)) {
                        @Override
                        protected void onClick(AjaxRequestTarget target) {
                            setResponsePage(
                                    new EditRolePage(getSecurityManager().getActiveRoleService().getName(),
                                            (GeoServerRole) getDefaultModelObject())
                                                    .setReturnPage(this.getPage()));
                        }
                    });
                }
            });
    calculatedRoles.setOutputMarkupId(true);

    form.add(new SubmitLink("save") {
        @Override
        public void onSubmit() {
            try {
                //update the user property listing the group names the user is admin for
                if (adminGroupChoice.isEnabled()) {
                    Collection<GeoServerUserGroup> groups = adminGroupChoice.getModelObject();
                    String[] groupNames = new String[groups.size()];
                    int i = 0;
                    for (GeoServerUserGroup group : groups) {
                        groupNames[i++] = group.getGroupname();
                    }

                    GroupAdminProperty.set(user.getProperties(), groupNames);
                } else {
                    GroupAdminProperty.del(user.getProperties());
                }

                onFormSubmit(user);
                setReturnPageDirtyAndReturn(true);
            } catch (Exception e) {
                handleSubmitError(e);
            }
        }
    }.setEnabled(hasUserGroupStore || hasRoleStore(getSecurityManager().getActiveRoleService().getName())));
    form.add(getCancelLink());

    // add the validators
    form.add(new EqualInputValidator(pw1, pw2) {
        private static final long serialVersionUID = 1L;

        @Override
        public void validate(Form<?> form) {
            if (isFinalSubmit(form)) {
                super.validate(form);
            }
        }

        @Override
        protected String resourceKey() {
            return "AbstractUserPage.passwordMismatch";
        }
    });
    form.add(new GroupAdminValidator());
}

From source file:org.geoserver.web.security.user.AbstractUserPage.java

License:Open Source License

protected AbstractUserPage(UserUIModel user) {
    final Model userModel = new Model(user);

    // build the form
    Form form = new Form("userForm");
    form.setModel(new CompoundPropertyModel(userModel));
    setDefaultModel(userModel);//from  ww w.j  a v a 2 s.c  o m
    add(form);

    // populate the form editing components
    username = new TextField("username");
    form.add(username);
    PasswordTextField pw1 = new PasswordTextField("password").setResetPassword(false);
    PasswordTextField pw2 = new PasswordTextField("confirmPassword").setResetPassword(false);
    form.add(pw1);
    form.add(pw2);
    form.add(new RolesFormComponent("roles", new PropertyModel(userModel, "authorities"), form, false));

    // build the submit/cancel
    form.add(new BookmarkablePageLink("cancel", UserPage.class));
    form.add(saveLink());

    // add the validators
    form.add(new EqualInputValidator(pw1, pw2));
    username.setRequired(true);
}