Java Code Examples for org.apache.wicket.validation.IValidator

The following examples show how to use org.apache.wicket.validation.IValidator. 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
Source Project: onedev   Source File: FormComponent.java    License: MIT License 6 votes vote down vote up
/**
 * Adds a validator to this form component
 * 
 * @param validator
 *            validator to be added
 * @return <code>this</code> for chaining
 * @throws IllegalArgumentException
 *             if validator is null
 * @see IValidator
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public final FormComponent<T> add(final IValidator<? super T> validator)
{
	Args.notNull(validator, "validator");

	if (validator instanceof Behavior)
	{
		add((Behavior)validator);
	}
	else
	{
		add((Behavior)new ValidatorAdapter(validator));
	}
	return this;
}
 
Example 2
Source Project: onedev   Source File: FormComponent.java    License: MIT License 6 votes vote down vote up
/**
 * Gets an unmodifiable list of validators for this FormComponent.
 * 
 * @return List of validators
 */
@SuppressWarnings("unchecked")
public final List<IValidator<? super T>> getValidators()
{
	final List<IValidator<? super T>> list = new ArrayList<>();

	for (Behavior behavior : getBehaviors())
	{
		if (behavior instanceof IValidator)
		{
			list.add((IValidator<? super T>)behavior);
		}
	}

	return Collections.unmodifiableList(list);
}
 
Example 3
Source Project: the-app   Source File: RegistrationPage.java    License: Apache License 2.0 6 votes vote down vote up
private Component usernameField() {
    TextField<String> username = new TextField<>("username", new PropertyModel<>(userInfoModel, "username"));
    username.add(new IValidator<String>() {
        private static final long serialVersionUID = 5670647976176255775L;

        @Override
        public void validate(IValidatable<String> userNameValidatable) {
            UserInfo userInfo = userService.findByUsername(userNameValidatable.getValue());
            if (userInfo != null) {
                error("The entered username is already in use.");
            }
        }
    });
    username.setRequired(true);
    return username;
}
 
Example 4
Source Project: yes-cart   Source File: ContactPage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct contact information page.
 * @param params page parameters.
 */
public ContactPage(final PageParameters params) {
    super(params);
    add(new StandardFooter(FOOTER));
    add(new StandardHeader(HEADER));
    add(new ServerSideJs("serverSideJs"));
    add(new HeaderMetaInclude("headerInclude"));
    final AttrValueWithAttribute emailConfig = customerServiceFacade.getShopEmailAttribute(getCurrentShop());
    final IValidator<String> emailValidator;
    if (emailConfig != null && StringUtils.isNotBlank(emailConfig.getAttribute().getRegexp())) {
        final String regexError = new FailoverStringI18NModel(
                emailConfig.getAttribute().getValidationFailedMessage(),
                emailConfig.getAttribute().getCode()).getValue(getLocale().getLanguage());

        emailValidator = new CustomPatternValidator(emailConfig.getAttribute().getRegexp(), new Model<>(regexError));
    } else {
        emailValidator = EmailAddressValidator.getInstance();
    }
    add(new ContactForm("contactForm",emailValidator));
    add(new FeedbackPanel("feedback"));
}
 
Example 5
Source Project: yes-cart   Source File: LoginPanel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct login panel.
 *
 * @param id panel id
 * @param isCheckout is we are on checkout
 */
public LoginPanel(final String id, final boolean isCheckout) {
    super(id);
    this.isCheckout = isCheckout;

    final Pair<Class<? extends Page>, PageParameters> target = determineRedirectTarget(this.isCheckout);
    final AttrValueWithAttribute emailConfig = customerServiceFacade.getShopEmailAttribute(getCurrentShop());
    final IValidator<String> emailValidator;
    if (emailConfig != null && StringUtils.isNotBlank(emailConfig.getAttribute().getRegexp())) {
        final String regexError = new FailoverStringI18NModel(
                emailConfig.getAttribute().getValidationFailedMessage(),
                emailConfig.getAttribute().getCode()).getValue(getLocale().getLanguage());

        emailValidator = new CustomPatternValidator(emailConfig.getAttribute().getRegexp(), new Model<>(regexError));
    } else {
        emailValidator = EmailAddressValidator.getInstance();
    }
    add(new LoginForm(LOGIN_FORM, target.getFirst(), target.getSecond(), emailValidator));

}
 
