List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:org.cloudifysource.dsl.internal.BaseDslScript.java
/** * Convert the value to an ExecutableDSLEntry object if object's property type is ExecutableDSLEntry or * ExecutableEntriesMap. Returns value otherwise. * * @param workDirectory/*from www .j a v a 2s . c o m*/ * workDirectory * @param object * object * @param name * property name * @param value * property value * @return The converted object * @throws IllegalAccessException * IllegalAccessException * @throws InvocationTargetException * InvocationTargetException * @throws NoSuchMethodException * NoSuchMethodException * @throws DSLValidationException * DSLValidationException */ public Object convertValueToExecutableDSLEntryIfNeeded(final File workDirectory, final Object object, final String name, final Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, DSLValidationException { final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(object, name); final Class<?> propertyType = descriptor.getPropertyType(); if (propertyType.equals(ExecutableDSLEntry.class)) { ExecutableDSLEntry entry = ExecutableDSLEntryFactory.createEntry(value, name, workDirectory); // if (entry.getEntryType() == ExecutableDSLEntryType.STRING) { // // handleDebugEntry(entry); // // } return entry; } else if (propertyType.equals(ExecutableEntriesMap.class)) { return ExecutableDSLEntryFactory.createEntriesMap(value, name, workDirectory); } else { return value; } }
From source file:org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.java
private Object getAttributeValue(PropertyDescriptor propertyDescriptor, String attributeValue) { Object attributeValueObject = null; if (propertyDescriptor != null && attributeValue != null) { Class<?> propertyType = propertyDescriptor.getPropertyType(); if (String.class.equals(propertyType)) { // it's already a String attributeValueObject = attributeValue; } // KULRICE-6808: Kim Role Maintenance - Custom boolean role qualifier values are not being converted properly else if (Boolean.class.equals(propertyType) || Boolean.TYPE.equals(propertyType)) { attributeValueObject = Truth.strToBooleanIgnoreCase(attributeValue); } else {/* w ww .j a v a 2s . c om*/ // try to create one with KRADUtils for other misc data types attributeValueObject = KRADUtils.createObject(propertyType, new Class[] { String.class }, new Object[] { attributeValue }); // if that didn't work, we'll get a null back if (attributeValueObject == null) { // this doesn't seem like a great option, since we know the property isn't of type String attributeValueObject = attributeValue; } } } return attributeValueObject; }
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClassProperty.java
/** * Constructor./* ww w.ja va 2s .c om*/ * @param domainClass * @param descriptor */ @SuppressWarnings("rawtypes") public DefaultGrailsDomainClassProperty(GrailsDomainClass domainClass, PropertyDescriptor descriptor, Map<String, Object> defaultConstraints) { this.domainClass = domainClass; name = descriptor.getName(); naturalName = GrailsNameUtils.getNaturalName(descriptor.getName()); type = descriptor.getPropertyType(); identity = descriptor.getName().equals(IDENTITY); // establish if property is persistant if (domainClass != null) { // figure out if this property is inherited if (!domainClass.isRoot()) { inherited = GrailsClassUtils.isPropertyInherited(domainClass.getClazz(), name); } List transientProps = getTransients(); checkIfTransient(transientProps); establishFetchMode(); } if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { persistent = false; } if (Errors.class.isAssignableFrom(type)) { persistent = false; } this.defaultConstraints = defaultConstraints; }
From source file:ch.ralscha.extdirectspring.util.ParametersResolver.java
private Map<String, Object> fillReadRequestFromMap(ExtDirectStoreReadRequest to, Map<String, Object> from) { Set<String> foundParameters = new HashSet<String>(); for (Entry<String, Object> entry : from.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.equals("filter")) { List<Filter> filters = new ArrayList<Filter>(); if (value instanceof String) { List<Map<String, Object>> rawFilters = this.jsonHandler.readValue((String) value, new TypeReference<List<Map<String, Object>>>() {/* empty */ });/* ww w. ja v a 2 s . c om*/ for (Map<String, Object> rawFilter : rawFilters) { Filter filter = Filter.createFilter(rawFilter, this.conversionService); if (filter != null) { filters.add(filter); } } } else if (value instanceof List) { @SuppressWarnings("unchecked") List<Map<String, Object>> filterList = (List<Map<String, Object>>) value; for (Map<String, Object> rawFilter : filterList) { Filter filter = Filter.createFilter(rawFilter, this.conversionService); if (filter != null) { filters.add(filter); } } } to.setFilters(filters); foundParameters.add(key); } else if (key.equals("sort") && value != null && value instanceof List) { List<SortInfo> sorters = new ArrayList<SortInfo>(); @SuppressWarnings("unchecked") List<Map<String, Object>> rawSorters = (List<Map<String, Object>>) value; for (Map<String, Object> aRawSorter : rawSorters) { sorters.add(SortInfo.create(aRawSorter)); } to.setSorters(sorters); foundParameters.add(key); } else if (key.equals("group") && value != null && value instanceof List) { List<GroupInfo> groups = new ArrayList<GroupInfo>(); @SuppressWarnings("unchecked") List<Map<String, Object>> rawGroups = (List<Map<String, Object>>) value; for (Map<String, Object> aRawGroupInfo : rawGroups) { groups.add(GroupInfo.create(aRawGroupInfo)); } to.setGroups(groups); foundParameters.add(key); } else { PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(to.getClass(), key); if (descriptor != null && descriptor.getWriteMethod() != null) { try { descriptor.getWriteMethod().invoke(to, this.conversionService.convert(value, descriptor.getPropertyType())); foundParameters.add(key); } catch (IllegalArgumentException e) { log.error("fillObjectFromMap", e); } catch (IllegalAccessException e) { log.error("fillObjectFromMap", e); } catch (InvocationTargetException e) { log.error("fillObjectFromMap", e); } } } } if (to.getLimit() != null) { // this test is no longer needed with extjs 4.0.7 and extjs 4.1.0 // these two libraries always send page, start and limit if (to.getPage() != null && to.getStart() == null) { to.setStart(to.getLimit() * (to.getPage() - 1)); // the else if is still valid for extjs 3 code } else if (to.getPage() == null && to.getStart() != null) { to.setPage(to.getStart() / to.getLimit() + 1); } } if (to.getSort() != null && to.getDir() != null) { List<SortInfo> sorters = new ArrayList<SortInfo>(); sorters.add(new SortInfo(to.getSort(), SortDirection.fromString(to.getDir()))); to.setSorters(sorters); } if (to.getGroupBy() != null && to.getGroupDir() != null) { List<GroupInfo> groups = new ArrayList<GroupInfo>(); groups.add(new GroupInfo(to.getGroupBy(), SortDirection.fromString(to.getGroupDir()))); to.setGroups(groups); } Map<String, Object> remainingParameters = new HashMap<String, Object>(); for (Entry<String, Object> entry : from.entrySet()) { if (!foundParameters.contains(entry.getKey())) { remainingParameters.put(entry.getKey(), entry.getValue()); } } to.setParams(remainingParameters); return remainingParameters; }
From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java
/** * Establish relationship with related domain class * * @param entity// www. j a v a 2s . co m * @param property Establishes a relationship between this class and the domain class property * @param context * @param hasOneMap */ private ToOne establishDomainClassRelationship(PersistentEntity entity, PropertyDescriptor property, MappingContext context, Map hasOneMap) { ToOne association = null; Class propType = property.getPropertyType(); ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(propType); // establish relationship to type Map relatedClassRelationships = getAllAssociationMap(cpf); Map mappedBy = cpf.getStaticPropertyValue(MAPPED_BY, Map.class); if (mappedBy == null) mappedBy = Collections.emptyMap(); Class<?> relatedClassPropertyType = null; // if there is a relationships map use that to find out // whether it is mapped to a Set String relatedClassPropertyName = null; if (!forceUnidirectional(property, mappedBy)) { if (relatedClassRelationships != null && !relatedClassRelationships.isEmpty()) { PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(entity.getJavaClass(), propType); relatedClassPropertyName = findOneToManyThatMatchesType(entity, relatedClassRelationships); // if there is only one property on many-to-one side of the relationship then // try to establish if it is bidirectional if (descriptors.length == 1 && isNotMappedToDifferentProperty(property, relatedClassPropertyName, mappedBy)) { if (StringUtils.hasText(relatedClassPropertyName)) { // get the type of the property relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName); } } // if there is more than one property on the many-to-one side then we need to either // find out if there is a mappedBy property or whether a convention is used to decide // on the mapping property else if (descriptors.length > 1) { if (mappedBy.containsValue(property.getName())) { for (Object o : mappedBy.keySet()) { String mappedByPropertyName = (String) o; if (property.getName().equals(mappedBy.get(mappedByPropertyName))) { Class<?> mappedByRelatedType = (Class<?>) relatedClassRelationships .get(mappedByPropertyName); if (mappedByRelatedType != null && propType.isAssignableFrom(mappedByRelatedType)) relatedClassPropertyType = cpf.getPropertyType(mappedByPropertyName); } } } else { String classNameAsProperty = Introspector.decapitalize(propType.getName()); if (property.getName().equals(classNameAsProperty) && !mappedBy.containsKey(relatedClassPropertyName)) { relatedClassPropertyType = cpf.getPropertyType(relatedClassPropertyName); } } } } // otherwise retrieve all the properties of the type from the associated class if (relatedClassPropertyType == null) { PropertyDescriptor[] descriptors = ReflectionUtils.getPropertiesOfType(propType, entity.getJavaClass()); // if there is only one then the association is established if (descriptors.length == 1) { relatedClassPropertyType = descriptors[0].getPropertyType(); relatedClassPropertyName = descriptors[0].getName(); } } } // establish relationship based on this type // uni-directional one-to-one final boolean isAssociationEntity = isPersistentEntity(relatedClassPropertyType); if (relatedClassPropertyType == null || isAssociationEntity) { association = propertyFactory.createOneToOne(entity, context, property); if (hasOneMap.containsKey(property.getName())) { association.setForeignKeyInChild(true); } } // bi-directional many-to-one else if (Collection.class.isAssignableFrom(relatedClassPropertyType) || Map.class.isAssignableFrom(relatedClassPropertyType)) { association = propertyFactory.createManyToOne(entity, context, property); } // bi-directional if (association != null) { PersistentEntity associatedEntity = getOrCreateAssociatedEntity(entity, context, propType); association.setAssociatedEntity(associatedEntity); boolean isNotCircular = entity != associatedEntity; if (relatedClassPropertyName != null && isNotCircular) { association.setReferencedPropertyName(relatedClassPropertyName); } } return association; }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues, String parentParamName) { if (Map.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Map not supported"); } else if (Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Collection not supported"); } else {/*from w w w. j av a 2s. c o m*/ try { Constructor[] constructors = clazz.getConstructors(); Constructor constructor = PropertyUtils.findDefaultCtor(constructors); if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found"); int parameterCount = constructor.getParameterTypes().length; Object[] args = new Object[parameterCount]; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; String paramName = jsonProperty.value(); List<String> formValue = formValues.get(parentParamName + paramName); Class<?> parameterType = parameters[paramIndex]; if (DataType.isSingleValueType(parameterType)) { if (formValue != null) { if (formValue.size() == 1) { args[paramIndex++] = DataType.asType(parameterType, formValue.get(0)); } else { // // TODO create proper collection type throw new IllegalArgumentException("variable list not supported"); // List<Object> listValue = new ArrayList<Object>(); // for (String item : formValue) { // listValue.add(DataType.asType(parameterType, formValue.get(0))); // } // args[paramIndex++] = listValue; } } else { args[paramIndex++] = null; } } else { args[paramIndex++] = recursivelyCreateObject(parameterType, formValues, parentParamName + paramName + "."); } } } } Assert.isTrue(args.length == paramIndex, "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty"); } Object ret = constructor.newInstance(args); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method writeMethod = propertyDescriptor.getWriteMethod(); String name = propertyDescriptor.getName(); List<String> strings = formValues.get(name); if (writeMethod != null && strings != null && strings.size() == 1) { writeMethod.invoke(ret, DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor } } return ret; } catch (Exception e) { throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e); } } }
From source file:de.xwic.appkit.webbase.viewer.EntityTableViewer.java
private boolean propertyExists(String propertyId) { if (propertyId == null) { return false; }/*from w w w. j a v a 2 s .com*/ StringTokenizer stk = new StringTokenizer(propertyId, "."); Class<?> clazz = daoClass.getEntityClass(); for (int nr = 0; stk.hasMoreTokens(); nr++) { PropertyDescriptor desc; try { desc = new PropertyDescriptor(stk.nextToken(), clazz); clazz = desc.getPropertyType(); } catch (IntrospectionException e) { return false; } } return true; }
From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java
/** * Recursively navigate to return a BeanWrapper for the nested property path. * * @param propertyPath property property path, which may be nested * @return a BeanWrapper for the target bean */// w w w .j av a 2 s . c o m PropertyDescriptor getPropertyDescriptorForPropertyPath(final String propertyPath, final Class<?> propertyType) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); // Handle nested properties recursively. if (pos > -1) { String nestedProperty = propertyPath.substring(0, pos); String nestedPath = propertyPath.substring(pos + 1); PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(propertyType, nestedProperty); // BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty); return getPropertyDescriptorForPropertyPath(nestedPath, propertyDescriptor.getPropertyType()); } else { return BeanUtils.getPropertyDescriptor(propertyType, propertyPath); } }
From source file:io.lightlink.dao.mapping.BeanMapper.java
public BeanMapper(Class paramClass, List<String> fieldsOfLine) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(paramClass); descriptorMap = new CaseInsensitiveMap(); for (PropertyDescriptor descriptor : descriptors) { descriptorMap.put(normalizePropertyName(descriptor.getName()), descriptor); }/*from w w w. j a v a 2s .c o m*/ List<String> ownFields = new ArrayList<String>(); Map<String, List<String>> fieldsByChild = new CaseInsensitiveMap(); groupFields(fieldsOfLine, ownFields, fieldsByChild); this.ownFields = ownFields; for (Map.Entry<String, List<String>> entry : fieldsByChild.entrySet()) { String childProperty = normalizePropertyName(entry.getKey()); PropertyDescriptor descriptor = descriptorMap.get(childProperty); if (descriptor != null) { List<String> properties = entry.getValue(); if (descriptor.getPropertyType().isAssignableFrom(ArrayList.class)) { Type[] typeArguments = ((ParameterizedType) descriptor.getReadMethod().getGenericReturnType()) .getActualTypeArguments(); if (typeArguments.length == 0) throw new RuntimeException("Cannot define Generic list type of " + entry.getKey() + " property of " + paramClass); Type firstType = typeArguments[0]; if (firstType instanceof Class) { childListMappers.put(childProperty, new BeanMapper((Class) firstType, properties)); } } else { childMappers.put(childProperty, new BeanMapper(descriptor.getPropertyType(), properties)); } } else { throw new RuntimeException( "cannot define mapping for class:" + paramClass.getName() + " property:" + childProperty); } } this.paramClass = paramClass; }
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Converts JSON types to "normal" java types. * * @param obj the object to convert (must not be * <code>null</code>, but can be * <code>JSONObject.NULL</code>). * @param targetType the desired target type (must not be * <code>null</code>). * * @return the converted object.//from w w w .jav a2s . com * * @exception IllegalArgumentException thrown if the desired * conversion is not possible. */ public Object toJava(Object obj, Class targetType) { try { if (obj == JSONObject.NULL) { if (targetType == Integer.TYPE || targetType == Double.TYPE || targetType == Boolean.TYPE || targetType == Long.TYPE || targetType == Float.TYPE) { // null does not work for primitive types throw new Exception(); } return null; } if (obj instanceof JSONArray) { Class componentType; if (targetType == null || targetType == Object.class) { componentType = null; } else { componentType = targetType.getComponentType(); } JSONArray jsonArray = (JSONArray) obj; int length = jsonArray.length(); Object retVal = Array.newInstance((componentType == null ? Object.class : componentType), length); for (int i = 0; i < length; ++i) { Array.set(retVal, i, toJava(jsonArray.get(i), componentType)); } return retVal; } if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; JSONArray names = jsonObject.names(); if (targetType == Map.class || targetType == HashMap.class || targetType == null || targetType == Object.class) { HashMap retVal = new HashMap(); if (names != null) { int length = names.length(); String name; for (int i = 0; i < length; ++i) { name = names.getString(i); retVal.put(name, toJava(jsonObject.get(name), null)); } } return retVal; } Object bean; String requestedTypeName = jsonObject.optString("class", null); if (requestedTypeName != null) { Class clazz = resolveClassHint(requestedTypeName, targetType); if (clazz == null || !targetType.isAssignableFrom(clazz)) { throw new Exception(); } bean = clazz.newInstance(); // TODO: support constructor parameters } else { bean = targetType.newInstance(); } if (names != null) { int length = names.length(); String name; PropertyDescriptor desc; for (int i = 0; i < length; ++i) { name = names.getString(i); if (!"class".equals(name)) { desc = PropertyUtils.getPropertyDescriptor(bean, name); if (desc != null && desc.getWriteMethod() != null) { PropertyUtils.setSimpleProperty(bean, name, toJava(jsonObject.get(name), desc.getPropertyType())); } } } } return bean; } if (targetType == null || targetType == Object.class) { return obj; } Class actualTargetType; Class sourceType = obj.getClass(); if (targetType == Integer.TYPE) { actualTargetType = Integer.class; } else if (targetType == Boolean.TYPE) { actualTargetType = Boolean.class; } else if ((targetType == Double.TYPE || targetType == Double.class) && Number.class.isAssignableFrom(sourceType)) { return new Double(((Number) obj).doubleValue()); // TODO: maybe return obj directly if it's a Double } else if ((targetType == Float.TYPE || targetType == Float.class) && Number.class.isAssignableFrom(sourceType)) { return new Float(((Number) obj).floatValue()); } else if ((targetType == Long.TYPE || targetType == Long.class) && Number.class.isAssignableFrom(sourceType)) { return new Long(((Number) obj).longValue()); } else { actualTargetType = targetType; } if (!actualTargetType.isAssignableFrom(sourceType)) { throw new Exception(); } return obj; } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { throw new IllegalArgumentException("Cannot convert " + (obj == null ? null : obj.getClass().getName()) + " to " + (targetType == null ? null : targetType.getName())); } }