List of usage examples for java.lang.reflect Field getAnnotations
public Annotation[] getAnnotations()
From source file:org.castor.jaxb.reflection.FieldAnnotationProcessingServiceTest.java
@Test public final void testWithXmlElements() { Class<WithXmlElements> clazz = WithXmlElements.class; Assert.assertFalse(clazz.isEnum());// w ww.ja v a 2s . co m Assert.assertNotNull(fieldAnnotationProcessingService); Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(field.getName())); fieldAnnotationProcessingService.processAnnotations(fi, field.getAnnotations()); if ("anythingInAList".equals(field.getName())) { Assert.assertTrue(fi.hasXmlElements()); // List<XmlElement> xmlElements = fi.getXmlElements(); // Assert.assertNotNull(xmlElements); } } Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(method.getName())); fieldAnnotationProcessingService.processAnnotations(fi, method.getAnnotations()); } }
From source file:com.mobsandgeeks.saripaar.Validator.java
private List<AnnotationFieldPair> getSaripaarAnnotatedFields() { List<AnnotationFieldPair> annotationFieldPairs = new ArrayList<AnnotationFieldPair>(); List<Field> fieldsWithAnnotations = getViewFieldsWithAnnotations(); for (Field field : fieldsWithAnnotations) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (isSaripaarAnnotation(annotation)) { annotationFieldPairs.add(new AnnotationFieldPair(annotation, field)); }/* ww w.j a va 2s .c o m*/ } } Collections.sort(annotationFieldPairs, new AnnotationFieldPairCompartor()); return annotationFieldPairs; }
From source file:com.hiperium.dao.common.generic.GenericDAO.java
/** * Gets the entity properties of the object. * // w ww . ja v a2s. c om * @param object * entity that contains the properties. * @param primaryKey * the primary key fields. * * @return map with the properties and values to be used in the construction * of the criteria object and the searching execution. */ @SuppressWarnings("unchecked") private <E> Map<String, Object> getEntityProperties(Object object, String... primaryKey) { Class<E> classType = (Class<E>) object.getClass(); Field[] fields = classType.getDeclaredFields(); Map<String, Object> fieldsMap = new HashMap<String, Object>(fields.length); for (Field field : fields) { Boolean isLob = Boolean.FALSE; Annotation[] annotationsArray = field.getAnnotations(); for (Annotation annotation : annotationsArray) { if ("@javax.persistence.Lob()".equals(annotation.toString()) || "@javax.persistence.Transient()".equals(annotation.toString())) { isLob = Boolean.TRUE; break; } } if (!isLob) { String fieldName = field.getName(); String methodName = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); try { Method method = classType.getMethod(methodName, new Class[] {}); Object result = method.invoke(object, new Object[] {}); if (result != null) { if (primaryKey != null && primaryKey.length == 1) { fieldsMap.put(primaryKey[0] + "." + field.getName(), result); } else { fieldsMap.put(field.getName(), result); } } } catch (RuntimeException e) { continue; } catch (NoSuchMethodException e) { continue; } catch (IllegalAccessException e) { continue; } catch (InvocationTargetException e) { continue; } } } return fieldsMap; }
From source file:org.nuunframework.cli.NuunCliPlugin.java
protected Specification<Class<?>> fieldAnnotatedWith(final Class<? extends Annotation> annotationClass) { return new AbstractSpecification<Class<?>>() { @Override//from ww w . ja v a2s . co m public boolean isSatisfiedBy(Class<?> candidate) { if (candidate != null) { try { for (Field field : candidate.getDeclaredFields()) { if (field.isAnnotationPresent(annotationClass)) { return true; } for (Annotation annotation : field.getAnnotations()) { if (hasAnnotationDeep(annotation.annotationType(), annotationClass)) { return true; } } } } catch (Throwable throwable) { logger.trace("fieldAnnotatedWith : " + candidate + " missing " + throwable); } } return false; } }; }
From source file:org.openecomp.sdnc.sli.aai.r1607.R1607AutoGeneratedTest.java
public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) {//ww w. j av a 2 s. c o m LOG.info("----------------------- Test: " + new Object() { }.getClass().getEnclosingMethod().getName() + " -----------------------"); try { Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext()); AAIRequest request = AAIRequest.createRequest(resource, nameValues); Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request == null ? GenericVnf.class : request.getModelClass()); Map<String, String> data = new HashMap<String, String>(); for (Field field : resourceClass.getDeclaredFields()) { String type = field.getType().getName(); if (type.startsWith("java.lang.")) { Annotation[] fieldAnnotations = field.getAnnotations(); for (int i = 0; i < fieldAnnotations.length; i++) { Annotation a = fieldAnnotations[i]; if (a instanceof JsonProperty) { JsonProperty pa = (JsonProperty) a; String name = pa.value(); String value; switch (type) { case "java.lang.Integer": case "java.lang.Long": value = RandomStringUtils.random(6, false, true); break; case "java.lang.Boolean": value = "false"; break; default: if (name.equals(identifier)) { value = idValue; } else { value = RandomStringUtils.random(10, true, false); } } data.put(name, value); } else if (a instanceof javax.xml.bind.annotation.XmlElement) { XmlElement xe = (XmlElement) a; String name = xe.name(); if ("link-type".equals(name)) { data.put(name, "roadmTail"); continue; } if ("operational-status".equals(name)) { data.put(name, "available"); continue; } String value; switch (type) { case "java.lang.Integer": case "java.lang.Long": value = RandomStringUtils.random(6, false, true); break; case "java.lang.Boolean": value = "false"; break; default: if (name.equals(identifier)) { value = idValue; } else { value = RandomStringUtils.random(10, true, false); } } data.put(name, value); } } } } SvcLogicContext ctx = new SvcLogicContext(); data.remove("resource-version"); QueryStatus resp = null; //(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms, String prefix, SvcLogicContext ctx) resp = client.save(resource, false, false, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx); } catch (Throwable e) { LOG.error("Caught exception", e); fail("Caught exception"); } }
From source file:windows.ValidateEntity.java
private ValidationContex validateGeneral(String[] fieldsName, String[] excludeField) { ValidationContex contex;//from w ww . ja v a 2s. co m Field[] fields; if (fieldsName == null || fieldsName.length == 0) { fields = ReflectionUtils.getAllFields(entidad.getClass()); } else { fields = new Field[fieldsName.length]; for (int i = 0; i < fieldsName.length; i++) { fields[i] = ReflectionUtils.getField(entidad, fieldsName[i]); } } for (Field field : fields) { if (excludeField != null) { boolean b = false; for (String exField : excludeField) { if (exField.equalsIgnoreCase(field.getName())) { b = true; break; } } if (b) { continue; } } Annotation[] annotation = field.getAnnotations(); if (annotation.length == 0) { continue; } contex = validateNotNull(field); if (contex != null) { return contex; } contex = validateSize(field); if (contex != null) { return contex; } contex = validateMin(field); if (contex != null) { return contex; } contex = validateMax(field); if (contex != null) { return contex; } contex = validatePattern(field); if (contex != null) { return contex; } } return null; }
From source file:eu.crisis_economics.abm.dashboard.AvailableParameter.java
public AvailableParameter(final ParameterInfo info, final Class<?> modelClass) { if (info == null) throw new IllegalArgumentException("AvailableParameter(): null parameter."); this.info = info; Class<?> parentClass = modelClass; if (info.isSubmodelParameter()) { parentClass = ((ISubmodelGUIInfo) info).getParentValue(); }/*from w w w . jav a 2s . c o m*/ Field declaredField = null; while (declaredField == null) { try { declaredField = parentClass.getDeclaredField(StringUtils.uncapitalize(info.getName())); } catch (NoSuchFieldException e) { parentClass = parentClass.getSuperclass(); if (parentClass == null) { // throw new IllegalStateException("Could not find field for parameter " + info.getName() + " in " + startClass); break; } } } if (declaredField != null) { for (final Annotation element : declaredField.getAnnotations()) { if (element.annotationType().getName() != Layout.class.getName()) // Proxies continue; final Class<? extends Annotation> type = element.annotationType(); try { displayName = (String) (type.getMethod("FieldName").invoke(element)); } catch (IllegalArgumentException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (NoSuchMethodException e) { } } } if (displayName == null) { displayName = info.getName().replaceAll("([A-Z])", " $1"); } }
From source file:com.serli.chell.framework.form.FormStructure.java
private void loadFields(Class<? extends Form> formClass) { List<FormField> fieldList = new ArrayList<FormField>(); Class<?> currentClass = formClass; Class<?> fieldType;/*from w ww. jav a 2 s . c o m*/ FormField formField; FormFieldConfiguration ffc; boolean multiValued; boolean required; long maxFileSize; do { for (Field field : currentClass.getDeclaredFields()) { fieldType = field.getType(); if (isFormField(field, fieldType)) { multiValued = isMultivaluedField(fieldType); required = isRequiredField(field, multiValued); formField = new FormField(field, multiValued, required); fieldList.add(formField); for (Annotation annotation : field.getAnnotations()) { ResourceProvider.loadResourcesFromAnnotation(resources, annotation); ffc = getFieldConfiguration(annotation); ffc.configure(formField, annotation); } if (formField.isUploadField()) { uploadForm = true; maxFileSize = formField.getUploadHandler().getMaxFileSize(); if (maxFileSize > maxUploadFileSize) { maxUploadFileSize = maxFileSize; } } if (LOGGER.isInfoEnabled()) { LOGGER.info("Loading field : " + formField); } } } currentClass = currentClass.getSuperclass(); } while (!currentClass.equals(Form.class)); Collections.sort(fieldList); for (FormField field : fieldList) { fields.put(field.getName(), field); } }
From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java
public EngineMetadata getObject() throws Exception { final Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validatorMap = getValidatorMap(); final Map<Class<?>, ClassMetadata> classMap = new HashMap<Class<?>, ClassMetadata>(); for (Class<?> clazz : m_classes) { log.debug("class name {}", clazz); boolean classNeeded = true; final ClassMetadata classMetadata = new ClassMetadata(); @SuppressWarnings("unchecked") Map<String, Property> propertyMap = ValidationUtils .getProperties((Class<? extends ValidationObject>) clazz); for (Property property : propertyMap.values()) { Method method = property.getGetter(); log.debug("method.getName() {}", method.getName()); String mname = method.getName(); final String fieldName = property.getFieldName(); final PropertyMetadataImpl fieldMetadata = new PropertyMetadataImpl(property, getMessageSource()); boolean fieldNeeded = false; boolean foundDigits = false; boolean foundLength = false; int digitsLength = -1; for (Annotation fieldAnnotation : method.getAnnotations()) { log.debug("field annotation {}", fieldAnnotation); if (fieldAnnotation instanceof Label) { fieldMetadata.setLabelName(((Label) fieldAnnotation).labelName()); fieldNeeded = true;// w w w . j a va2s .c o m } if (fieldAnnotation instanceof Inactive) { fieldMetadata.setInactive(true); fieldNeeded = true; } if (fieldAnnotation instanceof ReadOnly) { fieldMetadata.setReadOnly(true); fieldNeeded = true; } if (fieldAnnotation instanceof Secret) { fieldMetadata.setSecret(true); fieldNeeded = true; } if (fieldAnnotation instanceof Unknown) { fieldMetadata.setUnknown(true); fieldNeeded = true; } if (fieldAnnotation instanceof Required) { fieldMetadata.setRequired(true); fieldNeeded = true; } if (fieldAnnotation instanceof Digits) { fieldMetadata.setFractionalDigits(((Digits) fieldAnnotation).fractionalDigits()); fieldNeeded = true; foundDigits = true; digitsLength = Integer.parseInt(((Digits) fieldAnnotation).integerDigits()); foundLength = true; } if (fieldAnnotation instanceof Range) { fieldMetadata.setMinValue(((Range) fieldAnnotation).minInclusive()); fieldMetadata.setMaxValue(((Range) fieldAnnotation).maxInclusive()); fieldNeeded = true; } if (fieldAnnotation instanceof Description) { fieldMetadata.setDescription(((Description) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof History) { fieldMetadata.setHistory(((History) fieldAnnotation).expire(), ((History) fieldAnnotation).entries()); fieldNeeded = true; } if (fieldAnnotation instanceof Id) { fieldMetadata.setIdentifier(true); } if (fieldAnnotation instanceof Regex) { fieldMetadata.setRegex(((Regex) fieldAnnotation).pattern()); fieldNeeded = true; } // if (fieldAnnotation instanceof BeanValidator) // { // fieldMetadata.setBean(((BeanValidator)fieldAnnotation).bean()); // fieldMetadata.setParam(((BeanValidator)fieldAnnotation).param()); // fieldNeeded = true; // } if (fieldAnnotation instanceof MapField) { fieldMetadata.setMapField(((MapField) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof WritePermission) { fieldMetadata.setPermission(((WritePermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ReadPermission) { fieldMetadata.setReadPermission(((ReadPermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ChoiceList) { final List<ChoiceBase> choiceList = m_choicesMap.get(((ChoiceList) fieldAnnotation).name()); fieldMetadata.setChoiceList(choiceList); fieldNeeded = true; } if (fieldAnnotation instanceof Length) { fieldMetadata.setMaxLength(((Length) fieldAnnotation).maxLength()); fieldNeeded = true; foundLength = true; } Class<? extends FieldValidator<Annotation>> fvClass = validatorMap .get(fieldAnnotation.annotationType()); if (fvClass != null) { final FieldValidator<Annotation> fv = fvClass.newInstance(); fv.init(fieldAnnotation, fieldMetadata); fieldMetadata.addConstraintValidator(fv); fieldNeeded = true; } } Column column = method.getAnnotation(Column.class); if (column != null) { int precision = column.precision(); int fractional = column.scale(); int length = column.length(); if (!foundDigits) { if (fractional > 0) { fieldMetadata.setFractionalDigits(String.valueOf(fractional)); } } if (!foundLength) { if (precision > 0 && length == 255) { length = column.precision() + ((fractional > 0) ? 1 : 0); fieldMetadata.setMaxLength(String.valueOf(length)); } else { length = column.length(); fieldMetadata.setMaxLength(String.valueOf(length)); } } } Field field; try { field = clazz.getField(mname); for (Annotation fieldAnnotation : field.getAnnotations()) { if (fieldAnnotation instanceof XmlElement) { if (((XmlElement) fieldAnnotation).required()) { fieldMetadata.setRequired(true); fieldNeeded = true; } } } } catch (NoSuchFieldException e) { // ignore } Class<?> returnClass = method.getReturnType(); Object[] t = returnClass.getEnumConstants(); if (t != null) { fieldNeeded = true; fieldMetadata.setChoiceList(t); } if (!fieldNeeded) { if (m_classes.contains(returnClass) || returnClass.isAssignableFrom(List.class)) { fieldNeeded = true; } } if (fieldNeeded) { log.debug("fieldName added to metadata {}.{}", clazz.getName(), fieldName); classMetadata.addField(fieldName, fieldMetadata); classNeeded = true; } else { log.debug("fieldName not needed {}.{}", clazz.getName(), fieldName); } } if (classNeeded) { log.debug("Class added to metadata {}", clazz.getName()); classMap.put(clazz, classMetadata); } } return new EngineMetadata(classMap, m_choicesDoc); }
From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java
private static void addFields(Class entity, EntityDocModel docModel) { if (entity != null) { Field[] fields = entity.getDeclaredFields(); for (Field field : fields) { //Skip static field if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) { EntityFieldModel fieldModel = new EntityFieldModel(); fieldModel.setName(field.getName()); fieldModel.setType(field.getType().getSimpleName()); fieldModel.setOriginClass(entity.getSimpleName()); fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType())); if (ReflectionUtil.isCollectionClass(field.getType())) { DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); }/*ww w .j ava 2 s . c om*/ fieldModel.setGenericType(typeClass); } } APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class); if (description != null) { fieldModel.setDescription(description.value()); } for (Annotation annotation : field.getAnnotations()) { if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) { EntityConstraintModel entityConstraintModel = new EntityConstraintModel(); entityConstraintModel.setName(annotation.annotationType().getSimpleName()); APIDescription annotationDescription = (APIDescription) annotation.annotationType() .getAnnotation(APIDescription.class); if (annotationDescription != null) { entityConstraintModel.setDescription(annotationDescription.value()); } //rules Object annObj = field.getAnnotation(annotation.annotationType()); if (annObj instanceof NotNull) { entityConstraintModel.setRules("Field is required"); } else if (annObj instanceof PK) { PK pk = (PK) annObj; entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated()); fieldModel.setPrimaryKey(true); } else if (annObj instanceof FK) { FK fk = (FK) annObj; StringBuilder sb = new StringBuilder(); sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName()); sb.append(" (<b>Enforce</b>: ").append(fk.enforce()); sb.append(" <b>Soft reference</b>: ").append(fk.softReference()); if (StringUtils.isNotBlank(fk.referencedField())) { sb.append(" <b>Reference Field</b>: ").append(fk.referencedField()); } sb.append(" )"); entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof ConsumeField) { entityConstraintModel.setRules(""); } else if (annObj instanceof Size) { Size size = (Size) annObj; entityConstraintModel .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max()); } else if (annObj instanceof Pattern) { Pattern pattern = (Pattern) annObj; entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp()); } else if (annObj instanceof Sanitize) { Sanitize sanitize = (Sanitize) annObj; entityConstraintModel .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName()); } else if (annObj instanceof Unique) { Unique unique = (Unique) annObj; entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName()); } else if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; StringBuilder sb = new StringBuilder(); if (validValueType.value().length > 0) { sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value())); } if (validValueType.lookupClass().length > 0) { sb.append(" <b>Lookups:</b> "); for (Class lookupClass : validValueType.lookupClass()) { sb.append(lookupClass.getSimpleName()).append(" "); } } if (validValueType.enumClass().length > 0) { sb.append(" <b>Enumerations:</b> "); for (Class enumClass : validValueType.enumClass()) { sb.append(enumClass.getSimpleName()).append(" ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } } entityConstraintModel.setRules(sb.toString()); } else if (annObj instanceof Min) { Min min = (Min) annObj; entityConstraintModel.setRules("<b>Min value:</b> " + min.value()); } else if (annObj instanceof Max) { Max max = (Max) annObj; entityConstraintModel.setRules("<b>Max value:</b> " + max.value()); } else if (annObj instanceof Version) { entityConstraintModel.setRules("Entity version; For Multi-Version control"); } else if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; String typeClass = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeClass = dataType.actualClassName(); } entityConstraintModel.setRules("<b>Type:</b> " + typeClass); } else { entityConstraintModel.setRules(annotation.toString()); } //Annotations that have related classes if (annObj instanceof DataType) { DataType dataType = (DataType) annObj; entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName()); } if (annObj instanceof FK) { FK fk = (FK) annObj; entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName()); } if (annObj instanceof ValidValueType) { ValidValueType validValueType = (ValidValueType) annObj; for (Class lookupClass : validValueType.lookupClass()) { entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName()); } StringBuilder sb = new StringBuilder(); for (Class enumClass : validValueType.enumClass()) { sb.append("<br>"); sb.append(enumClass.getSimpleName()).append(": ("); sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")"); } entityConstraintModel .setRules(entityConstraintModel.getRules() + " " + sb.toString()); } fieldModel.getConstraints().add(entityConstraintModel); } } docModel.getFieldModels().add(fieldModel); } } addFields(entity.getSuperclass(), docModel); } }