Java javax.validation.constraints.AssertTrue 代码实例

・16 分钟阅读

以下是展示如何使用javax.validation.constraints.AssertTrue的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * User can't explicitly set mutually exclusive values together.
 */
@AssertTrue(message = "the 'topics' and 'queue' options are mutually exclusive")
public boolean isOptionMutuallyExclusive() {
        boolean optionSpecified = false;
        String[] distinctOptions = {this.topics, this.queue};
        for (String option : distinctOptions) {
                if (optionSpecified == true && option != null) {
                        return false;
                }
                if (option != null) {
                        optionSpecified = true;
                }
        }
        return true;
}
 

实例 2


/**
 * Tests customizations, i.e. facet customizations + custom facets, i.e.
 * Future, Past, AssertTrue, AssertFalse.
 */
public void testFacetCustomizationsAndCustomFacets() throws Exception {
    pkg = "cs";
    xjcGenerateJavaSourcesWithCustomizations(CUSTOMIZED_SCHEMA_PATH);
    compileGeneratedSources(createCompileList(pkg));
    Class<?> custom = loadCompiledClasses(createLoadList(pkg))[0];
    Field generic = custom.getDeclaredField("generic");
    Size s = generic.getAnnotation(Size.class);
    assertEquals(s.message(), "Hello, world!");
    assertEquals(s.groups()[0], BindingTeam.class);
    assertEquals(s.groups()[1], RocketTeam.class);
    assertEquals(s.max(), 4);
    Pattern p1 = generic.getAnnotation(Pattern.List.class).value()[0];
    Pattern p2 = generic.getAnnotation(Pattern.List.class).value()[1];
    assertEquals(p1.message(), p2.message());
    assertTrue(Arrays.equals(p1.groups(), p2.groups()));
    assertEquals(p1.message(), "Hello.");
    assertEquals(p1.groups()[0], Object.class);
    assertEquals(p1.regexp(), "10");
    Future f = generic.getAnnotation(Future.class);
    assertEquals(f.message(), "Welcome to the Future!");
    assertEquals(f.groups()[0], BindingTeam.class);
    Past p = generic.getAnnotation(Past.class);
    assertEquals(p.message(), "Farewell from the ancestors.");
    assertEquals(p.groups()[0], Ancestors.class);
    AssertTrue at = generic.getAnnotation(AssertTrue.class);
    assertEquals(at.message(), "True fan of the team!");
    assertEquals(at.groups()[0], BindingTeam.class);
    AssertFalse af = generic.getAnnotation(AssertFalse.class);
    assertEquals(af.message(), "false");
    assertEquals(af.groups()[0], Object.class);
    // To test a user custom annotation.
    CustomAnnotation xmlKey = generic.getAnnotation(CustomAnnotation.class);
    assertNotNull(xmlKey);
}
 

实例 3


@Override
public void handle(String paramName, Object paramVal, Annotation annotation, ActionContext context) {
    if (null != paramVal && !Boolean.parseBoolean(paramVal.toString())) {
        AssertTrue theAnno = (AssertTrue) annotation;
        context.addViolation(new ActionMethodParamConstraintViolation<Object>(paramVal, theAnno.message(), theAnno, context));
    }
}
 

实例 4


@Command(value = "AssertTrue", help = "Adds @AssertTrue constraint on the specified property")
public void addAssertTrueConstraint(@Option(name = "onProperty", completer = PropertyCompleter.class, required = true) String property,
                                    @Option(name = "onAccessor", flagOnly = true) boolean onAccessor,
                                    @Option(name = "message") String message,
                                    @Option(name = "groups", type = JAVA_CLASS) String[] groups,
                                    PipeOut pipeOut) throws FileNotFoundException
{
    final Annotation<JavaClass> constraintAnnotation = addConstraintOnProperty(property, onAccessor, AssertTrue.class);
    setConstraintMessage(constraintAnnotation, message);
    javaSourceFacet.saveJavaSource(constraintAnnotation.getOrigin());
    outputConstraintAdded(pipeOut, property, AssertTrue.class);
}
 

实例 5


