List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptor
@Nullable public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String propertyName) throws BeansException
From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java
private boolean isCandidateForBinding(PropertyValue pv) { boolean isCandidate = true; final Object value = pv.getValue(); if (value instanceof GrailsParameterMap || value instanceof JSONObject) { isCandidate = false;//w ww . j a v a2s . c o m } else if (value instanceof Map) { isCandidate = false; final String propertyName = pv.getName(); final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(getTarget().getClass(), propertyName); if (property != null) { final Class<?> propertyType = property.getPropertyType(); if (propertyType.isAssignableFrom(value.getClass())) { isCandidate = true; } } } return isCandidate; }
From source file:org.fao.geonet.api.records.formatters.groovy.template.TRenderContext.java
private Object safeGetProperty(@Nonnull Object value, String prop) throws InvocationTargetException, IllegalAccessException { prop = prop.trim();/* w w w . j a v a 2 s . com*/ if (prop.trim().isEmpty()) { throw new EmptyPropertyException(); } if (value instanceof GPathResult) { GPathResult result = (GPathResult) value; if (prop.replace("\\s+", "").equals("name()")) { return result.name(); } return result.getProperty(prop); } if (value instanceof Map) { Map map = (Map) value; return map.get(prop); } else if (value instanceof List) { List list = (List) value; try { return list.get(Integer.parseInt(prop)); } catch (NumberFormatException e) { throw new IllegalArgumentException("When accessing a list the property must be a number. Property:" + prop + ". List: " + list); } } else { final PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(value.getClass(), prop.trim()); if (propertyDescriptor == null) { try { final Field declaredField = value.getClass().getDeclaredField(prop.trim()); declaredField.setAccessible(true); return declaredField.get(value); } catch (NoSuchFieldException e) { // skip } throw new NoSuchPropertyException(prop + " on object: " + value + " (" + value.getClass() + ")"); } Method method = propertyDescriptor.getReadMethod(); method.setAccessible(true); value = method.invoke(value); return value; } }
From source file:org.geomajas.internal.service.DtoConverterServiceImpl.java
private Object getBeanProperty(Object bean, String property) throws GeomajasException { PropertyDescriptor d = BeanUtils.getPropertyDescriptor(bean.getClass(), property); if (d != null) { Method m = d.getReadMethod(); if (m != null) { if (!Modifier.isPublic(m.getDeclaringClass().getModifiers())) { m.setAccessible(true);//w w w .j a va 2 s.c om } Object value; try { value = m.invoke(bean); } catch (Exception e) { // NOSONAR throw new GeomajasException(e); } return value; } } return null; }
From source file:org.medici.bia.common.util.ListBeanUtils.java
/** * Method to obtains a list of a specific field contained in input list * inputObject. This method is able to manage simple property and nested * property (first level only ndr). //from www .ja v a 2 s. c o m * * @param inputList * List object containing beans having the field to extract. * @param fieldName Field name to extract * @return List<Object> Result list containing the specific input field of input list. **/ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<?> transformList(List inputList, String fieldName) { if (inputList == null || inputList.size() == 0) { return new ArrayList<Object>(0); } List retValue = new ArrayList(inputList.size()); if (!StringUtils.contains(fieldName, ".")) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(inputList.get(0).getClass(), fieldName); Method method = pd.getReadMethod(); for (int i = 0; i < inputList.size(); i++) { try { retValue.add(i, method.invoke(inputList.get(i), (Object[]) null)); if ((ObjectUtils.toString(retValue.get(i)).equals("0")) || ((ObjectUtils.toString(retValue.get(i)).equals("")))) { retValue.set(i, ""); } } catch (IllegalAccessException iaex) { retValue.set(i, null); } catch (InvocationTargetException itex) { retValue.set(i, null); } } } return retValue; }
From source file:org.medici.bia.common.util.ListBeanUtils.java
/** * Method to obtains a plain list of multiple fields contained in a bean input list. * The fields are marked by third parameter which is the separator. * The outputString// ww w. j a v a 2s. c o m * * @param beansList List of bean from which we estract the plain list of multiple fields. * @param concatenatedFields List of bean's fields we want to concatenate in outputlist * @param fieldsSeparator String Separator of previous parameter * @param outputFieldsSeparator Separator of fields in output list * @param addBlankSpace A boolean parameter to insert a blank space before and after every separatore of output fields * @param excludeZero If a field is numeric and his value is 0, the field is discarded from output. * @return */ public static List<String> toStringListWithConcatenationFields(List<?> beansList, String concatenatedFields, String fieldsSeparator, String outputFieldsSeparator, Boolean addBlankSpace, Boolean excludeZero) { if (beansList == null) { return new ArrayList<String>(0); } if ((beansList.size() == 0) || (StringUtils.isEmpty(fieldsSeparator)) || (StringUtils.isEmpty(outputFieldsSeparator))) { return new ArrayList<String>(0); } List<String> retValue = new ArrayList<String>(beansList.size()); String[] fields = StringTokenizerUtils.tokenizeToArray(concatenatedFields, fieldsSeparator); StringBuilder stringBuilder = null; for (int i = 0; i < beansList.size(); i++) { stringBuilder = new StringBuilder(0); for (int j = 0; j < fields.length; j++) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(beansList.get(0).getClass(), fields[j]); Method method = pd.getReadMethod(); try { Object fieldBeanValue = method.invoke(beansList.get(i), (Object[]) null); if (fieldBeanValue != null) { if (fieldBeanValue.getClass().equals(Integer.class)) { if (excludeZero.equals(Boolean.TRUE)) { if (fieldBeanValue.equals(0)) { continue; } } } if (j > 0) { if (addBlankSpace) { stringBuilder.append(' '); stringBuilder.append(outputFieldsSeparator); stringBuilder.append(' '); } else { stringBuilder.append(outputFieldsSeparator); } } stringBuilder.append(fieldBeanValue.toString()); } } catch (IllegalAccessException iaex) { retValue.set(i, null); } catch (InvocationTargetException itex) { retValue.set(i, null); } } retValue.add(i, stringBuilder.toString()); } return retValue; }
From source file:org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader.java
/** * Handles the given <property> element and updates the given bean validation configuration with the property * validation rules.//from www. j a va 2 s .com * * @param propertyDefinition The <property> element. * @param clazz The validated class. * @param configuration The bean validation configuration to update. */ protected void handlePropertyDefinition(Element propertyDefinition, Class clazz, MutableBeanValidationConfiguration configuration) { String propertyName = propertyDefinition.getAttribute(NAME_ATTR); if (propertyName == null) { logger.error("Could not parse property element. Missing 'name' attribute"); throw new ValidationConfigurationException( "Could not parse property element. Missing 'name' attribute"); } PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(clazz, propertyName); if (propertyDescriptor == null) { logger.error("Property '" + propertyName + "' does not exist in class '" + clazz.getName() + "'"); } if (propertyDefinition.hasAttribute(CASCADE_ATTR) && "true".equals(propertyDefinition.getAttribute(CASCADE_ATTR))) { CascadeValidation cascadeValidation = new CascadeValidation(propertyName); if (propertyDefinition.hasAttribute(CASCADE_CONDITION_ATTR)) { String conditionExpression = propertyDefinition.getAttribute(CASCADE_CONDITION_ATTR); cascadeValidation.setApplicabilityCondition(conditionExpressionParser.parse(conditionExpression)); } configuration.addCascadeValidation(cascadeValidation); } NodeList nodes = propertyDefinition.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element ruleDefinition = (Element) node; PropertyValidationElementHandler handler = handlerRegistry.findPropertyHandler(ruleDefinition, clazz, propertyDescriptor); if (handler == null) { logger.error("Could not handle element '" + ruleDefinition.getTagName() + "'. Please make sure the proper validation rule definition handler is registered"); throw new ValidationConfigurationException( "Could not handle element '" + ruleDefinition.getTagName() + "'"); } handler.handle(ruleDefinition, propertyName, configuration); } }
From source file:ubic.gemma.security.authorization.acl.AclAdvice.java
/** * Walk the tree of associations and add (or update) acls. * //from www .j av a2 s . co m * @param methodName method name * @param object * @param previousParent The parent ACL of the given object (if it is a Securable) or of the last visited Securable. * @see AuditAdvice for similar code for Auditing */ @SuppressWarnings("unchecked") private void processAssociations(String methodName, Object object, Acl previousParent) { if (canSkipAclCheck(object)) { return; } EntityPersister persister = crudUtils.getEntityPersister(object); if (persister == null) { log.error("No Entity Persister found for " + object.getClass().getName()); return; } CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles(); String[] propertyNames = persister.getPropertyNames(); Acl parentAcl = chooseParentForAssociations(object, previousParent); for (int j = 0; j < propertyNames.length; j++) { CascadeStyle cs = cascadeStyles[j]; String propertyName = propertyNames[j]; // log.warn( propertyName ); /* * The goal here is to avoid following associations that don't need to be checked. Unfortunately, this can * be a bit tricky because there are exceptions. This is kind of inelegant, but the alternative is to check * _every_ association, which will often not be reachable. */ if (!specialCaseForAssociationFollow(object, propertyName) && (canSkipAssociationCheck(object, propertyName) || !crudUtils.needCascade(methodName, cs))) { continue; } PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(object.getClass(), propertyName); Object associatedObject = null; try { associatedObject = ReflectionUtil.getProperty(object, descriptor); } catch (Exception e) { log.error("Error while processing: " + object.getClass() + " --> " + propertyName); throw (new RuntimeException(e)); } if (associatedObject == null) continue; Class<?> propertyType = descriptor.getPropertyType(); if (associatedObject instanceof Collection) { Collection<Object> associatedObjects = (Collection<Object>) associatedObject; try { for (Object object2 : associatedObjects) { if (Securable.class.isAssignableFrom(object2.getClass())) { addOrUpdateAcl((Securable) object2, parentAcl); } processAssociations(methodName, object2, parentAcl); } } catch (LazyInitializationException ok) { /* * This is not a problem. If this was reached via a create, the associated objects must not be new * so they should already have acls. */ // log.warn( "oops" ); } } else { if (Securable.class.isAssignableFrom(propertyType)) { addOrUpdateAcl((Securable) associatedObject, parentAcl); } processAssociations(methodName, associatedObject, parentAcl); } } }