List of usage examples for org.apache.commons.lang3.reflect FieldUtils getAllFields
public static Field[] getAllFields(final Class<?> cls)
From source file:lite.flow.runtime.kiss.ComponentUtil.java
public static void injectOutput(String outputName, Output<?> output, Object componentInstance) throws IllegalArgumentException, IllegalAccessException { Class<?> componentClazz = componentInstance.getClass(); // find activity all Output type fields for (Field field : FieldUtils.getAllFields(componentClazz)) { Class<?> decl = field.getType(); if (Output.class.isAssignableFrom(decl)) { String name = field.getName(); if (name != null && name.equals(outputName)) { field.setAccessible(true); field.set(componentInstance, output); return; }//from w ww. ja v a 2s.co m } } throw new IllegalArgumentException( format("Class '%s' do not contain output '%s'", componentClazz.getName(), outputName)); }
From source file:com.microsoft.rest.Validator.java
/** * Validates a user provided required parameter to be not null. * A {@link ServiceException} is thrown if a property fails the validation. * * @param parameter the parameter to validate * @throws ServiceException failures wrapped in {@link ServiceException} *//* w w w.j a v a 2 s . c o m*/ public static void validate(Object parameter) throws ServiceException { // Validation of top level payload is done outside if (parameter == null) { return; } Class parameterType = parameter.getClass(); if (ClassUtils.isPrimitiveOrWrapper(parameterType) || parameterType.isEnum() || ClassUtils.isAssignable(parameterType, LocalDate.class) || ClassUtils.isAssignable(parameterType, DateTime.class) || ClassUtils.isAssignable(parameterType, String.class) || ClassUtils.isAssignable(parameterType, DateTimeRfc1123.class) || ClassUtils.isAssignable(parameterType, Period.class)) { return; } Field[] fields = FieldUtils.getAllFields(parameterType); for (Field field : fields) { field.setAccessible(true); JsonProperty annotation = field.getAnnotation(JsonProperty.class); Object property; try { property = field.get(parameter); } catch (IllegalAccessException e) { throw new ServiceException(e); } if (property == null) { if (annotation != null && annotation.required()) { throw new ServiceException( new IllegalArgumentException(field.getName() + " is required and cannot be null.")); } } else { try { Class propertyType = property.getClass(); if (ClassUtils.isAssignable(propertyType, List.class)) { List<?> items = (List<?>) property; for (Object item : items) { Validator.validate(item); } } else if (ClassUtils.isAssignable(propertyType, Map.class)) { Map<?, ?> entries = (Map<?, ?>) property; for (Map.Entry<?, ?> entry : entries.entrySet()) { Validator.validate(entry.getKey()); Validator.validate(entry.getValue()); } } else if (parameter.getClass().getDeclaringClass() != propertyType) { Validator.validate(property); } } catch (ServiceException ex) { IllegalArgumentException cause = (IllegalArgumentException) (ex.getCause()); if (cause != null) { // Build property chain throw new ServiceException( new IllegalArgumentException(field.getName() + "." + cause.getMessage())); } else { throw ex; } } } } }
From source file:com.opencsv.bean.MappingUtils.java
/** * Determines which mapping strategy is appropriate for this bean. * The algorithm is:<ol>//w w w .j ava 2 s . c o m * <li>If annotations {@link CsvBindByPosition} or * {@link CsvCustomBindByPosition} are present, * {@link ColumnPositionMappingStrategy} is chosen.</li> * <li>Otherwise, {@link HeaderColumnNameMappingStrategy} is chosen. If * annotations are present, they will be used, otherwise the field names * will be used as the column names.</li></ol> * * @param <T> The type of the bean for which the mapping strategy is sought * @param type The class of the bean for which the mapping strategy is sought * @return A functional mapping strategy for the bean in question */ public static <T> MappingStrategy<T> determineMappingStrategy(Class type) { // Check for annotations Field[] fields = FieldUtils.getAllFields(type); boolean positionAnnotationsPresent = false; for (Field field : fields) { if (field.isAnnotationPresent(CsvBindByPosition.class) || field.isAnnotationPresent(CsvCustomBindByPosition.class)) { positionAnnotationsPresent = true; break; } if (positionAnnotationsPresent) { break; } } // Set the mapping strategy according to what we've found. MappingStrategy<T> mappingStrategy; if (positionAnnotationsPresent) { ColumnPositionMappingStrategy<T> ms = new ColumnPositionMappingStrategy<T>(); ms.setType(type); mappingStrategy = ms; } else { HeaderColumnNameMappingStrategy<T> ms = new HeaderColumnNameMappingStrategy<T>(); ms.setType(type); // Ugly hack, but I have to get the field names into the stupid // strategy somehow. if (!ms.isAnnotationDriven()) { SortedSet<String> sortedFields = new TreeSet<String>(); for (Field f : fields) { if (!f.isSynthetic()) { // Otherwise JaCoCo breaks tests sortedFields.add(f.getName()); } } String header = StringUtils.join(sortedFields, ',').concat("\n"); try { ms.captureHeader(new CSVReader(new StringReader(header))); ms.findDescriptor(0); } catch (IOException e) { // Can't happen. It's a StringReader with a defined string. } catch (IntrospectionException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(""); csve.initCause(e); throw csve; } } mappingStrategy = ms; } return mappingStrategy; }
From source file:io.github.moosbusch.permagon.configuration.controller.spi.AbstractPermagonController.java
@Override public void registerMembers() { Field[] fields = FieldUtils.getAllFields(getClass()); for (Field field : fields) { FXML fxml = field.getAnnotation(FXML.class); if (fxml != null) { String fieldName = field.getName(); Object fieldValue = null; try { field.setAccessible(true); fieldValue = field.get(this); } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(AbstractPermagonController.class.getName()).log(Level.SEVERE, null, ex); } finally { if (fieldValue != null) { appCtx.getBeanFactory().registerSingleton(fieldName, fieldValue); }// www . ja v a 2s . c om } } } }
From source file:com.github.srgg.springmockito.MockitoPropagatingFactoryPostProcessor.java
@Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { final Map<Field, Object> fields = new LinkedHashMap(); for (Object c : contexts) { for (Field f : FieldUtils.getAllFields(c.getClass())) { if (f.isAnnotationPresent(Mock.class) || f.isAnnotationPresent(Spy.class) || includeInjectMocks && f.isAnnotationPresent(InjectMocks.class)) { try { if (!f.isAccessible()) { f.setAccessible(true); }//ww w . jav a2 s .c om Object o = f.get(c); fields.put(f, o); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } } for (final Map.Entry<Field, Object> e : fields.entrySet()) { final Field f = e.getKey(); /* * To be processed by BeanPostProcessors, value must be an instance of FactoryBean */ final FactoryBean fb = new SimpleHolderFactoryBean(e.getValue()); beanFactory.registerSingleton(f.getName(), fb); } }
From source file:com.hlex.ondb.entity.AnnoEntityHelper.java
/** * Seek for @Major key and create/*from w w w. j a v a 2s . co m*/ * "fieldname/fieldvalue/fieldname/fieldvalue/" * * * @param type FindingAnnoation Target : MajorKey or MinorKey * @return * @throws com.hlex.ondb.exception.NullKeyException */ public List<String> getKeyByAnnotation(Object o, Class<? extends Annotation> type) throws NullKeyException { //returned variable List<String> key = new ArrayList(); //field all field for @MajorKey Field[] fs = FieldUtils.getAllFields(o.getClass()); for (Field f : fs) { Annotation mjk = f.getAnnotation(type); Object value = null; if (mjk != null) { try { value = FieldUtils.readField(o, f.getName(), true); //null value case if (value == null) { throw new NullKeyException(f.getName() + " has null value"); } //add /fieldname/fieldvalue key.add(f.getName()); key.add(value.toString()); } catch (IllegalAccessException ex) { Logger.getLogger(AnnoEntityHelper.class.getName()).log(Level.SEVERE, null, ex); } } } //no @majorkey case if (key.isEmpty()) { throw new NullKeyException("no " + type.getSimpleName() + " key"); } return key; }
From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.EntitlementItemAttributeDataInitializer.java
@Override public Collection<EntitlementItemAttribute> create() { ArrayList<EntitlementItemAttribute> attributes = new ArrayList<>(); // Software License EntitlementType sl = entitlementTypeDataInitializer.getByName("SL"); // Software License - Item Attributes Field[] itemFields = FieldUtils.getAllFields(SoftwareLicenseEntitlementItem.class); sl.setItemAttributes(new ArrayList<>(itemFields.length)); for (Field itemField : itemFields) { if (!Modifier.isStatic(itemField.getModifiers()) && // Exclusion from JPA annotations CollectionUtils.isEmpty(CollectionUtils.intersection( // Annotations Arrays.asList(itemField.getAnnotations()).stream() .map(annotation -> annotation.annotationType()).collect(Collectors.toList()), // Exclusions EXCLUSION_PROPERTY_ATTRIBUTES))) sl.getItemAttributes()//from ww w . ja v a2 s . c o m .add(generateEntitlementAttributes(itemField, new EntitlementItemAttribute())); } for (EntitlementItemAttribute itemAttribute : sl.getItemAttributes()) { itemAttribute.setEntitlementType(sl); attributes.add(itemAttribute); } return attributes; }
From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.EntitlementHeaderAttributeDataInitializer.java
@Override public Collection<EntitlementHeaderAttribute> create() { ArrayList<EntitlementHeaderAttribute> attributes = new ArrayList<>(); // Software License EntitlementType sl = entitlementTypeDataInitializer.getByName("SL"); // Software License - Header Attributes Field[] headerFields = FieldUtils.getAllFields(SoftwareLicenseEntitlementHeader.class); sl.setHeaderAttributes(new ArrayList<>(headerFields.length)); for (Field headerField : headerFields) { if (!Modifier.isStatic(headerField.getModifiers()) && // Exclusion from JPA annotations CollectionUtils.isEmpty(CollectionUtils.intersection( // Annotations Arrays.asList(headerField.getAnnotations()).stream() .map(annotation -> annotation.annotationType()).collect(Collectors.toList()), // Exclusions EXCLUSION_PROPERTY_ATTRIBUTES))) sl.getHeaderAttributes()//from ww w .j a v a2s .c om .add(generateEntitlementAttributes(headerField, new EntitlementHeaderAttribute())); } for (EntitlementHeaderAttribute headerAttribute : sl.getHeaderAttributes()) { headerAttribute.setEntitlementType(sl); attributes.add(headerAttribute); } return attributes; }
From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java
public static Map<String, Object> getBXMLFieldValues(Bindable obj) throws IllegalAccessException { Map<String, Object> result = new HashMap<>(); Class<?> type = obj.getClass(); Field[] allFields = FieldUtils.getAllFields(type); if (ArrayUtils.isNotEmpty(allFields)) { for (Field field : allFields) { BXML bxmlAnnotation = field.getAnnotation(BXML.class); if (bxmlAnnotation != null) { String id = bxmlAnnotation.id(); Object fieldValue = FieldUtils.readField(field, obj, true); if (StringUtils.isNotBlank(id)) { result.put(id, fieldValue); } else { result.put(field.getName(), fieldValue); }//from ww w .jav a 2 s . c o m } } } return result; }
From source file:org.force66.vobase.ValueObjectUtils.java
protected static void copyAllFields(Object source, Object target) { Validate.notNull(source, "Null source object fields can't be copied"); Validate.notNull(target, "Null target object fields can't be copied"); Validate.isTrue(ClassUtils.isAssignable(target.getClass(), source.getClass()), "Source and target classes must be assignable"); Object value = null;/*w w w. jav a2 s . c o m*/ for (Field field : FieldUtils.getAllFields(source.getClass())) { if (!Modifier.isFinal(field.getModifiers())) { value = copyField(source, target, value, field); } } }