org.apache.wicket.validation.ValidationError Java Examples

The following examples show how to use org.apache.wicket.validation.ValidationError. 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: RecommenderEditorPanel.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    Recommender currentRecommender = recommender.getObject();
    Optional<Recommender> recommenderWithNewName = recommendationService
            .getRecommender(project.getObject(), newName);
    // Either there should be no recommender with the new name already existing or it should
    // be the recommender we are currently editing (i.e. the name has not changed)
    if (
            recommenderWithNewName.isPresent() &&
            !Objects.equals(recommenderWithNewName.get().getId(),
                    currentRecommender.getId())
    ) {
        aValidatable.error(new ValidationError(
                "Another recommender with the same name exists. Please try a different name"));
    }
}
 
Example #2
Source File: StrongPasswordValidator.java    From openmeetings with Apache License 2.0 6 votes vote down vote up
private void error(IValidatable<String> pass, String key, Map<String, Object> params) {
	if (web) {
		ValidationError err = new ValidationError().addKey(key);
		if (params != null) {
			err.setVariables(params);
		}
		pass.error(err);
	} else {
		String msg = LabelDao.getString(key, 1L);
		if (params != null && !params.isEmpty() && !Strings.isEmpty(msg)) {
			for (Map.Entry<String, Object> e : params.entrySet()) {
				msg = msg.replace(String.format("${%s}", e.getKey()), "" + e.getValue());
			}
		}
		log.warn(msg);
		pass.error(new ValidationError(msg));
	}
}
 
Example #3
Source File: HibernateValidatorProperty.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validate(IValidatable<Object> validatable) {
	Validator validator = HibernateValidatorProperty.validatorFactory.getValidator();
	
	@SuppressWarnings("unchecked")
	Set<ConstraintViolation<Object>> violations = validator.validateValue((Class<Object>)beanModel.getObject().getClass(), propertyName, validatable.getValue());
	
	if(!violations.isEmpty()){
		for(ConstraintViolation<?> violation : violations){
			ValidationError error = new ValidationError(violation.getMessage());
			
			String key = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
			if(getValidatorPrefix()!=null) key = getValidatorPrefix()+"."+key;
			
			error.addKey(key);
			error.setVariables(new HashMap<String, Object>(violation.getConstraintDescriptor().getAttributes()));
			
			//remove garbage from the attributes
			error.getVariables().remove("payload");
			error.getVariables().remove("message");
			error.getVariables().remove("groups");
			
			validatable.error(error);
		}
	}
}
 
Example #4
Source File: ManageUsersPage.java    From webanno with Apache License 2.0 6 votes vote down vote up
private void validateRoles(IValidatable<Collection<Role>> aValidatable)
{
    Collection<Role> newRoles = aValidatable.getValue();
    if (newRoles.isEmpty()) {
        aValidatable.error(new ValidationError()
                .setMessage("A user has to have at least one role."));
    }
    // enforce users to have at least the ROLE_USER role
    if (!newRoles.contains(Role.ROLE_USER)) {
        aValidatable.error(new ValidationError()
                .setMessage("Every user must have 'ROLE_USER'."));
    }
    // don't let an admin user strip himself of admin rights
    if (userRepository.getCurrentUser().equals(getModelObject())
            && !newRoles.contains(Role.ROLE_ADMIN)) {
        aValidatable.error(new ValidationError()
                .setMessage("You cannot remove your own admin status."));
    }
}
 
Example #5
Source File: GeneralSettingsPanel.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String kbName = aValidatable.getValue();
    if (kbService.knowledgeBaseExists(projectModel.getObject(), kbName)) {
        String message = String.format(
                "There already exists a knowledge base in the project with name: [%s]!",
                kbName);
        aValidatable.error(new ValidationError(message));
    }
}
 
