Java Code Examples for javax.validation.ConstraintValidatorContext#disableDefaultConstraintViolation()

The following examples show how to use javax.validation.ConstraintValidatorContext#disableDefaultConstraintViolation() . 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: IssueQueryValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) {
		return true;
	} else {
		Project project = Project.get();
		try {
			io.onedev.server.search.entity.issue.IssueQuery.parse(project, value, 
					true, withCurrentUserCriteria, withCurrentBuildCriteria, 
					withCurrentPullRequestCriteria, withCurrentCommitCriteria);
			return true;
		} catch (Exception e) {
			constraintContext.disableDefaultConstraintViolation();
			String message = this.message;
			if (message.length() == 0) {
				if (StringUtils.isNotBlank(e.getMessage()))
					message = e.getMessage();
				else
					message = "Malformed issue query";
			}
			
			constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}
	}
}
 
Example 2
Source File: ValidQueryParamsValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(Object[] value, ConstraintValidatorContext context) {
	Set<String> expectedParams = new HashSet<>();
	for (Annotation[] annotations: resourceInfo.getResourceMethod().getParameterAnnotations()) {
		for (Annotation annotation: annotations) {
			if (annotation instanceof QueryParam) {
				QueryParam param = (QueryParam) annotation;
				expectedParams.add(param.value());
			}
		}
	}
	
	Set<String> actualParams = new HashSet<>(uriInfo.getQueryParameters().keySet());
	actualParams.removeAll(expectedParams);
	if (actualParams.isEmpty()) {
		return true;
	} else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate("Unexpected query params: " + actualParams).addConstraintViolation();
		return false;
	}
}
 
Example 3
Source File: UrlValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    if (value == null) {
        return true;
    }
    if (value.isEmpty()) {
        ValidatorUtil.addConstraintViolation(context, "URL may not be empty");
        return false;
    }

    long validatorOptions = ALLOW_ALL_SCHEMES + ALLOW_LOCAL_URLS + NO_FRAGMENTS;
    org.apache.commons.validator.routines.UrlValidator commonsValidator = new org.apache.commons.validator.routines.UrlValidator(validatorOptions);
    if (!commonsValidator.isValid(value)) {
        ValidatorUtil.addConstraintViolation(context, value + " is not a valid URL");
        return false;
    }
    return true;
}
 
Example 4
Source File: BuildQueryValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) {
		return true;
	} else {
		Project project = Project.get();
		try {
			io.onedev.server.search.entity.build.BuildQuery.parse(project, value, 
					withCurrentUserCriteria, withUnfinishedCriteria);
			return true;
		} catch (Exception e) {
			constraintContext.disableDefaultConstraintViolation();
			String message = this.message;
			if (message.length() == 0) {
				if (StringUtils.isNotBlank(e.getMessage()))
					message = e.getMessage();
				else
					message = "Malformed build query";
			}
			
			constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}
	}
}
 
Example 5
Source File: RoleNotContainSelfValidator.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
  log.trace("Validating role doesn't contain itself: {}", value);

  String id = getId(value);
  //this must be a create if there is no id
  if (Strings2.isEmpty(id)) {
    return true;
  }

  Set<String> processedRoleIds = new HashSet<>();
  Collection<String> roleIds = getRoleIds(value);
  for (String roleId : roleIds) {
    if (containsRole(id, roleId, processedRoleIds)) {
      context.disableDefaultConstraintViolation();
      context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
      return false;
    }
  }

  return true;
}
 
Example 6
Source File: UserMatchValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) {
		return true;
	} else {
		try {
			io.onedev.server.util.usermatch.UserMatch.parse(value);
			return true;
		} catch (Exception e) {
			constraintContext.disableDefaultConstraintViolation();
			String message = this.message;
			if (message.length() == 0) {
				if (StringUtils.isNotBlank(e.getMessage()))
					message = e.getMessage();
				else
					message = "Malformed user match";
			}
			
			constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}
	}
}
 
Example 7
Source File: SpringValidatorAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper beanWrapper = new BeanWrapperImpl(value);
	Object fieldValue = beanWrapper.getPropertyValue(field);
	Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
	boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
	if (matched) {
		return true;
	}
	else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message)
				.addPropertyNode(field)
				.addConstraintViolation();
		return false;
	}
}
 
Example 8
Source File: OneNotBlankValidator.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    try {
        for (final String name : fieldsName) {
            final String prop = BeanUtils.getProperty(value, name);
            if (isNotBlank(prop)) {
                return true;
            }
        }
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }

    context.disableDefaultConstraintViolation();
    context
            .buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
            .addPropertyNode(fieldsName[0])
            .addConstraintViolation();
    return false;
}
 
