Example usage for java.lang.annotation ElementType FIELD

List of usage examples for java.lang.annotation ElementType FIELD

Introduction

In this page you can find the example usage for java.lang.annotation ElementType FIELD.

Prototype

ElementType FIELD

To view the source code for java.lang.annotation ElementType FIELD.

Click Source Link

Document

Field declaration (includes enum constants)

Usage

From source file:com.sinosoft.one.mvc.testcases.controllers.validators.DefControllerTest.java

public void testCascade() {

    RentalCar rentalCar = new RentalCar();
    Car car = new Car();
    car.setRentalCar(rentalCar);/*  w w w.  j a v  a2 s.  c o  m*/
    car.setLicensePlate("1");
    car.setManufacturer("2");
    List<RentalCar> list = new ArrayList<RentalCar>();
    list.add(rentalCar);
    car.setRentalCarList(list);
    HibernateValidatorConfiguration config = Validation.byProvider(HibernateValidator.class).configure();
    ConstraintMapping mapping = config.createConstraintMapping();
    PropertyConstraintMappingContext context = mapping.type(Car.class)
            .property("manufacturer", ElementType.FIELD).constraint(new NotNullDef()).valid()
            .property("licensePlate", ElementType.FIELD).constraint(new NotNullDef())
            .constraint(new SizeDef().min(2).max(14)).property("seatCount", ElementType.FIELD)
            .constraint(new MinDef().value(2)).property("rentalCarList", ElementType.FIELD).valid()
            .type(RentalCar.class).property("rentalStation", ElementType.FIELD);
    System.out.println(context.getClass());
    context.constraint(new NotNullDef()).valid();
    config.addMapping(mapping);
    Set<ConstraintViolation<Car>> result = config.buildValidatorFactory().getValidator().validate(car);
    Assert.assertEquals(3, result.size());

}

From source file:com.thesett.util.validation.core.JsonSchemaConstraintMapping.java

/**
 * Adds constraints in a json schema to the mapping, against the specified class.
 *
 * @param type       The class to add constraints to.
 * @param jsonSchema The json schema to add constraints from.
 * @param <C>        The type of the class to add constraints to.
 *//*from   ww  w  .j a  v a  2s.co m*/
public <C> void addSchema(Class<C> type, JsonSchema jsonSchema) {
    TypeConstraintMappingContext<C> typeContext = type(type);

    // Scan all of the fields of the class being added to, to check if there are any @JsonProperty mappings,
    // translating field names between Java and JSON.
    Map<String, String> jsonToJava = new HashMap<>();

    for (Field field : type.getDeclaredFields()) {
        JsonProperty annotation = field.getAnnotation(JsonProperty.class);

        if (annotation != null) {
            jsonToJava.put(annotation.value(), field.getName());
        }
    }

    if (jsonSchema.getProperties() != null) {
        for (Map.Entry<String, JsonSchema> property : jsonSchema.getProperties().entrySet()) {
            String jsonPropertyName = property.getKey();
            String javaPropertyName;

            if (jsonToJava.containsKey(jsonPropertyName)) {
                javaPropertyName = jsonToJava.get(jsonPropertyName);
            } else {
                javaPropertyName = jsonPropertyName;
            }

            PropertyConstraintMappingContext propertyContext = typeContext.property(javaPropertyName,
                    ElementType.FIELD);

            addConstraints(propertyContext, javaPropertyName, jsonPropertyName, property.getValue(), type);

            convertRequired(propertyContext, javaPropertyName, jsonPropertyName, jsonSchema);
        }
    }
}

From source file:org.web4thejob.orm.PropertyMetadataImpl.java