@AssertTrue(message = VALIDATION_MSG_ALL, groups = { Default.class, ValidationGroupAllComponents.class })
public boolean isAllInputsCorrect() {
    return autocompleteInput.contains(SMILE) && inplaceSelect.contains(SMILE) && inplaceInput.contains(SMILE)
        && select.contains(SMILE) && inputNumberSlider.equals(REQUIRED_INTEGER_VALUE)
        && inputNumberSpinner.equals(REQUIRED_INTEGER_VALUE) && inputText.contains(SMILE) && inputSecret.contains(SMILE)
        && inputTextarea.contains(SMILE) && selectBooleanCheckbox.booleanValue() && selectManyCheckbox.contains(SMILE)
        && selectOneListbox.contains(SMILE) && selectManyListbox.contains(SMILE) && selectOneMenu.contains(SMILE)
        && selectManyMenu.contains(SMILE) && selectOneRadio.contains(SMILE)
        && !calendar.after(new Date(System.currentTimeMillis()));
}
 

实例 6


@AssertTrue(message = "Please verify the recipients set")
private boolean isValid()
{
  if (recipients.isEmpty()) {
    return false;
  }
  for (Map.Entry<String, String> entry : recipients.entrySet()) {
    if (entry.getKey().toUpperCase().equalsIgnoreCase(RecipientType.TO.toString())) {
      if (entry.getValue() != null && entry.getValue().length() > 0) {
        return true;
      }
      return false;
    }
  }
  return false;
}
 

实例 7


@GET
   @Path("lazy")
   @Produces("text/plain")
   @AssertTrue
   public boolean testLazyValidator(@Context Providers providers)
   {
      ContextResolver<GeneralValidator> resolver = providers.getContextResolver(GeneralValidator.class, MediaType.WILDCARD_TYPE);
      System.out.println("resolver: " + resolver);
      if (resolver == null)
      {
         return false;
      }
      Field field = null;
      try
      {
//         field = ValidatorContextResolver.class.getField("validatorFactory");
         field = resolver.getClass().getField("validatorFactory");
         field.setAccessible(true);
         Object factory = field.get(resolver);
         System.out.println("ValidatorFactory: " + factory);
         if (factory == null)
         {
            return false;
         }
         return factory.getClass().getName().equals("org.jboss.as.ee.beanvalidation.LazyValidatorFactory");
      }
      catch (Exception e)
      {
         e.printStackTrace();
         return false;
      }
   }
 

实例 8


private void checkAnnotations(Class<?> contractClass) {
    Field[] fields = contractClass.getFields();
    for (Field field : fields) {
        Class fieldType = field.getType();
        if (Optional.class.isAssignableFrom(fieldType)) {
            checkAnnotation(contractClass, field,UnwrapValidatedValue.class);
            checkNoAnnotation(contractClass, field, NotNull.class);
        }
        else {
            checkNoAnnotation(contractClass, field, UnwrapValidatedValue.class);
            checkAnnotation(contractClass, field,NotNull.class);
        }
    }
    for(Method method : contractClass.getMethods()) {
        if(method.isAnnotationPresent(AssertTrue.class) || method.isAnnotationPresent(AssertFalse.class)) {
            if(method.getReturnType() != boolean.class && method.getReturnType() != Boolean.class) {
                throw new IllegalStateException("AssertTrue or AssertFalse annotations must be placed 上面 methods that return boolean value");
            }
            if(!method.getName().startsWith("is")) {
                throw new IllegalStateException("Methods annotated with AssertTrue or AssertFalse must start with "is"");
            }
        }
    }
}
 

实例 9


@AssertTrue(message = "{error.signature.underlying.form.mandatory}")
public boolean isAsicUnderlyingFormValid(){
        if (SignatureForm.ASiC_S.equals(signatureForm) || SignatureForm.ASiC_E.equals(signatureForm)){
                return SignatureForm.CAdES.equals(asicUnderlyingForm) || SignatureForm.XAdES.equals(asicUnderlyingForm);
        } else{
                return true;
        }
}
 

实例 10


/**
 * The validation context can change depending on the nature of a widget. A custom widget name can't contain space but a
 * normal one yes
 */
@AssertTrue(message = "Widget name should contains only alphanumeric characters with no space")
private boolean isValidName() {
    if (!isCustom()) {
        return true;
    }
    return PATTERN_DATE_VALIDATION.matcher(name).matches();
}
 

实例 11