Example 6
Source Project: yes-cart   Source File: NewsletterPanel.java    License: Apache License 2.0 6 votes vote down vote up
public NewsletterPanel(final String id) {
    super(id);

    final AttrValueWithAttribute emailConfig = customerServiceFacade.getShopEmailAttribute(getCurrentShop());
    final IValidator<String> emailValidator;
    if (emailConfig != null && StringUtils.isNotBlank(emailConfig.getAttribute().getRegexp())) {
        final String regexError = new FailoverStringI18NModel(
                emailConfig.getAttribute().getValidationFailedMessage(),
                emailConfig.getAttribute().getCode()).getValue(getLocale().getLanguage());

        emailValidator = new CustomPatternValidator(emailConfig.getAttribute().getRegexp(), new Model<>(regexError));
    } else {
        emailValidator = EmailAddressValidator.getInstance();
    }
    add(new SingUpForm(SIGNUP_FORM, emailValidator));
}
 
Example 7
Source Project: AppStash   Source File: RegistrationPage.java    License: Apache License 2.0 6 votes vote down vote up
private Component usernameField() {
    TextField<String> username = new TextField<>("username", new PropertyModel<>(userInfoModel, "username"));
    username.add(new IValidator<String>() {
        private static final long serialVersionUID = 5670647976176255775L;

        @Override
        public void validate(IValidatable<String> userNameValidatable) {
            UserInfo userInfo = userService.findByUsername(userNameValidatable.getValue());
            if (userInfo != null) {
                error("The entered username is already in use.");
            }
        }
    });
    username.setRequired(true);
    return username;
}
 
Example 8
Source Project: onedev   Source File: FormComponent.java    License: MIT License 5 votes vote down vote up
/**
 * Removes a validator from the form component.
 * 
 * @param validator
 *            validator
 * @throws IllegalArgumentException
 *             if validator is null or not found
 * @see IValidator
 * @see #add(IValidator)
 * @return form component for chaining
 */
public final FormComponent<T> remove(final IValidator<? super T> validator)
{
	Args.notNull(validator, "validator");
	Behavior match = null;
	for (Behavior behavior : getBehaviors())
	{
		if (behavior.equals(validator))
		{
			match = behavior;
			break;
		}
		else if (behavior instanceof ValidatorAdapter)
		{
			if (((ValidatorAdapter<?>)behavior).getValidator().equals(validator))
			{
				match = behavior;
				break;
			}
		}
	}

	if (match != null)
	{
		remove(match);
	}
	else
	{
		throw new IllegalStateException(
			"Tried to remove validator that was not previously added. "
				+ "Make sure your validator's equals() implementation is sufficient");
	}
	return this;
}
 
Example 9
Source Project: onedev   Source File: FormComponent.java    License: MIT License 5 votes vote down vote up
/**
 * Adds a validator to this form component.
 * 
 * @param validators
 *            The validator(s) to be added
 * @return This
 * @throws IllegalArgumentException
 *             if validator is null
 * @see IValidator
 */
@SafeVarargs
public final FormComponent<T> add(final IValidator<? super T>... validators)
{
	Args.notNull(validators, "validators");

	for (IValidator<? super T> validator : validators)
	{
		add(validator);
	}

	// return this for chaining
	return this;
}
 