protected boolean isMandatory() {
    final Validator validator = ContextUtil.getBean(Validator.class);
    final BeanDescriptor beanDescriptor = validator
            .getConstraintsForClass(getEntityMetadata().getMappedClass());

    if (!beanDescriptor.isBeanConstrained()) {
        return false;
    }// w w  w.j a v a 2 s  .  c  o m
    PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(property.getName());
    if (propertyDescriptor == null) {
        return false;
    }
    Set<ConstraintDescriptor<?>> constraints = propertyDescriptor.findConstraints()
            .declaredOn(ElementType.FIELD).unorderedAndMatchingGroups(Default.class).getConstraintDescriptors();

    for (ConstraintDescriptor<?> constraint : constraints) {
        if (NotNull.class.isInstance(constraint.getAnnotation())
                || NotBlank.class.isInstance(constraint.getAnnotation())
                || NotEmpty.class.isInstance(constraint.getAnnotation())) {
            return true;
        }
    }

    return false;
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private boolean isPropertyConstrained(final PropertyDescriptor ppropertyDescription, final boolean useField) {
    // cascaded counts as constrained
    // we must know if the @Valid annotation is on a field or a getter
    final JClassType jClass = this.beanHelper.getJClass();
    if (useField && jClass.findField(ppropertyDescription.getPropertyName()).isAnnotationPresent(Valid.class)) {
        return true;
    } else if (!useField
            && jClass.findMethod(asGetter(ppropertyDescription), NO_ARGS).isAnnotationPresent(Valid.class)) {
        return true;
    }/*from   ww w . j a  v  a  2  s.com*/
    // for non-cascaded properties
    for (final ConstraintDescriptor<?> constraint : ppropertyDescription.getConstraintDescriptors()) {
        final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate = (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
        if (constraintHibernate.getElementType() == (useField ? ElementType.FIELD : ElementType.METHOD)) {
            return true;
        }
    }
    return false;
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private void writeValidatePropertyMethod(final SourceWriter sw, final PropertyDescriptor ppropertyDescription,
        final boolean useField) throws UnableToCompleteException {
    final Class<?> elementClass = ppropertyDescription.getElementClass();
    final JType elementType = this.beanHelper.getElementType(ppropertyDescription, useField);

    // private final <T> void validateProperty_{get}<p>(
    sw.print("private final <T> void ");
    if (useField) {
        sw.print(this.validateMethodFieldName(ppropertyDescription));
    } else {/*from w w w. ja v  a 2  s.c o m*/
        sw.print(this.validateMethodGetterName(ppropertyDescription));
    }
    sw.println("(");
    sw.indent();
    sw.indent();

    // final GwtValidationContext<T> context,
    sw.println("final GwtValidationContext<T> context,");

    // final Set<ConstraintViolation<T>> violations,
    sw.println("final Set<ConstraintViolation<T>> violations,");

    // BeanType object,
    sw.println(this.beanHelper.getTypeCanonicalName() + " object,");

    // final <Type> value,
    sw.print("final ");
    sw.print(elementType.getParameterizedQualifiedSourceName());
    sw.println(" value,");

    // boolean honorValid,
    sw.println("boolean honorValid,");

    // Class<?>... groups) {
    sw.println("Class<?>... groups) {");
    sw.outdent();

    // only write the checks if the property is constrained in some way
    if (this.isPropertyConstrained(ppropertyDescription, useField)) {
        // context = context.append("myProperty");
        sw.print("final GwtValidationContext<T> myContext = context.append(\"");
        sw.print(ppropertyDescription.getPropertyName());
        sw.println("\");");

        // only check this property if the TraversableResolver says we can

        // Node leafNode = myContext.getPath().getLeafNode();
        sw.println("Node leafNode = myContext.getPath().getLeafNode();");
        // PathImpl path = myContext.getPath().getPathWithoutLeafNode();
        sw.println("PathImpl path = myContext.getPath().getPathWithoutLeafNode();");
        // boolean isReachable;
        sw.println("boolean isReachable;");
        // try {
        sw.println("try {");
        sw.indent();
        // isReachable = myContext.getTraversableResolver().isReachable(object, leafNode,
        // myContext.getRootBeanClass(), path, ElementType);
        sw.println("isReachable = myContext.getTraversableResolver().isReachable(object, "
                + "leafNode, myContext.getRootBeanClass(), path, "
                + (useField ? asLiteral(ElementType.FIELD) : asLiteral(ElementType.METHOD)) + ");");
        // } catch (Exception e) {
        sw.outdent();
        sw.println("} catch (Exception e) {");
        sw.indent();
        // throw new ValidationException("TraversableResolver isReachable caused an exception", e);
        sw.println("throw new ValidationException(\"TraversableResolver isReachable caused an "
                + "exception\", e);");
        // }
        sw.outdent();
        sw.println("}");
        // if (isReachable) {
        sw.println("if (isReachable) {");
        sw.indent();

        // TODO(nchalko) move this out of here to the Validate method
        if (ppropertyDescription.isCascaded() && this.hasValid(ppropertyDescription, useField)) {

            // if (honorValid && value != null) {
            sw.println("if (honorValid && value != null) {");
            sw.indent();
            // boolean isCascadable;
            sw.println("boolean isCascadable;");
            // try {
            sw.println("try {");
            sw.indent();
            // isCascadable = myContext.getTraversableResolver().isCascadable(object, leafNode,
            // myContext.getRootBeanClass(), path, ElementType)
            sw.println("isCascadable = myContext.getTraversableResolver().isCascadable(object, "
                    + "leafNode, myContext.getRootBeanClass(), path, "
                    + (useField ? asLiteral(ElementType.FIELD) : asLiteral(ElementType.METHOD)) + ");");
            // } catch (Exception e) {
            sw.outdent();
            sw.println("} catch (Exception e) {");
            sw.indent();
            // throw new ValidationException("TraversableResolver isReachable caused an exception", e);
            sw.println("throw new ValidationException(\"TraversableResolver isCascadable caused an "
                    + "exception\", e);");
            // }
            sw.outdent();
            sw.println("}");
            // if (isCascadable) {
            sw.println("if (isCascadable) {");
            sw.indent();

            if (isIterableOrMap(elementClass)) {
                final JClassType associationType = this.beanHelper.getAssociationType(ppropertyDescription,
                        useField);
                this.createBeanHelper(associationType);
                if (Map.class.isAssignableFrom(elementClass)) {
                    this.writeValidateMap(sw, ppropertyDescription);
                } else {
                    this.writeValidateIterable(sw, ppropertyDescription);
                }
            } else {
                this.createBeanHelper(elementClass);

                // if (!context.alreadyValidated(value)) {
                sw.println(" if (!context.alreadyValidated(value)) {");
                sw.indent();

                // violations.addAll(myContext.getValidator().validate(context, value,
                // groups));
                sw.print("violations.addAll(");
                sw.println("myContext.getValidator().validate(myContext, value, groups));");

                // }
                sw.outdent();
                sw.println("}");
            }

            // }
            sw.outdent();
            sw.println("}");
            // }
            sw.outdent();
            sw.println("}");
        }

        // It is possible for an annotation with the exact same values to be set on
        // both the field and the getter.
        // Keep track of the ones we have used to make sure we don't duplicate.
        final Set<Object> includedAnnotations = Sets.newHashSet();
        int count = 0;
        for (final ConstraintDescriptor<?> constraint : ppropertyDescription.getConstraintDescriptors()) {
            if (this.areConstraintDescriptorGroupsValid(constraint)) {
                final Object annotation = constraint.getAnnotation();
                if (this.hasMatchingAnnotation(ppropertyDescription, useField, constraint)) {
                    final String constraintDescriptorVar = this
                            .constraintDescriptorVar(ppropertyDescription.getPropertyName(), count);
                    if (includedAnnotations.contains(annotation)) {
                        // The annotation has been looked at once already during this validate property call
                        // so we know the field and the getter are both annotated with the same constraint.
                        if (!useField) {
                            this.writeValidateConstraint(sw, ppropertyDescription, elementClass, constraint,
                                    constraintDescriptorVar);
                        }
                    } else {
                        if (useField) {
                            this.writeValidateConstraint(sw, ppropertyDescription, elementClass, constraint,
                                    constraintDescriptorVar);
                        } else {
                            // The annotation hasn't been looked at twice (yet) and we are validating a getter
                            // Write the call if only the getter has this constraint applied to it
                            final boolean hasField = this.beanHelper.hasField(ppropertyDescription);
                            if (!hasField || hasField
                                    && !this.hasMatchingAnnotation(ppropertyDescription, true, constraint)) {
                                this.writeValidateConstraint(sw, ppropertyDescription, elementClass, constraint,
                                        constraintDescriptorVar);
                            }
                        }
                    }
                    includedAnnotations.add(annotation);
                }
                count++;
            }
        }
        // }
        sw.outdent();
        sw.println("}");
    }
    sw.outdent();
    sw.println("}");
}

From source file:org.apache.bval.util.FieldAccess.java

/**
 * {@inheritDoc}
 */
public ElementType getElementType() {
    return ElementType.FIELD;
}

From source file:org.apache.bval.util.PropertyAccess.java

/**
 * {@inheritDoc}
 */
public ElementType getElementType() {
    return rememberField != null ? ElementType.FIELD : ElementType.METHOD;
}

From source file:org.bonitasoft.engine.bdm.CodeGenerator.java

protected void checkAnnotationTarget(final JAnnotatable annotable,
        final Class<? extends Annotation> annotationType, final Set<ElementType> supportedElementTypes) {
    if (annotable instanceof JClass && !supportedElementTypes.isEmpty()
            && !supportedElementTypes.contains(ElementType.TYPE)) {
        throw new IllegalArgumentException(annotationType.getName() + " is not supported for " + annotable);
    }//from  w  ww.j  a  v a 2s .  co  m
    if (annotable instanceof JFieldVar && !supportedElementTypes.isEmpty()
            && !supportedElementTypes.contains(ElementType.FIELD)) {
        throw new IllegalArgumentException(annotationType.getName() + " is not supported for " + annotable);
    }
    if (annotable instanceof JMethod && !supportedElementTypes.isEmpty()
            && !supportedElementTypes.contains(ElementType.METHOD)) {
        throw new IllegalArgumentException(annotationType.getName() + " is not supported for " + annotable);
    }
}

From source file:org.jgentleframework.utils.ReflectUtils.java

/**
 * Phng thc s kim tra xem <code>annotation</code> ch nh c
 * {@link Target} tng ng hp l vi i tng <code>object</code> hay
 * khng (i tng <code>object</code> c th l bt k thc th ch nh
 * no cho php annotate annotation nh/*from w  ww.  ja va2s  .  co  m*/
 * <code>Class, Interface, Annotation, Enum, Method, Field, Constructor, ...</code>
 * )
 * 
 * @param annotation
 *            i tng <code>annotation</code> cn kim tra.
 * @param obj
 *            i tng <code>object</code> cn kim tra
 * @return tr v? <b>true</b> nu c, nu khng tr v? <b>false</b>.
 */
public static boolean isValidTarget(Annotation annotation, Object obj) {

    if (annotation.annotationType().isAnnotationPresent(Target.class)) {
        Target target = annotation.annotationType().getAnnotation(Target.class);
        if (obj.getClass().isAnnotation()) {
            if (!Arrays.asList(target.value()).contains(ElementType.TYPE)
                    || !Arrays.asList(target.value()).contains(ElementType.ANNOTATION_TYPE)) {
                return false;
            }
        } else if (ReflectUtils.isCast(Constructor.class, obj)) {
            if (!Arrays.asList(target.value()).contains(ElementType.CONSTRUCTOR)) {
                return false;
            }
        } else if (ReflectUtils.isField(obj)) {
            if (!Arrays.asList(target.value()).contains(ElementType.FIELD)) {
                return false;
            }
        } else if (ReflectUtils.isMethod(obj)) {
            if (!Arrays.asList(target.value()).contains(ElementType.METHOD)) {
                return false;
            }
        } else if (ReflectUtils.isClass(obj) || ReflectUtils.isInterface(obj)) {
            if (!Arrays.asList(target.value()).contains(ElementType.TYPE)) {
                return false;
            }
        } else {
            if (!obj.getClass().isAnnotation() && !ReflectUtils.isCast(Constructor.class, obj)
                    && !ReflectUtils.isField(obj) && !ReflectUtils.isMethod(obj.getClass())
                    && !ReflectUtils.isClass(obj) && !ReflectUtils.isInterface(obj)) {
                return false;
            }
        }
    }
    return true;
}

From source file:org.springframework.data.keyvalue.riak.RiakMappedClass.java

private void initFields() {
    ReflectionUtils.doWithFields(this.clazz, new FieldCallback() {

        @Override//ww w.jav  a 2 s. com
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (!field.isAccessible())
                ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(Transient.class) || field.isSynthetic()
                    || field.getModifiers() == Modifier.FINAL || field.getModifiers() == Modifier.TRANSIENT) {
                return;
            }

            // Field can only have one of these, if more than one throw an
            // error
            List<Annotation> annots = org.springframework.data.keyvalue.riak.util.AnnotationUtils
                    .getFoundAnnotation(Id.class, Column.class, Embedded.class, Version.class, ManyToOne.class,
                            OneToMany.class, Basic.class);

            // Probably allow auto generation at some point, but for now
            // have to add one of the annotations
            if (annots.size() > 1)
                throw new IllegalArgumentException(String.format(
                        "The field %s must have only one of the following annotations: "
                                + "@Id, @Basic, @Column, @Embedded, @Version, @ManyToOne, @OneToMany",
                        field.getName()));

            Annotation annot = annots.get(0);

            if (annot.annotationType().equals(Id.class))
                RiakMappedClass.this.id = field;

            // Create a new mapped field here and then add to a list of
            // property MappedFields
            propertyFields.add(new RiakMappedField(field, annot));
        }
    });
    Map<Class<? extends Annotation>, Annotation> fieldAnnotMap = new HashMap<Class<? extends Annotation>, Annotation>();
    for (Class<? extends Annotation> a : entityAnnotations) {
        Target target = a.getAnnotation(Target.class);
        if (target != null && (ArrayUtils.contains(target.value(), ElementType.FIELD)
                || ArrayUtils.contains(target.value(), ElementType.METHOD))) {
            Annotation fieldAnnot;
            if ((fieldAnnot = this.clazz.getAnnotation(a)) != null) {
                fieldAnnotMap.put(a, fieldAnnot);
            }
        }
    }
}