Example 9
Source File: CoderadarPasswordValidator.java    From coderadar with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
  if (value == null || value.isEmpty()) {
    return false;
  }
  PasswordValidator passwordValidator =
      new PasswordValidator( //
          Arrays.asList(
              new CharacterRule(EnglishCharacterData.Digit, 1),
              new CharacterRule(EnglishCharacterData.Alphabetical, 1),
              new WhitespaceRule()));
  RuleResult result = passwordValidator.validate(new PasswordData(value));
  if (result.isValid()) {
    return true;
  }
  context.disableDefaultConstraintViolation();
  context
      .buildConstraintViolationWithTemplate(
          Joiner.on("n").join(passwordValidator.getMessages(result)))
      .addConstraintViolation();
  return false;
}
 
Example 10
Source File: SpringValidatorAdapterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public boolean isValid(Object value, ConstraintValidatorContext context) {
	BeanWrapper beanWrapper = new BeanWrapperImpl(value);
	Object fieldValue = beanWrapper.getPropertyValue(field);
	Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
	boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
	if (matched) {
		return true;
	}
	else {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message)
				.addPropertyNode(field)
				.addConstraintViolation();
		return false;
	}
}
 
Example 11
Source File: CodeCommentQueryValidator.java    From onedev with MIT License 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintContext) {
	if (value == null) {
		return true;
	} else {
		Project project = Project.get();
		try {
			io.onedev.server.search.entity.codecomment.CodeCommentQuery.parse(project, value);
			return true;
		} catch (Exception e) {
			constraintContext.disableDefaultConstraintViolation();
			String message = this.message;
			if (message.length() == 0) {
				if (StringUtils.isNotBlank(e.getMessage()))
					message = e.getMessage();
				else
					message = "Malformed code comment query";
			}
			
			constraintContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
			return false;
		}
	}
}
 
Example 12
Source File: UnsupportedKeyPairValidator.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(UnsupportedKeyPair keyPair, ConstraintValidatorContext context) {
    if (isIncompleteDirectKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.bothDirectKeysRequired.message}")
                .addConstraintViolation();
    }
    else if (isIncompleteInlineKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.bothInlineKeysRequired.message}")
                .addConstraintViolation();
    }
    else if (isIncompleteAzureVaultKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.bothAzureKeysRequired.message}")
                .addConstraintViolation();
    }
    else if (isIncompleteHashicorpVaultKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.allHashicorpKeyDataRequired.message}")
                .addConstraintViolation();
    }
    else if (isIncompleteAWSVaultKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.bothAWSKeysRequired.message}")
            .addConstraintViolation();
    }
    else if (isIncompleteFilesystemKeyPair(keyPair)) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("{UnsupportedKeyPair.bothFilesystemKeysRequired.message}")
            .addConstraintViolation();
    }

    return false;
}
 
Example 13
Source File: HostKeyAndAlgoBothExistValidator.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private boolean isAlgorithmSpecifiedWhenHostKeySet(
		JGitEnvironmentProperties sshUriProperties,
		ConstraintValidatorContext context) {
	if (hasText(sshUriProperties.getHostKey())
			&& !hasText(sshUriProperties.getHostKeyAlgorithm())) {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(format(
				"Property '%shostKeyAlgorithm' must be set when '%shostKey' is specified",
				GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX)).addConstraintViolation();
		return false;
	}
	return true;
}
 
Example 14
Source File: AudioCodecValidator.java    From poor-man-transcoder with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean isValid(ICodec codec, ConstraintValidatorContext context) {
	// TODO Auto-generated method stub
	String message = null;
	boolean valid = true;
	
	try
	{
		String codecName = (String) codec.getValue();
		
		if(!isInEnum(codecName, CodecOptions.class) && !isInEnum(codecName, AudioCodecs.class))
		{
			valid = false;
			message = "{com.flashvisions.server.rtmp.transcoder.validation.audio.codec.invalid.generic}";
		}
		
		if(isEnum(codecName, CodecOptions.COPY))
		codec.setSameAsSource(true);
			
		if(isEnum(codecName, CodecOptions.DISABLE))
		codec.setEnabled(false);
		
		if(isEnum(codecName, CodecOptions.SKIPTHRU))
		codec.setIgnore(true);
		
		if(!valid) {
		context.disableDefaultConstraintViolation();
		context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
	    }
	}
	catch(Exception e)
	{
		valid = false;
	}
	
	return valid;
}
 