Example 10
Source Project: openmeetings   Source File: Captcha.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	add(captchaText.setLabel(new ResourceModel("captcha.text")).add(new IValidator<String>() {
		private static final long serialVersionUID = 1L;

		@Override
		public void validate(IValidatable<String> validatable) {
			if (!randomText.equals(validatable.getValue())) {
				validatable.error(new ValidationError(getString("bad.captcha.text")));
			}
		}
	}).setOutputMarkupId(true));
	add(new BootstrapAjaxLink<>("refresh", Model.of(""), Buttons.Type.Outline_Info, new ResourceModel("lbl.refresh")) {
		private static final long serialVersionUID = 1L;

		@Override
		public void onClick(AjaxRequestTarget target) {
			captchaImageResource.invalidate();
			target.add(captcha);
		}

		@Override
		protected Icon newIcon(String markupId) {
			return new Icon(markupId, FontAwesome5IconType.sync_s);
		}
	});
}
 
Example 11
@Test
public void testNotNull() {
	IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "a");
	
	Validatable<Object> validatable = new Validatable<Object>(null);
	validator.validate(validatable);
	
	assertEquals(1, validatable.getErrors().size());
	assertEquals("NotNull", getError(validatable).getKeys().get(0));
}
 
Example 12
@Test
public void testSuccess(){
	IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "a");
	
	Validatable<Object> validatable = new Validatable<Object>("bb");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());
}
 
Example 13
@Test
public void testMessageParameters(){
	IValidator<Object> validator = new HibernateValidatorProperty(new Model<TestBean>(new TestBean("aaa", "aaa")), "b");
	
	Validatable<Object> validatable = new Validatable<Object>("a");
	validator.validate(validatable);
	
	assertEquals(1, validatable.getErrors().size());
	assertEquals("Size", getError(validatable).getKeys().get(0));
	
	assertEquals(2, getError(validatable).getVariables().size());
	assertEquals(2, getError(validatable).getVariables().get("min"));
	assertEquals(4, getError(validatable).getVariables().get("max"));
}
 
Example 14
@Test
public void testValidNifUsual() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("123456789");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());
}
 
Example 15
@Test
public void testValidNif0term() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("504426290");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());
}
 
Example 16
@Test
public void testValidNif0TermWithMod1() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("504646680");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());
}
 
Example 17
@Test
public void testInvalidNif() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("124456789");
	validator.validate(validatable);
	
	assertEquals(1, validatable.getErrors().size());
}
 
Example 18
@Test
public void testAnotherInvalidNif() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("505646780");
	validator.validate(validatable);
	
	assertEquals(1, validatable.getErrors().size());
}
 
Example 19
@SuppressWarnings("serial")
protected static DropDownChoice<Integer> createCost2ChoiceRenderer(final String id, final TimesheetDao timesheetDao,
    final TaskTree taskTree, final LabelValueChoiceRenderer<Integer> kost2ChoiceRenderer, final TimesheetDO data,
    final List<Kost2DO> kost2List)
    {
  final DropDownChoice<Integer> choice = new DropDownChoice<Integer>(id, new Model<Integer>() {
    @Override
    public Integer getObject()
    {
      return data.getKost2Id();
    }

    @Override
    public void setObject(final Integer kost2Id)
    {
      if (kost2Id != null) {
        timesheetDao.setKost2(data, kost2Id);
      } else {
        data.setKost2(null);
      }
    }
  }, kost2ChoiceRenderer.getValues(), kost2ChoiceRenderer);
  choice.setNullValid(true);
  choice.add(new IValidator<Integer>() {
    @Override
    public void validate(final IValidatable<Integer> validatable)
    {
      final Integer value = validatable.getValue();
      if (value != null && value >= 0) {
        return;
      }
      if (CollectionUtils.isNotEmpty(kost2List) == true) {
        // Kost2 available but not selected.
        choice.error(PFUserContext.getLocalizedString("timesheet.error.kost2Required"));
      }
    }
  });
  return choice;
    }
 
Example 20
Source Project: onedev   Source File: FormComponent.java    License: MIT License 4 votes vote down vote up
/**
 * Validates this component using the component's validators.
 */
