下面列出了怎么用javax.validation.constraints.AssertTrue的API类实例代码及写法,或者点击链接到github查看源代码。
@AssertTrue(message = "Exactly one of 'bigquery.credentials-key' or 'bigquery.credentials-file' must be specified, or the default GoogleCredentials could be created")
public boolean isCredentialsConfigurationValid()
{
// only one of them (at most) should be present
if (credentialsKey.isPresent() && credentialsFile.isPresent()) {
return false;
}
// if no credentials were supplied, let's check if we can create the default ones
if (credentialsKey.isEmpty() && credentialsFile.isEmpty()) {
try {
GoogleCredentials.getApplicationDefault();
}
catch (IOException e) {
return false;
}
}
return true;
}
@AssertTrue(message="{specificDate.isDateTimeValid.AssertTrue}")
private boolean isDateTimeValid() {
try {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
dateformat.setLenient(false);
ParsePosition position = new ParsePosition(0);
String firstDateTime = this.startDate + " " + this.startTime;
String secondDateTime = this.endDate + " " + this.endTime;
Date first = dateformat.parse(firstDateTime, position);
if (( first == null) || (position.getIndex() != firstDateTime.length()))
return false;
position = new ParsePosition(0);
Date second = dateformat.parse(secondDateTime, position);
if (( second == null) || (position.getIndex() != secondDateTime.length()))
return false;
return first.before(second);
} catch (Exception e) {
BeanValidation.logger.info(e.getMessage());
return false;
}
}
@AssertTrue(message="{recurringSchedule.isRepeatOnValid.AssertTrue}")
private boolean isRepeatOnValid() {
String[] s_values = this.repeatOn.replace("\"", "").replace("[", "").replace("]", "").split(",");
String[] weekday = {"1", "2", "3", "4", "5", "6", "7"};
List<String> weekday_list = Arrays.asList(weekday);
Set<String> validValues = new HashSet<String>(weekday_list);
List<String> value_list = Arrays.asList(s_values);
Set<String> value_set = new HashSet<String>(value_list);
if ( s_values.length > value_set.size()) {
return false;
}
for (String s: s_values){
if(!validValues.contains(s)) {
return false;
}
}
if ( s_values.length > validValues.size()) {
return false;
}
return true;
}
@AssertTrue(message="{recurringSchedule.isTimeValid.AssertTrue}")
private boolean isTimeValid() {
try {
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
parser.setLenient(false);
ParsePosition position = new ParsePosition(0);
Date start_time = parser.parse(this.startTime, position);
if (( start_time == null) || (position.getIndex() != this.startTime.length()))
return false;
position = new ParsePosition(0);
Date end_time = parser.parse(this.endTime, position);
if (( end_time == null) || (position.getIndex() != this.endTime.length()))
return false;
return start_time.before(end_time);
} catch (Exception e) {
return false;
}
}
@AssertTrue(message="{Schedule.isTimeZoneValid.AssertTrue}") //debug
private boolean isTimeZoneValid() {
if ((null != this.timezone) && (this.timezone.trim().length() != 0)) {
BeanValidation.logger.debug("In schedules timezone is " + this.timezone);//debug
Set<String> timezoneset = new HashSet<String>(Arrays.asList(Constants.timezones));
if(timezoneset.contains(this.timezone))
return true;
else
return false;
}
else {
BeanValidation.logger.debug("timezone is empty in schedules");//debug
return false; //timezone must be specified in Schedule
}
}
@Test
public void testValidation()
{
assertValidates(new LdapConfig()
.setLdapUrl("ldaps://localhost")
.setUserBindSearchPattern("uid=${USER},ou=org,dc=test,dc=com")
.setUserBaseDistinguishedName("dc=test,dc=com")
.setGroupAuthorizationSearchPattern("&(objectClass=user)(memberOf=cn=group)(user=username)"));
assertValidates(new LdapConfig()
.setLdapUrl("ldap://localhost")
.setAllowInsecure(true)
.setUserBindSearchPattern("uid=${USER},ou=org,dc=test,dc=com")
.setUserBaseDistinguishedName("dc=test,dc=com")
.setGroupAuthorizationSearchPattern("&(objectClass=user)(memberOf=cn=group)(user=username)"));
assertFailsValidation(
new LdapConfig()
.setLdapUrl("ldap://")
.setAllowInsecure(false),
"urlConfigurationValid",
"Connecting to the LDAP server without SSL enabled requires `ldap.allow-insecure=true`",
AssertTrue.class);
assertFailsValidation(new LdapConfig().setLdapUrl("localhost"), "ldapUrl", "Invalid LDAP server URL. Expected ldap:// or ldaps://", Pattern.class);
assertFailsValidation(new LdapConfig().setLdapUrl("ldaps:/localhost"), "ldapUrl", "Invalid LDAP server URL. Expected ldap:// or ldaps://", Pattern.class);
assertFailsValidation(new LdapConfig(), "ldapUrl", "may not be null", NotNull.class);
}
@AssertTrue(message = "Invalid JDBC URL for MySQL connector")
public boolean isUrlValid()
{
try {
Driver driver = new Driver();
Properties properties = driver.parseURL(getConnectionUrl(), null);
return properties != null;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
@AssertTrue(message = "Database (catalog) must not be specified in JDBC URL for MySQL connector")
public boolean isUrlWithoutDatabase()
{
try {
Driver driver = new Driver();
Properties properties = driver.parseURL(getConnectionUrl(), null);
return (properties == null) || (driver.database(properties) == null);
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public PropertyModel postProcessInternal(PropertyModel propertyModel) {
AssertTrue assertTrueAnno = propertyModel.getPropertyItem().getAnnotation(AssertTrue.class);
if (assertTrueAnno == null) return propertyModel;
propertyModel.setDescription(TextUtils.combine(propertyModel.getDescription(), " (值只能为true)"));
return propertyModel;
}
@AssertTrue(message="{Schedule.isScheduleValid.AssertTrue}") //debug
private boolean isScheduleValid() {
if (((null == this.recurringSchedule) || (this.recurringSchedule.size() == 0) ) && ((null == this.specificDate) || (this.specificDate.size() == 0)) ){
return false; //at least one setting should be exist
}
return true;
}
@Test
public void testRegisteredPostConstructProcessor() {
genie.registerPostConstructProcessor(AssertTrue.class, new AssertTrueHandler());
yes(genie.get(FooToPass.class).val);
try {
genie.get(FooToFail.class);
fail("Expect ValidationException here");
} catch (ValidationException e) {
// test pass
}
}
/**
* Makes sure that the Reflections helper stuff is working properly and capturing all annotation possibilities (class type, constructor, constructor param, method, method param, and field).
*/
@Test
public void verifyThatTheReflectionsConfigurationIsCapturingAllAnnotationPossibilities() {
List<Pair<Annotation, AnnotatedElement>> annotationOptionsClassAnnotations = getSubAnnotationListForElementsOfOwnerClass(TROLLER.allConstraintAnnotationsMasterList,
DifferentValidationAnnotationOptions.class);
assertThat(annotationOptionsClassAnnotations.size(), is(10));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, SomeClassLevelJsr303Annotation.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, OtherClassLevelJsr303Annotation.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, AssertTrue.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, AssertFalse.class).size(), is(1));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, NotNull.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, Min.class).size(), is(2));
assertThat(getSubAnnotationListForAnnotationsOfClassType(annotationOptionsClassAnnotations, Max.class).size(), is(1));
}
@AssertTrue(message = "I am a constructor annotated with a constraint even though it doesn't really make sense")
public DifferentValidationAnnotationOptions(String nonAnnotatedConstructorParam,
@NotNull(message = "I am a constructor param annotated with a constraint 1") String annotatedConstructorParam1,
@NotNull(message = "I am a constructor param annotated with a constraint 2") String annotatedConstructorParam2,
String alsoNotAnnotatedConstructorParam) {
}
@AssertTrue(message="{HistoryData.isTimeZoneValid.AssertTrue}")
private boolean isTimeZoneValid() {
Set<String> timezoneset = new HashSet<String>(Arrays.asList(Constants.timezones));
if(timezoneset.contains(this.timeZone))
return true;
return false;
}
@AssertTrue(message="{Policy.isMetricTypeValid.AssertTrue}")
private boolean isMetricTypeUnique() {
Set<String> metric_types = new HashSet<String>();
for (PolicyTrigger trigger : this.policyTriggers){
metric_types.add(trigger.metricType);
}
if (metric_types.size() != this.policyTriggers.size())
return false;
else
return true;
}
@AssertTrue(message="{PolicyTrigger.isInstanceStepCountUpValid.AssertTrue}")
private boolean isInstanceStepCountUpValid() { //debug we support count instead of percent change only currently
for (PolicyTrigger trigger : this.policyTriggers){
if (trigger.instanceStepCountUp > (instanceMaxCount -1))
return false;
}
return true;
}
@AssertTrue(message="{Policy.isMetricTypeMatched.AssertTrue}")
private boolean isMetricTypeSupported() {
String [] supported_metrics = Constants.getMetricTypeByAppType(this.appType);
BeanValidation.logger.info("supported metrics are: " + Arrays.toString(supported_metrics));
if (supported_metrics != null) {
for (PolicyTrigger trigger : this.policyTriggers) {
if (!(Arrays.asList(supported_metrics).contains(trigger.metricType)))
return false;
}
}
return true;
}
@AssertTrue(message="{Policy.isRecurringScheduleTimeValid.AssertTrue}")
private boolean isRecurringScheduleTimeValid() {
if ((this.schedules != null) && (RecurringScheduleTimeValid(this.schedules.recurringSchedule) == false)) {
return false;
}
return true;
}
@AssertTrue(message="{Policy.isSpecificDateTimeValid.AssertTrue}")
private boolean isSpecificDateTimeValid() {
if ((this.schedules != null) && (SpecificDateTimeValid(this.schedules.specificDate) == false)) {
return false;
}
return true;
}
@AssertTrue(message="{specificDate.isInstCountValid.AssertTrue}")
private boolean isInstCountValid() {
if (this.maxInstCount > 0) { //maxInstCount is set
if (this.minInstCount > this.maxInstCount) {
return false;
}
}
return true;
}
@AssertTrue(message = "exactly one of 'name' and 'nameExpression' must be set")
public boolean isExclusiveOptions() {
return getName() != null ^ getNameExpression() != null;
}
@AssertTrue(message = "Trust store must be provided when TLS is enabled")
public boolean isTruststorePathValid()
{
return !tlsEnabled || getTruststorePath() != null;
}
@AssertTrue(message = "Empty request")
private boolean isValidRequest() {
return StringUtils.hasText(name) || StringUtils.hasText(email) || StringUtils.hasText(phoneNumber);
}
@AssertTrue(message = "Empty request")
private boolean isValidRequest() {
return StringUtils.hasText(name) || StringUtils.hasText(email) || StringUtils.hasText(phoneNumber);
}
@AssertTrue(message = "routingKey or routingKeyExpression is required")
public boolean isRoutingKeyProvided() {
return this.routingKey != null || this.routingKeyExpression != null;
}
@AssertTrue(message = "stop must be after start")
private boolean shopIsAfterStart() {
long duration = stop.toEpochMilli() - start.toEpochMilli();
return duration > 0;
}
@AssertTrue(message = "Shifts exceed max allowed hour duration")
private boolean withInMaxDuration() {
long duration = stop.toEpochMilli()- start.toEpochMilli();
return duration <= MAX_SHIFT_DURATION;
}
@AssertTrue(message = "Exactly one of 'queue', 'queueExpression', 'key', 'keyExpression', "
+ "'topic' and 'topicExpression' must be set")
public boolean isMutuallyExclusive() {
Object[] props = new Object[]{queue, queueExpression, key, keyExpression, topic, topicExpression};
return (props.length - 1) == Collections.frequency(Arrays.asList(props), null);
}
@AssertTrue(message = "Shifts exceed max allowed hour duration")
private boolean withInMaxDuration() {
long duration = stop.toEpochMilli() - start.toEpochMilli();
return duration <= MAX_SHIFT_DURATION;
}
@AssertTrue(message = "shift_start_after must be before shift_start_before")
private boolean correctAfterAndBefore() {
long duration = shiftStartAfter.toEpochMilli() - shiftStartBefore.toEpochMilli();
return duration < 0;
}