Example 15
Source File: PolicyValidator.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(final Policy policy, final ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();

    if (isHtml(policy.getDescription())) {
        context.buildConstraintViolationWithTemplate(
                getTemplate(EntityViolationType.InvalidName, policy.getDescription())).
                addPropertyNode("description").addConstraintViolation();
        return false;
    }

    return true;
}
 
Example 16
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public boolean isValid(InnerBean bean, ConstraintValidatorContext context) {
	context.disableDefaultConstraintViolation();
	if (bean.getValue() == null) {
		context.buildConstraintViolationWithTemplate("NULL").addPropertyNode("value").addConstraintViolation();
		return false;
	}
	return true;
}
 
Example 17
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean isValid(List<String> list, ConstraintValidatorContext context) {
	context.disableDefaultConstraintViolation();
	boolean valid = true;
	for (int i = 0; i < list.size(); i++) {
		if ("X".equals(list.get(i))) {
			context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addBeanNode().inIterable().atIndex(i).addConstraintViolation();
			valid = false;
		}
	}
	return valid;
}
 
Example 18
Source File: SslConfigValidator.java    From tessera with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid(SslConfig sslConfig, ConstraintValidatorContext context) {

    context.disableDefaultConstraintViolation();

    if (Objects.isNull(sslConfig)) {
        return true;
    }

    if (sslConfig.getTls() == SslAuthenticationMode.STRICT) {

        if (!sslConfig.isGenerateKeyStoreIfNotExisted()) {

            if (!isServerKeyStoreConfigValid(sslConfig, context)
                    || !isClientKeyStoreConfigValid(sslConfig, context)) {
                return false;
            }
        }

        if (!isTrustModeConfigValid(sslConfig, context)) {
            return false;
        }

        if (!isServerConfigValidForWhiteListMode(sslConfig, context)) {
            return false;
        }

        if (!isServerConfigValidForCAMode(sslConfig, context)) {
            return false;
        }

        if (!isClientConfigValidForWhiteListMode(sslConfig, context)) {
            return false;
        }

        if (!isClientConfigValidForCAMode(sslConfig, context)) {
            return false;
        }
    }

    return true;
}
 
Example 19
Source File: LessThanEqualsToValidator.java    From sinavi-jfw with Apache License 2.0 4 votes vote down vote up
private boolean addErrors(ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(lessThanEqualsTo.message()).addPropertyNode(lessThanEqualsTo.from()).addConstraintViolation();
    return false;
}
 
Example 20
Source File: ServerConfigValidator.java    From tessera with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid(ServerConfig serverConfig, ConstraintValidatorContext constraintContext) {

    if (serverConfig == null) {
        return true;
    }

    if (serverConfig.getApp() == null || AppType.ADMIN.toString().equals(serverConfig.getApp().toString())) {
        String supportedAppTypes =
                Arrays.stream(AppType.values())
                        .filter(t -> t != AppType.ADMIN)
                        .map(AppType::name)
                        .map(n -> "THIRD_PARTY".equals(n) ? "ThirdParty" : n)
                        .collect(Collectors.joining(", "));

        constraintContext.disableDefaultConstraintViolation();
        constraintContext
                .buildConstraintViolationWithTemplate(
                        "app must be provided for serverConfig and be one of " + supportedAppTypes)
                .addConstraintViolation();
        return false;
    }

    if (!serverConfig.getApp().getAllowedCommunicationTypes().contains(serverConfig.getCommunicationType())) {
        LOGGER.debug(
                "Invalid communicationType '"
                        + serverConfig.getCommunicationType()
                        + "' specified for serverConfig with app "
                        + serverConfig.getApp());
        constraintContext.disableDefaultConstraintViolation();
        constraintContext
                .buildConstraintViolationWithTemplate(
                        "Invalid communicationType '"
                                + serverConfig.getCommunicationType()
                                + "' specified for serverConfig with app "
                                + serverConfig.getApp())
                .addConstraintViolation();
        return false;
    }

    if (serverConfig.getApp() != AppType.THIRD_PARTY) {
        if (serverConfig.getCrossDomainConfig() != null) {
            LOGGER.debug("Invalid server config. CrossDomainConfig is only allowed in ThirdParty server");
            constraintContext.disableDefaultConstraintViolation();
            constraintContext
                    .buildConstraintViolationWithTemplate(
                            "Invalid server config. CrossDomainConfig is only allowed in ThirdParty server")
                    .addConstraintViolation();
            return false;
        }
    }

    return true;
}