@SuppressWarnings("unchecked")
protected final void validateValidators()
{
	final IValidatable<T> validatable = newValidatable();

	boolean isNull = getConvertedInput() == null;

	IValidator<T> validator;

	for (Behavior behavior : getBehaviors())
	{
		if (isBehaviorAccepted(behavior) == false)
		{
			continue;
		}

		validator = null;
		if (behavior instanceof ValidatorAdapter)
		{
			validator = ((ValidatorAdapter<T>)behavior).getValidator();
		}
		else if (behavior instanceof IValidator)
		{
			validator = (IValidator<T>)behavior;
		}
		if (validator != null)
		{
			if (isNull == false || validator instanceof INullAcceptingValidator<?>)
			{
				try
				{
					validator.validate(validatable);
				}
				catch (Exception e)
				{
					throw new WicketRuntimeException("Exception '" + e.getMessage() +
							"' occurred during validation " + validator.getClass().getName() +
							" on component " + getPath(), e);
				}
			}
			if (!isValid())
			{
				break;
			}
		}
	}
}
 
Example 21
Source Project: yes-cart   Source File: ContactPage.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Construct form.
 *
 * @param id             form id.
 */
public ContactForm(final String id, final IValidator<String> emailValidator) {

    super(id);

    setModel(new CompoundPropertyModel<>(ContactForm.this));


    add(
            new TextField<String>("email")
                    .setRequired(true)
                    .add(emailValidator)
    );

    add(
            new TextField<String>("name")
                    .setRequired(true)
    );

    add(
            new TextField<String>("subject")
                    .setRequired(true)
    );

    add(
            new TextField<String>("phone")
                    .setRequired(true)
                    .add(StringValidator.lengthBetween(4, 13))
    );

    add(
            new TextArea<String>("message")
                    .setRequired(true)
    );


    add(
            new Button("sendBtn") {


                @Override
                public void onSubmit() {

                    final Map<String, Object> data = new HashMap<>();
                    data.put("name", getName());
                    data.put("phone", getPhone());
                    data.put("email", getEmail());
                    data.put("subject", getSubject());
                    data.put("body", getMessage());

                    getCustomerServiceFacade().registerEmailRequest(
                            getCurrentShop(), email, data);

                    info(
                            getLocalizer().getString("emailSend", this)
                    );

                    setEmail(null);
                    setPhone(null);
                    setName(null);
                    setSubject(null);
                    setMessage(null);

                }
            }
    );

}
 
Example 22
Source Project: openmeetings   Source File: UserWebService.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Adds a new User like through the Frontend, but also does activates the
 * Account To do SSO see the methods to create a hash and use those ones!
 *
 * @param sid
 *            The SID from getSession
 * @param user
 *            user object
 * @param confirm
 *            whatever or not to send email, leave empty for auto-send
 *
 * @return - id of the user added or error code
 */
