List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:org.openspotlight.persist.support.SimplePersistImpl.java
private <T> void fillBeanSimpleProperties(final StorageNode node, final T bean, final List<PropertyDescriptor> simplePropertiesDescriptor) throws Exception { for (final PropertyDescriptor descriptor : simplePropertiesDescriptor) { final String value = node.getPropertyValueAsString(currentSession, descriptor.getName()); if (value == null && descriptor.getPropertyType().isPrimitive()) { continue; }/*from w w w . ja v a 2 s . co m*/ descriptor.getWriteMethod().invoke(bean, Conversion.convert(value, descriptor.getPropertyType())); } }
From source file:org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceBase.java
protected List<RemotableAttributeError> validateDataDictionaryAttribute(KimTypeAttribute attr, String key, String value) {//from w w w . ja v a 2s . c o m try { // create an object of the proper type per the component Object componentObject = Class.forName(attr.getKimAttribute().getComponentName()).newInstance(); if (attr.getKimAttribute().getAttributeName() != null) { // get the bean utils descriptor for accessing the attribute on that object PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(componentObject, attr.getKimAttribute().getAttributeName()); if (propertyDescriptor != null) { // set the value on the object so that it can be checked Object attributeValue = KRADUtils.hydrateAttributeValue(propertyDescriptor.getPropertyType(), value); if (attributeValue == null) { attributeValue = value; // not a super-awesome fallback strategy, but... } propertyDescriptor.getWriteMethod().invoke(componentObject, attributeValue); return validateDataDictionaryAttribute(attr.getKimTypeId(), attr.getKimAttribute().getComponentName(), componentObject, propertyDescriptor); } } } catch (Exception e) { throw new KimTypeAttributeValidationException(e); } return Collections.emptyList(); }
From source file:com.complexible.pinto.RDFMapper.java
private Class pinpointClass(final Model theGraph, final Resource theResource, final PropertyDescriptor theDescriptor) { Class aClass = theDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(aClass)) { // if the field we're assigning from is a collection, try and figure out the type of the thing // we're creating from the collection Type[] aTypes = null;/* w w w . j a v a 2 s . c o m*/ if (theDescriptor.getReadMethod().getGenericParameterTypes().length > 0) { // should this be the return type? eg new Type[] { theDescriptor.getReadMethod().getGenericReturnType() }; aTypes = theDescriptor.getReadMethod().getGenericParameterTypes(); } else if (theDescriptor.getWriteMethod().getGenericParameterTypes().length > 0) { aTypes = theDescriptor.getWriteMethod().getGenericParameterTypes(); } if (aTypes != null && aTypes.length >= 1) { // first type argument to a collection is usually the one we care most about if (aTypes[0] instanceof ParameterizedType && ((ParameterizedType) aTypes[0]).getActualTypeArguments().length > 0) { Type aType = ((ParameterizedType) aTypes[0]).getActualTypeArguments()[0]; if (aType instanceof Class) { aClass = (Class) aType; } else if (aType instanceof WildcardTypeImpl) { WildcardTypeImpl aWildcard = (WildcardTypeImpl) aType; // trying to suss out super v extends w/o resorting to string munging. if (aWildcard.getLowerBounds().length == 0 && aWildcard.getUpperBounds().length > 0) { // no lower bounds afaik indicates ? extends Foo aClass = ((Class) aWildcard.getUpperBounds()[0]); } else if (aWildcard.getLowerBounds().length > 0) { // lower & upper bounds I believe indicates something of the form Foo super Bar aClass = ((Class) aWildcard.getLowerBounds()[0]); } else { // shoot, we'll try the string hack that Adrian posted on the mailing list. try { aClass = Class.forName(aType.toString().split(" ")[2].substring(0, aTypes[0].toString().split(" ")[2].length() - 1)); } catch (Exception e) { // everything has failed, let aClass be the default (theClass) and hope for the best } } } else { // punt? wtf else could it be? try { aClass = Class.forName(aType.toString()); } catch (ClassNotFoundException e) { // oh well, we did the best we can } } } else if (aTypes[0] instanceof Class) { aClass = (Class) aTypes[0]; } } else { LOGGER.info("Could not find type for collection %s", aClass); } } else if (!Classes.isInstantiable(aClass) || !Classes.hasDefaultConstructor(aClass)) { Class<?> aCurr = null; final Iterable<Resource> aRdfTypes = Models2.getTypes(theGraph, theResource); for (Resource aType : aRdfTypes) { Class<?> aMappedClass = mMappings.get(aType); if (aMappedClass != null) { if (aCurr == null) { aCurr = aMappedClass; } else if (aCurr.isAssignableFrom(aMappedClass)) { // we want the most specific class, that's likely to be what's instantiable aCurr = aMappedClass; } } } if (aCurr != null) { aClass = aCurr; } } return aClass; }
From source file:com.mx.core.dao.BeanPropRowMap.java
/** * Extract the values for all columns in the current row. * <p>Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData/*from w ww .jav a 2 s .c om*/ */ public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index); PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase()); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (logger.isDebugEnabled() && rowNumber == 0) { //logger.debug("Mapping column '" + column + "' to property '" + // pd.getName() + "' of type " + pd.getPropertyType()); } try { bw.setPropertyValue(pd.getName(), value); } catch (TypeMismatchException e) { if (value == null && primitivesDefaultedForNullValue) { logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() + " on object: " + mappedObject); } else { throw e; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + pd.getName(), ex); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; }
From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java
public void updateSymbols() throws Exception { if (!compilablePropertySourceValuesMap.isEmpty()) { PropertyDescriptor[] propertyDescriptors = CachedIntrospector.getBeanInfo(getClass()) .getPropertyDescriptors(); for (Entry<String, Object> propertySource : compilablePropertySourceValuesMap.entrySet()) { String propertyName = propertySource.getKey(); Object propertyValue = propertySource.getValue(); PropertyDescriptor propertyDescriptor = findPropertyDescriptor(propertyDescriptors, propertyName); Class<?> propertyType = propertyDescriptor.getPropertyType(); Object newValue = compileProperty(propertyType, propertyName, propertyValue); propertyDescriptor.getWriteMethod().invoke(this, newValue); }/*ww w .j a v a 2s . co m*/ } }
From source file:it.doqui.index.ecmengine.client.webservices.AbstractWebServiceDelegateBase.java
@SuppressWarnings("unchecked") protected Object convertDTO(Object sourceDTO, Class destDTOClass) throws Exception { if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] BEGIN"); }// www.j a va2 s.c om Object destDTO = null; try { if (sourceDTO != null) { if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] converting DTO from type " + sourceDTO.getClass().getName() + " to type " + destDTOClass.getName()); } destDTO = BeanUtils.instantiateClass(destDTOClass); PropertyDescriptor[] targetpds = BeanUtils.getPropertyDescriptors(destDTOClass); PropertyDescriptor sourcepd = null; if (log.isDebugEnabled()) { log.debug(" found " + targetpds.length + " properties for type " + destDTOClass.getName()); } for (int i = 0; i < targetpds.length; i++) { if (targetpds[i].getWriteMethod() != null) { Method writeMethod = targetpds[i].getWriteMethod(); sourcepd = BeanUtils.getPropertyDescriptor(sourceDTO.getClass(), targetpds[i].getName()); if (sourcepd != null && sourcepd.getReadMethod() != null) { if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] found property: " + targetpds[i].getName()); log.debug("[" + getClass().getSimpleName() + "::convertDTO] source type: " + sourcepd.getPropertyType().getName() + ", dest type: " + targetpds[i].getPropertyType().getName()); } Method readMethod = sourcepd.getReadMethod(); Object valueObject = null; if (!BeanUtils.isSimpleProperty(targetpds[i].getPropertyType())) { if (sourcepd.getPropertyType().isArray()) { valueObject = convertDTOArray( (Object[]) readMethod.invoke(sourceDTO, new Object[] {}), targetpds[i].getPropertyType().getComponentType()); } else if (sourcepd.getPropertyType().equals(java.util.Calendar.class) && targetpds[i].getPropertyType().equals(java.util.Date.class)) { // if java.util.Calendar => convert to java.util.Date valueObject = readMethod.invoke(sourceDTO, new Object[0]); if (valueObject != null) { valueObject = ((Calendar) valueObject).getTime(); } } else if (sourcepd.getPropertyType().equals(java.util.Date.class) && targetpds[i].getPropertyType().equals(java.util.Calendar.class)) { // if java.util.Date => convert to java.util.Calendar Calendar calendar = Calendar.getInstance(); valueObject = readMethod.invoke(sourceDTO, new Object[0]); if (valueObject != null) { calendar.setTime((Date) valueObject); valueObject = calendar; } } else { valueObject = convertDTO(readMethod.invoke(sourceDTO, new Object[0]), targetpds[i].getPropertyType()); } } else { valueObject = readMethod.invoke(sourceDTO, new Object[0]); } if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] writing value: " + valueObject); } writeMethod.invoke(destDTO, new Object[] { valueObject }); } else { if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] skipping property: " + targetpds[i].getName()); } } } } } } catch (Exception e) { log.error("[" + getClass().getSimpleName() + "::convertDTO] ERROR", e); throw e; } finally { if (log.isDebugEnabled()) { log.debug("[" + getClass().getSimpleName() + "::convertDTO] END"); } } return destDTO; }
From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java
@Override public Class<?> getPropertyType(String propertyName) throws BeansException { try {/*from ww w . ja v a2 s . c o m*/ PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { return pd.getPropertyType(); } else { // Maybe an indexed/mapped property... Object value = getPropertyValue(propertyName); if (value != null) { return value.getClass(); } // Check to see if there is a custom editor, // which might give an indication on the desired target type. Class<?> editorType = guessPropertyTypeFromEditors(propertyName); if (editorType != null) { return editorType; } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; }
From source file:org.kuali.rice.krad.service.impl.PersistenceServiceOjbImpl.java
/** * * @see org.kuali.rice.krad.service.PersistenceService#allForeignKeyValuesPopulatedForReference(org.kuali.rice.krad.bo.BusinessObject, * java.lang.String)//from www .j a va 2s. c om */ @Override public boolean allForeignKeyValuesPopulatedForReference(PersistableBusinessObject bo, String referenceName) { boolean allFkeysHaveValues = true; // yelp if nulls were passed in if (bo == null) { throw new IllegalArgumentException("The Class passed in for the BusinessObject argument was null."); } if (StringUtils.isBlank(referenceName)) { throw new IllegalArgumentException( "The String passed in for the referenceName argument was null or empty."); } PropertyDescriptor propertyDescriptor = null; // make sure the attribute exists at all, throw exception if not try { propertyDescriptor = PropertyUtils.getPropertyDescriptor(bo, referenceName); } catch (Exception e) { throw new RuntimeException(e); } if (propertyDescriptor == null) { throw new ReferenceAttributeDoesntExistException("Requested attribute: '" + referenceName + "' does not exist " + "on class: '" + bo.getClass().getName() + "'."); } // get the class of the attribute name Class referenceClass = getBusinessObjectAttributeClass(bo.getClass(), referenceName); if (referenceClass == null) { referenceClass = propertyDescriptor.getPropertyType(); } // make sure the class of the attribute descends from BusinessObject, // otherwise throw an exception if (!PersistableBusinessObject.class.isAssignableFrom(referenceClass)) { throw new ObjectNotABusinessObjectRuntimeException("Attribute requested (" + referenceName + ") is of class: " + "'" + referenceClass.getName() + "' and is not a " + "descendent of BusinessObject. Only descendents of BusinessObject " + "can be used."); } // make sure the attribute designated is listed as a // reference-descriptor // on the clazz specified, otherwise throw an exception (OJB); ClassDescriptor classDescriptor = getClassDescriptor(bo.getClass()); ObjectReferenceDescriptor referenceDescriptor = classDescriptor .getObjectReferenceDescriptorByName(referenceName); if (referenceDescriptor == null) { throw new ReferenceAttributeNotAnOjbReferenceException( "Attribute requested (" + referenceName + ") is not listed " + "in OJB as a reference-descriptor for class: '" + bo.getClass().getName() + "'"); } // get the list of the foreign-keys for this reference-descriptor // (OJB) Vector fkFields = referenceDescriptor.getForeignKeyFields(); Iterator fkIterator = fkFields.iterator(); // walk through the list of the foreign keys, get their types while (fkIterator.hasNext()) { // get the field name of the fk & pk field String fkFieldName = (String) fkIterator.next(); // get the value for the fk field Object fkFieldValue = null; try { fkFieldValue = PropertyUtils.getSimpleProperty(bo, fkFieldName); } // if we cant retrieve the field value, then // it doesnt have a value catch (IllegalAccessException e) { return false; } catch (InvocationTargetException e) { return false; } catch (NoSuchMethodException e) { return false; } // test the value if (fkFieldValue == null) { return false; } else if (String.class.isAssignableFrom(fkFieldValue.getClass())) { if (StringUtils.isBlank((String) fkFieldValue)) { return false; } } } return allFkeysHaveValues; }
From source file:org.kuali.rice.krad.datadictionary.validation.AttributeValidatingTypeServiceBase.java
/** * <p>Validates a data dictionary mapped attribute for a primitive property.</p> * <p>This implementation checks that the attribute is defined using the {@link DataDictionaryService} if it is * from a specific set of types defined in TypeUtils. Then, if the value is not blank, it checks for errors by * calling//from ww w .ja va 2 s. c o m * {@link #validateAttributeFormat(org.kuali.rice.core.api.uif.RemotableAttributeField, String, String, String, String)}. * If it is blank, it checks for errors by calling * {@link #validateAttributeRequired(org.kuali.rice.core.api.uif.RemotableAttributeField, String, String, Object, String)} * .</p> * * @param typeAttributeDefinition the definition for the attribute * @param componentName the data dictionary component name * @param object the instance of the component * @param propertyDescriptor the descriptor for the property that the attribute maps to * @return a List of errors ({@link RemotableAttributeError}s) encountered during validation. Cannot return null. */ protected List<RemotableAttributeError> validatePrimitiveAttributeFromDescriptor( TypeAttributeDefinition typeAttributeDefinition, String componentName, Object object, PropertyDescriptor propertyDescriptor) { List<RemotableAttributeError> errors = new ArrayList<RemotableAttributeError>(); // validate the primitive attributes if defined in the dictionary if (null != propertyDescriptor && getDataDictionaryService().isAttributeDefined(componentName, propertyDescriptor.getName())) { DataObjectWrapper wrapper = KradDataServiceLocator.getDataObjectService().wrap(object); Object value = wrapper.getPropertyValue(propertyDescriptor.getName()); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (TypeUtils.isStringClass(propertyType) || TypeUtils.isIntegralClass(propertyType) || TypeUtils.isDecimalClass(propertyType) || TypeUtils.isTemporalClass(propertyType)) { // check value format against dictionary if (value != null && StringUtils.isNotBlank(value.toString())) { if (!TypeUtils.isTemporalClass(propertyType)) { errors.addAll(validateAttributeFormat(typeAttributeDefinition.getField(), componentName, propertyDescriptor.getName(), value.toString(), propertyDescriptor.getName())); } } else { // if it's blank, then we check whether the attribute should be required errors.addAll(validateAttributeRequired(typeAttributeDefinition.getField(), componentName, propertyDescriptor.getName(), value, propertyDescriptor.getName())); } } } return errors; }
From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java
private void buildChildren(SPObject parent) { for (Class c : parent.getAllowedChildTypes()) { try {//from w ww . ja v a 2 s . c om if (parent.getChildren(c).size() > 0) { logger.debug("It already had a " + c.getSimpleName() + "!"); continue; } SPObject child; child = ((SPObject) valueMaker.makeNewValue(c, null, "child")); parent.addChild(child, parent.getChildren(c).size()); } catch (Exception e) { logger.warn("Could not add a " + c.getSimpleName() + " to a " + parent.getClass().getSimpleName() + " because of a " + e.getClass().getName()); } try { Set<String> s = TestUtils.findPersistableBeanProperties(parent, false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(parent.getClass())); TableMergeRules testParent = null; // special case- the parent of all others //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!s.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. if (property.getName().equals("session")) continue; if (property.getName().equals("type")) continue; try { oldVal = PropertyUtils.getSimpleProperty(parent, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + parent.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); if (property.getName().equals("parentMergeRule")) { if (testParent == null) { newVal = null; testParent = (TableMergeRules) parent; } else { newVal = testParent; } } try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + (newVal == null ? "null" : newVal.getClass().getName()) + ")"); BeanUtils.copyProperty(parent, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + parent.getClass().getName()); } } } catch (Exception e) { throw new RuntimeException(e); } } for (SPObject spo : parent.getChildren()) { buildChildren(spo); } }