Example #6
Source File: AnalysisNameValidator.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	String value = validatable.getValue();
	if (value.contains(" ")) {			
		ValidationError error = new ValidationError();   
		String errorM = errorMessage;
		if (errorM == null) {
			errorM = "' ' not allowed in name";
		}
           error.setMessage(errorM);
           validatable.error(error);
	} else {
		super.validate(validatable);
	}
}
 
Example #7
Source File: FoundEntityValidator.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	String value = validatable.getValue();
	String path = StorageUtil.createPath(parentPath, value);		
	if (storageService.entityExists(path)) {			
		ValidationError error = new ValidationError();
		String message = String.format(errorMessage, value);
		error.setMessage(message);
		validatable.error(error);
	}
}
 
Example #8
Source File: IntervalFieldStringValidator.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
 public void validate(IValidatable<String> validatable) {
     boolean hasError = false;
     String s = validatable.getValue();
     String[] elements = s.split(",");
     if (elements.length > 1) {
         List<String> nonDuplicatesList = new ArrayList<String>(new LinkedHashSet<String>(Arrays.asList(elements)));
         if (elements.length != nonDuplicatesList.size()) {
             // have duplicates
         	hasError = true;
         }
     } else {
         elements = s.split("-");
         if (elements.length == 2) {
             if (SelectIntervalPanel.getComparator(entityType, false).compare(elements[0], elements[1]) >= 0) {
             	hasError = true;
             }
         }
     }
     
     if (hasError) {
ValidationError error = new ValidationError();
String messageKey = Classes.simpleName(IntervalFieldStringValidator.class);
error.addKey(messageKey);
validatable.error(error);
     }
 }
 
Example #9
Source File: PhoneNumberValidator.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onValidate(final IValidatable<String> validatable)
{
  if (StringHelper.checkPhoneNumberFormat(validatable.getValue()) == false) {
    validatable.error(new ValidationError().addMessageKey("address.error.phone.invalidFormat"));
  }
}
 
Example #10
Source File: UserEmailValidator.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
    String email = validatable.getValue();
    if (OrienteerUserRepository.isUserExistsWithEmail(email)) {
        ValidationError error = new ValidationError(this);
        error.setVariable("email", email);
        validatable.error(error);
    }
}
 
Example #11
Source File: OPropertyValueValidator.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
protected ValidationError newValidationError(String variation,
		Object... params) {
	ValidationError error = new ValidationError(this, variation);
	error.setVariable("property", getProperty().getFullName());
	error.setVariable("type", getProperty().getType());
	for (int i = 0; i < params.length; i += 2) {
		error.setVariable(params[i].toString(), params[i + 1]);
	}
	return error;
}
 
Example #12
Source File: DateFormatValidator.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	String pattern = validatable.getValue();
	try {
		newDateFormat(pattern).format(new Date());
	} catch (Exception e) {
		ValidationError error = new ValidationError(this);
		error.setVariable("pattern", pattern);
		validatable.error(decorate(error, validatable));
	}
}
 
Example #13
Source File: PortugueseNIFValidator.java    From pm-wicket-utils with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	super.validate(validatable);
	
	final String value = validatable.getValue();
	
	if(value==null || value.length()==0) return;
	
	try {
		if(!isNIFValid(value)) validatable.error(new ValidationError(this));
	} catch(NumberFormatException e){
		validatable.error(new ValidationError(this));
	}
}
 
Example #14
Source File: UsernameTextField.java    From wicket-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable) {
	final String field = validatable.getValue();
	if(service.usernameExists(field)){
		ValidationError error = new ValidationError();
		error.setMessage(getString(getClass().getSimpleName()));
		validatable.error(error);
	}
	
}
 
Example #15
Source File: ManageUsersPage.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void validateUsername(IValidatable<String> aValidatable)
{
    if (userRepository.exists(aValidatable.getValue()) && isCreate) {
        aValidatable.error(new ValidationError().addKey("username.alreadyExistsError")
                .setVariable("name", aValidatable.getValue()));
    }
    else if (aValidatable.getValue().contains(" ")) {
        aValidatable.error(new ValidationError().addKey("username.containsSpaceError"));
    }
    else if (!NameUtil.isNameValid(aValidatable.getValue())) {
        aValidatable.error(new ValidationError().addKey("username.invalidCharactersError"));
    }
}
 