@WebMethod
@POST
@Path("/")
public UserDTO add(
		@WebParam(name="sid") @QueryParam("sid") String sid
		, @WebParam(name="user") @FormParam("user") UserDTO user
		, @WebParam(name="confirm") @FormParam("confirm") Boolean confirm
		)
{
	return performCall(sid, User.Right.SOAP, sd -> {
		if (!isAllowRegisterSoap()) {
			throw new ServiceException("Soap register is denied in Settings");
		}
		User testUser = userDao.getExternalUser(user.getExternalId(), user.getExternalType());

		if (testUser != null) {
			throw new ServiceException("User does already exist!");
		}

		String tz = user.getTimeZoneId();
		if (Strings.isEmpty(tz)) {
			tz = getDefaultTimezone();
		}
		if (user.getAddress() == null) {
			user.setAddress(new Address());
			user.getAddress().setCountry(Locale.getDefault().getCountry());
		}
		if (user.getLanguageId() == null) {
			user.setLanguageId(1L);
		}
		User jsonUser = user.get(userDao, groupDao);
		IValidator<String> passValidator = new StrongPasswordValidator(true, jsonUser);
		Validatable<String> passVal = new Validatable<>(user.getPassword());
		passValidator.validate(passVal);
		if (!passVal.isValid()) {
			StringBuilder sb = new StringBuilder();
			for (IValidationError err : passVal.getErrors()) {
				sb.append(((ValidationError)err).getMessage()).append(System.lineSeparator());
			}
			log.debug("addNewUser::weak password '{}', msg: {}", user.getPassword(), sb);
			throw new ServiceException(sb.toString());
		}
		Object ouser;
		try {
			jsonUser.addGroup(groupDao.get(getDefaultGroup()));
			ouser = userManager.registerUser(jsonUser, user.getPassword(), null);
		} catch (NoSuchAlgorithmException | OmException e) {
			throw new ServiceException("Unexpected error while creating user");
		}

		if (ouser == null) {
			throw new ServiceException(UNKNOWN.getMessage());
		} else if (ouser instanceof String) {
			throw new ServiceException((String)ouser);
		}

		User u = (User)ouser;

		u.getRights().add(Right.ROOM);
		if (Strings.isEmpty(user.getExternalId()) && Strings.isEmpty(user.getExternalType())) {
			// activate the User
			u.getRights().add(Right.LOGIN);
			u.getRights().add(Right.DASHBOARD);
		}

		u = userDao.update(u, sd.getUserId());

		return new UserDTO(u);
	});
}
 
Example 23
Source Project: openmeetings   Source File: Admin.java    License: Apache License 2.0 4 votes vote down vote up
private void checkAdminDetails() throws Exception {
	cfg.setUsername(cmdl.getOptionValue("user"));
	cfg.setEmail(cmdl.getOptionValue(OPTION_EMAIL));
	cfg.setGroup(cmdl.getOptionValue(OPTION_GROUP));
	if (cfg.getUsername() == null || cfg.getUsername().length() < USER_LOGIN_MINIMUM_LENGTH) {
		doLog("User login was not provided, or too short, should be at least " + USER_LOGIN_MINIMUM_LENGTH + " character long.");
		throw new ExitException();
	}

	if (!MailUtil.isValid(cfg.getEmail())) {
		doLog(String.format("Please provide non-empty valid email: '%s' is not valid.", cfg.getEmail()));
		throw new ExitException();
	}
	if (Strings.isEmpty(cfg.getGroup())) {
		doLog(String.format("User group was not provided, or too short, should be at least 1 character long: %s", cfg.getGroup()));
		throw new ExitException();
	}
	if (cmdl.hasOption(OPTION_PWD)) {
		cfg.setPassword(cmdl.getOptionValue(OPTION_PWD));
	}
	IValidator<String> passValidator = new StrongPasswordValidator(false, new User());
	Validatable<String> passVal;
	do {
		passVal = new Validatable<>(cfg.getPassword());
		passValidator.validate(passVal);
		if (!passVal.isValid()) {
			doLog(String.format("Please enter password for the user '%s':", cfg.getUsername()));
			cfg.setPassword(new BufferedReader(new InputStreamReader(System.in, UTF_8)).readLine());
		}
	} while (!passVal.isValid());
	Map<String, String> tzMap = ImportHelper.getAllTimeZones(TimeZone.getAvailableIDs());
	cfg.setTimeZone(null);
	if (cmdl.hasOption("tz")) {
		String tz = cmdl.getOptionValue("tz");
		cfg.setTimeZone(tzMap.containsKey(tz) ? tz : null);
	}
	if (cfg.getTimeZone() == null) {
		doLog("Please enter timezone, Possible timezones are:");

		for (Map.Entry<String,String> me : tzMap.entrySet()) {
			doLog(String.format("%1$-25s%2$s", "\"" + me.getKey() + "\"", me.getValue()));
		}
		throw new ExitException();
	}
}
 