private static void mapBeanValidationParameter(Annotation annotation, InstanceDescriptor element) {
        SimpleTypeDescriptor typeDescriptor = (SimpleTypeDescriptor) element.getLocalType(false);
if (annotation instanceof AssertFalse)
                typeDescriptor.setTrueQuota(0.);
        else if (annotation instanceof AssertTrue)
                typeDescriptor.setTrueQuota(1.);
        else if (annotation instanceof DecimalMax)
                typeDescriptor.setMax(String.valueOf(DescriptorUtil.convertType(((DecimalMax) annotation).value(), typeDescriptor)));
        else if (annotation instanceof DecimalMin)
                typeDescriptor.setMin(String.valueOf(DescriptorUtil.convertType(((DecimalMin) annotation).value(), typeDescriptor)));
        else if (annotation instanceof Digits) {
                Digits digits = (Digits) annotation;
        typeDescriptor.setGranularity(String.valueOf(Math.pow(10, - digits.fraction())));
        } else if (annotation instanceof Future)
       typeDescriptor.setMin(new SimpleDateFormat("yyyy-MM-dd").format(TimeUtil.tomorrow()));
      else if (annotation instanceof Max)
        typeDescriptor.setMax(String.valueOf(((Max) annotation).value()));
      else if (annotation instanceof Min)
                typeDescriptor.setMin(String.valueOf(((Min) annotation).value()));
        else if (annotation instanceof NotNull) {
                element.setNullable(false);
                element.setNullQuota(0.);
        } else if (annotation instanceof Null) {
                element.setNullable(true);
                element.setNullQuota(1.);
        } else if (annotation instanceof Past)
       typeDescriptor.setMax(new SimpleDateFormat("yyyy-MM-dd").format(TimeUtil.yesterday()));
      else if (annotation instanceof Pattern)
                typeDescriptor.setPattern(String.valueOf(((Pattern) annotation).regexp()));
        else if (annotation instanceof Size) {
                Size size = (Size) annotation;
                typeDescriptor.setMinLength(size.min());
                typeDescriptor.setMaxLength(size.max());
        }
  }
 

实例 12


@AssertTrue(message="Een beheerder kan geen bronhouder kiezen. Een beheerder is automatisch bronhouder voor alle provincies")
public boolean isBronhouderMandatoryValid(){
        boolean valid = true;
        // If beheerder, then bronhouder is not permitted
        if(this.isBeheerder()){
                if(this.getBronhouder() != null){
                        valid = false;
                }
        }
        return valid;
}
 

实例 13


/**
 * dummy check to make sure that from is lower or equal to to
 * @return true of from is lower or equal to
 */
@AssertTrue(message = "error.calendar.empty")
public boolean getNonEmpty() {
        if (this.fromJD == null || this.toJD == null) return true; // no NPEs
        // not allowed empty values in both entries
        if (this.fromJD == Long.MIN_VALUE && this.toJD == Long.MAX_VALUE) return false;
        return true;
}
 

实例 14


@AssertTrue(message = "withMarkers can only be supplied when FileReadingMode is 'lines'")
public boolean isWithMarkersValid() {
        if (this.withMarkers != null && FileReadingMode.lines != this.fileReadingmode) {
                return false;
        }
        else {
                return true;
        }
}
 

实例 15


@Test
public void testValidations()
{
    assertFailsValidation(new ServerConfig().setCombinerStartDaysAgo(1).setCombinerEndDaysAgo(1), "combinerStartEndDaysSane", "must be true", AssertTrue.class);
    assertFailsValidation(new ServerConfig().setCombinerGroupId(null), "combinerGroupId", "may not be null", NotNull.class);
    assertFailsValidation(new ServerConfig().setCombinerGroupId(""), "combinerGroupId", "must be non-empty", Size.class);
    assertFailsValidation(new ServerConfig().setCombinerThreadCount(0), "combinerThreadCount", "must be greater than or equal to 1", Min.class);
    assertFailsValidation(new ServerConfig().setCombinerHighPriorityEventTypes(ImmutableSet.of("TypeA", "TypeB")).setCombinerLowPriorityEventTypes(ImmutableSet.of("TypeB", "TypeC")), "highAndLowPriorityEventTypesDisjoint", "High- and Low-Priority event type lists must be disjoint.", AssertTrue.class);
    assertValidates(new ServerConfig()
            .setLocalStagingDirectory(new File("testdir"))
            .setAwsAccessKey("my-access-key")
            .setAwsSecretKey("my-secret-key")
            .setS3StagingLocation("s3://example-staging/")
            .setS3DataLocation("s3://example-data/")
            .setS3MetadataLocation("s3://example-metadata/")
            .setCombinerGroupId("someGroupId"));
}
 
讨论
淘淘あ西西 profile image