Example #16
Source File: ProjectDetailPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && projectService.existsProject(newName)) {
        aValidatable.error(new ValidationError(
                "Another project with the same name exists. Please try a different name"));
    }
}
 
Example #17
Source File: ProjectDetailPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    if (isNotBlank(newName) && !NameUtil.isNameValid(newName)) {
        aValidatable.error(new ValidationError(
                "Project name shouldn't contain characters such as /\\*?&!$+[^]"));
    }
}
 
Example #18
Source File: KeyBindingsConfigurationPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String keyCombo = aValidatable.getValue();
    KeyBinding keyBinding = new KeyBinding(keyCombo, null);
    if (!keyBinding.isValid()) {
        aValidatable.error(new ValidationError("Invalid key combo: [" + keyCombo + "]"));
    }
}
 
Example #19
Source File: ManageUsersPage.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void validateEnabled(IValidatable<Boolean> aValidatable)
{
    if (!aValidatable.getValue()
            && userRepository.getCurrentUser().equals(getModelObject())) {
        aValidatable.error(new ValidationError()
                .setMessage("You cannot disable your own account."));
    }
}
 
Example #20
Source File: ToggleBox.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<Boolean> aValidatable)
{
    if (aValidatable.getValue() == null) {
        aValidatable.error(new ValidationError("You need to make a choice."));
    }
}
 
Example #21
Source File: TagSetEditorPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && annotationSchemaService.existsTagSet(newName, selectedProject.getObject())) {
        aValidatable.error(new ValidationError(
                "Another tag set with the same name exists. Please try a different name"));
    }
}
 
Example #22
Source File: TagEditorPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> aValidatable)
{
    String newName = aValidatable.getValue();
    String oldName = aValidatable.getModel().getObject();
    if (!StringUtils.equals(newName, oldName) && isNotBlank(newName)
            && annotationSchemaService.existsTag(newName, selectedTagSet.getObject())) {
        aValidatable.error(new ValidationError(
                "Another tag with the same name exists. Please try a different name"));
    }
}
 
Example #23
Source File: Captcha.java    From openmeetings with 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 #24
Source File: IriValidator.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(IValidatable<String> validatable)
{
    if (!URIUtil.isValidURIReference(validatable.getValue())) {
        validatable.error(new ValidationError(this));
    }
}
 
Example #25
Source File: PasswordPatternValidator.java    From artifact-listener with Apache License 2.0 4 votes vote down vote up
@Override
protected IValidationError decorate(IValidationError error, IValidatable<String> validatable) {
	((ValidationError) error).setKeys(Collections.singletonList("register.password.malformed"));
	return error;
}
 
Example #26
Source File: ProjectVersionFormPopupPanel.java    From artifact-listener with Apache License 2.0 4 votes vote down vote up
@Override
protected IValidationError decorate(IValidationError error, IValidatable<String> validatable) {
	((ValidationError) error).setKeys(Collections.singletonList("project.version.field.version.malformed"));
	return error;
}
 
Example #27
Source File: ProjectFormPopupPanel.java    From artifact-listener with Apache License 2.0 4 votes vote down vote up
@Override
protected IValidationError decorate(IValidationError error, IValidatable<String> validatable) {
	((ValidationError) error).setKeys(Collections.singletonList("project.field.name.malformed"));
	return error;
}
 
Example #28
Source File: FormComponent.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Reports required error against this component
 */
protected void reportRequiredError()
{
	error(new ValidationError().addKey("Required"));
}
 
Example #29
Source File: UserWebService.java    From openmeetings with 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 #30
Source File: DatePanel.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @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));
        }
      }
    }
  });
}