Example 24
Source Project: syncope   Source File: AjaxTextFieldPanel.java    License: Apache License 2.0 4 votes vote down vote up
public void addValidator(final IValidator<? super String> validator) {
    this.field.add(validator);
}
 
Example 25
Source Project: syncope   Source File: AjaxCharacterFieldPanel.java    License: Apache License 2.0 4 votes vote down vote up
public void addValidator(final IValidator<? super Character> validator) {
    this.field.add(validator);
}
 
Example 26
Source Project: syncope   Source File: AjaxSearchFieldPanel.java    License: Apache License 2.0 4 votes vote down vote up
public void addValidator(final IValidator<String> validator) {
    this.field.add(validator);
}
 
Example 27
/**
 * @param id
 * @param label Only for displaying the field's name on validation messages.
 * @param model
 * @param settings with target type etc.
 */
@SuppressWarnings("serial")
public DatePanel(final String id, final IModel<Date> model, final DatePanelSettings settings)
{
  super(id, model);
  setType(settings.targetType);
  final MyDateConverter dateConverter = new MyDateConverter(settings.targetType, "M-");
  dateField = new DateTextField("dateField", new PropertyModel<Date>(this, "date"), dateConverter) {
    /**
     * @see org.apache.wicket.Component#renderHead(org.apache.wicket.markup.head.IHeaderResponse)
     */
    @Override
    public void renderHead(final IHeaderResponse response)
    {
      super.renderHead(response);
      WicketRenderHeadUtils.renderMainJavaScriptIncludes(response);
      DatePickerUtils.renderHead(response, getLocale(), dateField.getMarkupId(), autosubmit);
    }
  };
  dateField.add(AttributeModifier.replace("size", "10"));
  dateField.setOutputMarkupId(true);
  add(dateField);
  if (settings.required == true) {
    this.required = true;
  }
  if (settings.tabIndex != null) {
    dateField.add(AttributeModifier.replace("tabindex", String.valueOf(settings.tabIndex)));
  }
  dateField.add(new IValidator<Date>() {

    @Override
    public void validate(final IValidatable<Date> validatable)
    {
      final Date date = validatable.getValue();
      if (date != null) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        final int year = cal.get(Calendar.YEAR);
        if (year < minYear || year > maxYear) {
          validatable.error(new ValidationError().addKey("error.date.yearOutOfRange").setVariable("minimumYear", minYear)
              .setVariable("maximumYear", maxYear));
        }
      }
    }
  });
}
 
Example 28
Source Project: yes-cart   Source File: NewsletterPanel.java    License: Apache License 2.0 3 votes vote down vote up
public SingUpForm(final String id,
                  final IValidator<String> emailValidator) {
    super(id);

    setModel(new CompoundPropertyModel<>(SingUpForm.this));

    final TextField<String> emailInput = (TextField<String>) new TextField<String>(EMAIL_INPUT)
            .setRequired(true)
            .add(emailValidator);

    add(
            emailInput
    );

    add(
            new Button(SIGNUP_BUTTON) {

                @Override
                public void onSubmit() {

                    if (!SingUpForm.this.hasError()) {
                        customerServiceFacade.registerNewsletter(getCurrentShop(), getEmail(), new HashMap<>());

                        final PageParameters params = new PageParameters(getPage().getPageParameters());
                        params.add("signupok", Boolean.TRUE);

                        setResponsePage(getPage().getPageClass(), params);
                    }

                }

            }
    );

    add(new Label(CONTENT, ""));

}
 
Example 29
@Test
public void testValidNif() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("241250609");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());

}
 
Example 30
@Test
public void testValidDoubleDigit() {
	IValidator<String> validator = new PortugueseNIFValidator();
	
	Validatable<String> validatable = new Validatable<String>("451234561");
	validator.validate(validatable);
	
	assertEquals(0, validatable.getErrors().size());

}