List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>(); RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager(); if (xmlNodeInfo != null) { if (xmlNodeInfo.isInheritable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); propertyTemplate = new AutoPropertyTemplate("parent"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); }/*from w ww .j a v a 2 s . c om*/ if (xmlNodeInfo.isScopable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope"); propertyTemplate.setPrimitive(true); Object[] ecs = Scope.class.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); properties.put(propertyTemplate.getName(), propertyTemplate); } if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) { Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType()); if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } if (InterceptableDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } } for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) { String propertyName = entry.getKey(); String value = entry.getValue(); AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName); propertyTemplate.setDefaultValue(value); propertyTemplate.setPrimitive(true); propertyTemplate.setFixed(true); propertyTemplate.setVisible(false); properties.put(propertyName, propertyTemplate); } for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) { String propertyName = entry.getKey(); XmlProperty xmlProperty = entry.getValue(); TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType()); Class<?> propertyType = null; if (propertyTypeInfo != null) { propertyType = propertyTypeInfo.getType(); } AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); if (propertyType != null && !propertyType.equals(String.class)) { propertyTemplate.setType(propertyType.getName()); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); properties.put(propertyName, propertyTemplate); } } PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getWriteMethod() != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } String propertyName = propertyDescriptor.getName(); XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { continue; } TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } AutoPropertyTemplate propertyTemplate = null; XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class); if (xmlProperty != null) { if (xmlProperty.unsupported()) { continue; } propertyTemplate = properties.get(propertyName); if (propertyTemplate == null) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); } if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName) || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) { propertyTemplate.setHighlight(1); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes()); if (clientTypes > 0) { propertyTemplate.setClientTypes(clientTypes); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class) || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); } if (propertyTemplate != null) { propertyTemplate.setType(propertyDescriptor.getPropertyType().getName()); if (propertyType.isEnum()) { Object[] ecs = propertyType.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); } ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class); if (componentReference != null) { ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager, componentReference.value(), "id"); propertyTemplate.setReference(referenceTemplate); } IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class); if (ideProperty != null) { propertyTemplate.setVisible(ideProperty.visible()); propertyTemplate.setEditor(ideProperty.editor()); propertyTemplate.setHighlight(ideProperty.highlight()); if (StringUtils.isNotEmpty(ideProperty.enumValues())) { propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;")); } } ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class); if (clientProperty != null) { propertyTemplate.setDefaultValue(clientProperty.escapeValue()); } properties.put(propertyName, propertyTemplate); } } } return properties.values(); }
From source file:io.milton.property.BeanPropertySource.java
@Override public PropertyMetaData getPropertyMetaData(QName name, Resource r) { log.debug("getPropertyMetaData"); BeanPropertyResource anno = getAnnotation(r); if (anno == null) { log.debug(" no annotation: ", r.getClass().getCanonicalName()); return PropertyMetaData.UNKNOWN; }/*from w w w . ja v a 2 s. c o m*/ if (!name.getNamespaceURI().equals(anno.value())) { log.debug("different namespace", anno.value(), name.getNamespaceURI()); return PropertyMetaData.UNKNOWN; } PropertyDescriptor pd = getPropertyDescriptor(r, name.getLocalPart()); if (pd == null || pd.getReadMethod() == null) { LogUtils.debug(log, "getPropertyMetaData: no read method:", name.getLocalPart(), r.getClass()); return PropertyMetaData.UNKNOWN; } else { BeanProperty propAnno = pd.getReadMethod().getAnnotation(BeanProperty.class); if (propAnno != null) { if (!propAnno.value()) { log.trace( "getPropertyMetaData: property is annotated and value is false, so do not allow access"); return PropertyMetaData.UNKNOWN; } else { log.trace("getPropertyMetaData: property is annotated and value is true, so allow access"); } } else { if (anno.enableByDefault()) { log.trace( "getPropertyMetaData: no property annotation, property annotation is enable by default so allow access"); } else { log.trace( "getPropertyMetaData:no property annotation, class annotation says disable by default, decline access"); return PropertyMetaData.UNKNOWN; } } if (log.isDebugEnabled()) { log.debug("writable: " + anno.writable() + " - " + (pd.getWriteMethod() != null)); } boolean writable = anno.writable() && (pd.getWriteMethod() != null); if (writable) { return new PropertyMetaData(PropertyAccessibility.WRITABLE, pd.getPropertyType()); } else { return new PropertyMetaData(PropertyAccessibility.READ_ONLY, pd.getPropertyType()); } } }
From source file:com.bradmcevoy.property.BeanPropertySource.java
@Override public PropertyMetaData getPropertyMetaData(QName name, Resource r) { log.debug("getPropertyMetaData"); BeanPropertyResource anno = getAnnotation(r); if (anno == null) { log.debug(" no annotation: ", r.getClass().getCanonicalName()); return PropertyMetaData.UNKNOWN; }//from w w w . j a v a2 s .c om if (!name.getNamespaceURI().equals(anno.value())) { log.debug("different namespace", anno.value(), name.getNamespaceURI()); return PropertyMetaData.UNKNOWN; } PropertyDescriptor pd = getPropertyDescriptor(r, name.getLocalPart()); if (pd == null || pd.getReadMethod() == null) { LogUtils.debug(log, "getPropertyMetaData: no read method:", name.getLocalPart(), r.getClass()); return PropertyMetaData.UNKNOWN; } else { BeanPropertyAccess propAnno = pd.getReadMethod().getAnnotation(BeanPropertyAccess.class); if (propAnno != null) { if (!propAnno.value()) { log.trace( "getPropertyMetaData: property is annotated and value is false, so do not allow access"); return PropertyMetaData.UNKNOWN; } else { log.trace("getPropertyMetaData: property is annotated and value is true, so allow access"); } } else { if (anno.enableByDefault()) { log.trace( "getPropertyMetaData: no property annotation, property annotation is enable by default so allow access"); } else { log.trace( "getPropertyMetaData:no property annotation, class annotation says disable by default, decline access"); return PropertyMetaData.UNKNOWN; } } if (log.isDebugEnabled()) { log.debug("writable: " + anno.writable() + " - " + (pd.getWriteMethod() != null)); } boolean writable = anno.writable() && (pd.getWriteMethod() != null); if (writable) { return new PropertyMetaData(PropertyAccessibility.WRITABLE, pd.getPropertyType()); } else { return new PropertyMetaData(PropertyAccessibility.READ_ONLY, pd.getPropertyType()); } } }
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Populates the form from the given map of properties. If a matching property is null or an empty * string, then null is placed on the form. * * @param form the form to populate./*from w ww . j av a 2 s .co m*/ * @param formatters any date or time formatters. * @param properties the properties to populate from. * @param ignoreProperties names of any properties to ignore when it comes to populating on the form. * @param override whether or not to override properties already set on the given form. * @param assignableTypesOnly whether or not copying should be attempted only if the property types are assignable. */ @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateFormFromPropertyMap(final Object form, final Map<String, DateFormat> formatters, final Map<String, ?> properties, final String[] ignoreProperties, boolean override, boolean assignableTypesOnly) { if (properties != null) { try { final Collection<String> ignoredProperties = ignoreProperties != null ? Arrays.asList(ignoreProperties) : new ArrayList<String>(); final Map<String, Object> formProperties = PropertyUtils.describe(form); for (final Iterator<String> iterator = formProperties.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(form, name) && !ignoredProperties.contains(name)) { final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(form, name); if (descriptor != null) { boolean populateProperty = true; if (!override) { final String isSetPropertyName = name + "Set"; if (PropertyUtils.isReadable(form, isSetPropertyName)) { final Boolean isPropertySet = (Boolean) PropertyUtils.getProperty(form, isSetPropertyName); if (isPropertySet.booleanValue()) { populateProperty = false; } } } if (populateProperty) { final Object property = properties.get(name); // - only convert if the string is not empty if (property != null) { Object value = null; if (property instanceof String) { final String propertyAsString = (String) property; if (propertyAsString.trim().length() > 0) { DateFormat formatter = formatters != null ? formatters.get(name) : null; // - if the formatter is available we use that, otherwise we attempt to convert if (formatter != null) { try { value = formatter.parse(propertyAsString); } catch (ParseException parseException) { // - try the default formatter (handles the default java.util.Date.toString() format) formatter = formatters != null ? formatters.get(null) : null; value = formatter.parse(propertyAsString); } } else { value = ConvertUtils.convert(propertyAsString, descriptor.getPropertyType()); } } // - don't attempt to set null on primitive fields if (value != null || !descriptor.getPropertyType().isPrimitive()) { PropertyUtils.setProperty(form, name, value); } } else { value = property; try { if (!assignableTypesOnly || descriptor.getPropertyType() .isAssignableFrom(value.getClass())) { PropertyUtils.setProperty(form, name, value); } } catch (Exception exception) { final String valueTypeName = value.getClass().getName(); final String propertyTypeName = descriptor.getPropertyType().getName(); final StringBuilder message = new StringBuilder( "Can not set form property '" + name + "' of type: " + propertyTypeName + " with value: " + value); if (!descriptor.getPropertyType().isAssignableFrom(value.getClass())) { message.append("; " + valueTypeName + " is not assignable to " + propertyTypeName); } throw new IllegalArgumentException( message + ": " + exception.toString()); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }
From source file:com.complexible.pinto.RDFMapper.java
/** * Read the object from the RDF/*from www .j a v a2 s . c om*/ * * @param theGraph the RDF * @param theClass the type of the object to read * @param theObj the identifier of the object to create * * @return the object * * @throws RDFMappingException if the object could not be created */ public <T> T readValue(final Model theGraph, final Class<T> theClass, final Resource theObj) { if (theClass == null) { return null; } final T aInst = newInstance(theClass); if (aInst instanceof Identifiable) { ((Identifiable) aInst).id(theObj); } for (PropertyDescriptor aDescriptor : PropertyUtils.getPropertyDescriptors(aInst)) { if (isIgnored(aDescriptor)) { continue; } final IRI aProperty = getProperty(aDescriptor); Collection<Value> aValues = theGraph.stream() .filter(Statements.subjectIs(theObj).and(Statements.predicateIs(aProperty))) .map(Statement::getObject).collect(Collectors.toList()); Object aObj; if (aValues.isEmpty()) { continue; } else if (Collection.class.isAssignableFrom(aDescriptor.getPropertyType())) { final Collection aIterable = mCollectionFactory.create(aDescriptor); Collection<Value> aElems = Lists.newArrayListWithCapacity(aValues.size()); // this will allow the mixing of RDF lists of values with single values. in "well-formed" data that // kind of mixing probably won't ever happen. but it's easier/better to be lax about what we'll accept // here, and this will cover one or more list assertions as well as multiple property assertions forming // the list as well as the mix of both for (Value aValue : aValues) { if (aValue instanceof Resource && Models2.isList(theGraph, (Resource) aValue)) { aElems.addAll(Models2.asList(theGraph, (Resource) aValue)); } else { aElems.add(aValue); } } aElems.stream().map(toObject(theGraph, aDescriptor)::apply).forEach(aIterable::add); aObj = aIterable; } else if (Map.class.isAssignableFrom(aDescriptor.getPropertyType())) { if (aValues.size() > 1) { if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) { LOGGER.warn( "Property type of {} is Map, expected a single value, but {} were found. MappingOptions is set to ignore this, so using only the first value.", aDescriptor.getName(), aValues.size()); } else { throw new RDFMappingException(String.format( "%s values found, but property type is Map, one value expected", aValues.size())); } } Value aPropValue = aValues.iterator().next(); final Map aMap = mMapFactory.create(aDescriptor); for (Value aMapEntry : theGraph.filter((Resource) aPropValue, HAS_ENTRY, null).objects()) { final Value aKey = theGraph.stream() .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(KEY))) .map(Statement::getObject).findFirst().orElse(null); final Value aValue = theGraph.stream() .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(VALUE))) .map(Statement::getObject).findFirst().orElse(null); Object aKeyObj = null, aValueObj = null; if (aKey instanceof Literal) { // ok to pass null here, it won't be used aKeyObj = valueToObject(aKey, theGraph, null); } else { aKeyObj = readValue(theGraph, type(theGraph, (Resource) aKey), (Resource) aKey); } if (aValue instanceof Literal) { aValueObj = valueToObject(aValue, theGraph, null); } else { aValueObj = readValue(theGraph, type(theGraph, (Resource) aValue), (Resource) aValue); } if (aKeyObj == null || aValueObj == null) { LOGGER.warn("Skipping map entry, key or value could not be created."); continue; } aMap.put(aKeyObj, aValueObj); } aObj = aMap; } else { if (aValues.size() > 1) { if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) { LOGGER.warn( "Property type of {} is {}, expected a single value, but {} were found. MappingOptions is set to ignore this, so using only the first value.", aDescriptor.getName(), aDescriptor.getPropertyType(), aValues.size()); } else { throw new RDFMappingException(String.format("%s values found, but property type is %s", aValues.size(), aDescriptor.getPropertyType())); } } final Value aValue = aValues.iterator().next(); aObj = valueToObject(aValue, theGraph, aDescriptor); } try { // this will fail spectacularly if there is a mismatch between the incoming RDF and what the bean // defines. we can either check that eagerly and fail spectacularly then, or do it here and be // lazy. we'll go with lazy PropertyUtils.setProperty(aInst, aDescriptor.getName(), aObj); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, RDFMappingException.class); throw new RDFMappingException(e); } } return aInst; }
From source file:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java
private Association establishRelationshipForCollection(PropertyDescriptor property, PersistentEntity entity, MappingContext context, Map<String, Class> hasManyMap, Map mappedByMap) { // is it a relationship Class relatedClassType = hasManyMap.get(property.getName()); if (relatedClassType == null) { return propertyFactory.createBasicCollection(entity, context, property); }//from ww w .jav a 2 s .c o m // set the referenced type in the property ClassPropertyFetcher referencedCpf = ClassPropertyFetcher.forClass(relatedClassType); String referencedPropertyName = null; // if the related type is a domain class // then figure out what kind of relationship it is if (!isPersistentEntity(relatedClassType)) { // otherwise set it to not persistent as you can't persist // relationships to non-domain classes return propertyFactory.createBasicCollection(entity, context, property); } // check the relationship defined in the referenced type // if it is also a Set/domain class etc. Map relatedClassRelationships = referencedCpf.getPropertyValue(HAS_MANY, Map.class); Class<?> relatedClassPropertyType = null; String relatedClassPropertyName = null; ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass()); // First check whether there is an explicit relationship // mapping for this property (as provided by "mappedBy"). String mappingProperty = (String) mappedByMap.get(property.getName()); if (StringUtils.hasText(mappingProperty)) { // First find the specified property on the related class, if it exists. PropertyDescriptor pd = findProperty( referencedCpf.getPropertiesAssignableFromType(entity.getJavaClass()), mappingProperty); // If a property of the required type does not exist, search // for any collection properties on the related class. if (pd == null) { pd = findProperty(referencedCpf.getPropertiesAssignableToType(Collection.class), mappingProperty); } // We've run out of options. The given "mappedBy" setting is invalid. if (pd == null) { if (entity.isExternal()) { return null; } throw new IllegalMappingException( "Non-existent mapping property [" + mappingProperty + "] specified for property [" + property.getName() + "] in class [" + entity.getJavaClass().getName() + "]"); } // Tie the properties together. relatedClassPropertyType = pd.getPropertyType(); referencedPropertyName = pd.getName(); } else { if (!forceUnidirectional(property, mappedByMap)) { // if the related type has a relationships map it may be a many-to-many // figure out if there is a many-to-many relationship defined if (isRelationshipToMany(entity, relatedClassType, relatedClassRelationships)) { Map relatedClassMappedBy = cpf.getStaticPropertyValue(MAPPED_BY, Map.class); if (relatedClassMappedBy == null) relatedClassMappedBy = Collections.emptyMap(); // retrieve the relationship property for (Object o : relatedClassRelationships.keySet()) { String currentKey = (String) o; String mappedByProperty = (String) relatedClassMappedBy.get(currentKey); if (mappedByProperty != null && !mappedByProperty.equals(property.getName())) continue; Class<?> currentClass = (Class<?>) relatedClassRelationships.get(currentKey); if (currentClass.isAssignableFrom(entity.getJavaClass())) { relatedClassPropertyName = currentKey; break; } } // Map classRelationships = cpf.getPropertyValue(HAS_MANY, Map.class); // // if (isRelationshipToMany(entity, relatedClassType, classRelationships)) { // String relatedClassPropertyName = findManyRelatedClassPropertyName( // property.getName(), referencedCpf, classRelationships, relatedClassType); // if there is one defined get the type if (relatedClassPropertyName != null) { relatedClassPropertyType = referencedCpf.getPropertyType(relatedClassPropertyName); } } // otherwise figure out if there is a one-to-many relationship by retrieving any properties that are of the related type // if there is more than one property then (for the moment) ignore the relationship if (relatedClassPropertyType == null || Collection.class.isAssignableFrom(relatedClassPropertyType)) { List<PropertyDescriptor> descriptors = referencedCpf .getPropertiesAssignableFromType(entity.getJavaClass()); if (descriptors.size() == 1) { final PropertyDescriptor pd = descriptors.get(0); relatedClassPropertyType = pd.getPropertyType(); referencedPropertyName = pd.getName(); } else if (descriptors.size() > 1) { // try now to use the class name by convention String classPropertyName = entity.getDecapitalizedName(); PropertyDescriptor pd = findProperty(descriptors, classPropertyName); if (pd == null) { if (entity.isExternal()) { return null; } pd = descriptors.get(0); } if (pd != null) { relatedClassPropertyType = pd.getPropertyType(); referencedPropertyName = pd.getName(); } } } } } // if its a many-to-many figure out the owning side of the relationship final boolean isInverseSideEntity = isPersistentEntity(relatedClassPropertyType); Association association = null; boolean many = false; if (relatedClassPropertyType == null || isInverseSideEntity) { // uni-directional one-to-many association = propertyFactory.createOneToMany(entity, context, property); } else if (Collection.class.isAssignableFrom(relatedClassPropertyType) || Map.class.isAssignableFrom(relatedClassPropertyType)) { // many-to-many association = propertyFactory.createManyToMany(entity, context, property); ((ManyToMany) association).setInversePropertyName(relatedClassPropertyName); many = true; } PersistentEntity associatedEntity = getOrCreateAssociatedEntity(entity, context, relatedClassType); if (many) { Map classRelationships = referencedCpf.getPropertyValue(HAS_MANY, Map.class); referencedPropertyName = findManyRelatedClassPropertyName(null, referencedCpf, classRelationships, entity.getJavaClass()); } if (association != null) { association.setAssociatedEntity(associatedEntity); if (referencedPropertyName != null) { association.setReferencedPropertyName(referencedPropertyName); } } return association; }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests passing an object to an {@link SPPersisterListener} will persist * the object and all of the properties that have setters. *///from w ww . j a va2 s.c o m public void testSPListenerPersistsNewObjects() throws Exception { CountingSPPersister persister = new CountingSPPersister(); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject objectUnderTest = getSPObjectUnderTest(); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + objectUnderTest.getClass().getName()); } } //persist the object to the new target root new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest, objectUnderTest.getParent().getChildren(objectUnderTest.getClass()).indexOf(objectUnderTest)); assertTrue(persister.getPersistPropertyCount() > 0); assertEquals(getSPObjectUnderTest().getUUID(), persister.getPersistObjectList().get(0).getUUID()); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newValue = null; boolean found = false; for (PersistedSPOProperty persistedSPO : persister.getPersistPropertyList()) { if (persistedSPO.getPropertyName().equals(property.getName()) && persistedSPO.getUUID().equals(getSPObjectUnderTest().getUUID())) { newValue = persistedSPO.getNewValue(); found = true; break; } } assertTrue("Could not find the persist call for property " + property.getName(), found); if (oldVal == null) { assertNull(newValue); } else { assertPersistedValuesAreEqual(oldVal, getConverter().convertToComplexType(newValue, oldVal.getClass()), getConverter().convertToBasicType(oldVal), newValue, property.getPropertyType()); } } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Tests that calling//from ww w .j av a2s . c om * {@link SPPersister#persistObject(String, String, String, int)} for a * session persister will create a new object and set all of the properties * on the object. */ public void testPersisterAddsNewObject() throws Exception { SPObject wo = getObjectUnderTest(); wo.setMagicEnabled(false); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, session.getWorkspace(), true); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, persister, true); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Set all possible values to new values for testing. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } SPObject parent = wo.getParent(); int oldChildCount = parent.getChildren().size(); listener.transactionStarted(null); listener.childRemoved( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().indexOf(wo), EventType.REMOVED)); listener.transactionEnded(null); //persist the object wo.setParent(parent); listener.transactionStarted(null); listener.childAdded( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().size(), EventType.ADDED)); listener.transactionEnded(null); //the object must now be added to the super parent assertEquals(oldChildCount, parent.getChildren().size()); SPObject persistedObject = parent.getChildren().get(parent.childPositionOffset(wo.getClass())); persistedObject.setMagicEnabled(false); //check all the properties are what we expect on the new object Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist(); List<String> settablePropertyNames = new ArrayList<String>(); for (PropertyDescriptor pd : settableProperties) { settablePropertyNames.add(pd.getName()); } settablePropertyNames.removeAll(ignorableProperties); for (String persistedPropertyName : settablePropertyNames) { Class<?> classType = null; for (PropertyDescriptor propertyDescriptor : settableProperties) { if (propertyDescriptor.getName().equals(persistedPropertyName)) { classType = propertyDescriptor.getPropertyType(); break; } } logger.debug("Persisted object is of type " + persistedObject.getClass()); Object oldVal = PropertyUtils.getSimpleProperty(wo, persistedPropertyName); Object newVal = PropertyUtils.getSimpleProperty(persistedObject, persistedPropertyName); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && persistedPropertyName.equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object basicOldVal = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); Object basicNewVal = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); logger.debug("Property " + persistedPropertyName + ". oldVal is \"" + basicOldVal + "\" but newVal is \"" + basicNewVal + "\""); assertPersistedValuesAreEqual(oldVal, newVal, basicOldVal, basicNewVal, classType); } }
From source file:org.obiba.onyx.jade.instrument.gemac800.CardiosoftInstrumentRunner.java
/** * Place the results and xml file into a map object to send them to the server for persistence * * @param resultParser/*from w ww.ja v a 2s .c om*/ * @throws Exception */ public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) { Map<String, Data> outputToSend = new HashMap<String, Data>(); try { for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class) .getPropertyDescriptors()) { if (instrumentExecutionService.hasOutputParameter(pd.getName())) { Object value = pd.getReadMethod().invoke(resultParser); if (value != null) { if (value instanceof Long) { // We need to subtract one to the birthday month since the month of January is represented by "0" in // java.util.Calendar (January is represented by "1" in Cardiosoft). if (pd.getName().equals("participantBirthMonth")) { outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1)); } else { outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value)); } } else if (value instanceof Double) { outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value)); } else { outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString())); } } else { // send null values as well (ONYX-585) log.info("Output parameter " + pd.getName() + " was null; will send null to server"); if (pd.getPropertyType().isAssignableFrom(Long.class)) { log.info("Output parameter " + pd.getName() + " is of type INTEGER"); outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null)); } else if (pd.getPropertyType().isAssignableFrom(Double.class)) { log.info("Output parameter " + pd.getName() + " is of type DECIMAL"); outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null)); } else { log.info("Output parameter " + pd.getName() + " is of type TEXT"); outputToSend.put(pd.getName(), new Data(DataType.TEXT, null)); } } } } // Save the xml and pdf files File xmlFile = new File(getExportPath(), getXmlFileName()); outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile)); instrumentExecutionService.addOutputParameterValues(outputToSend); } catch (Exception e) { log.debug("Sending data to server failed.", e); throw new RuntimeException(e); } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will be run for each object that extends SPObject and confirms * the SPSessionPersister can create new objects * @throws Exception//ww w .ja v a 2s. c om */ public void testPersisterCreatesNewObjects() throws Exception { SPObjectRoot newRoot = new SPObjectRoot(); WorkspaceContainer stub = new StubWorkspaceContainer() { private final SPObject workspace = new StubWorkspace(this, this, root); @Override public SPObject getWorkspace() { return workspace; } }; newRoot.setParent(stub.getWorkspace()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); NewValueMaker newValueMaker = createNewValueMaker(newRoot, getPLIni()); SessionPersisterSuperConverter newConverter = new SessionPersisterSuperConverter(getPLIni(), newRoot); SPSessionPersister persister = new TestingSessionPersister("Test persister", newRoot, newConverter); persister.setWorkspaceContainer(stub); for (SPObject child : root.getChildren()) { copyToRoot(child, newValueMaker); } SPObject objectUnderTest = getSPObjectUnderTest(); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); Object newValInNewRoot = newValueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); if (newValInNewRoot instanceof SPObject) { ((SPObject) newValInNewRoot).setUUID(((SPObject) newVal).getUUID()); } try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + objectUnderTest.getClass().getName()); } } //create a new root and parent for the object SPObject newParent; if (objectUnderTest.getParent() instanceof SPObjectRoot) { newParent = newRoot; } else { newParent = (SPObject) newValueMaker.makeNewValue(objectUnderTest.getParent().getClass(), null, ""); } newParent.setUUID(objectUnderTest.getParent().getUUID()); int childCount = newParent.getChildren().size(); //persist the object to the new target root Class<? extends SPObject> classChildType = PersisterUtils.getParentAllowedChildType( objectUnderTest.getClass().getName(), objectUnderTest.getParent().getClass().getName()); new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest, objectUnderTest.getParent().getChildren(classChildType).indexOf(objectUnderTest)); //check object exists assertEquals(childCount + 1, newParent.getChildren().size()); SPObject newChild = null; for (SPObject child : newParent.getChildren()) { if (child.getUUID().equals(objectUnderTest.getUUID())) { newChild = child; break; } } if (newChild == null) fail("The child was not correctly persisted."); //check all interesting properties for (PropertyDescriptor property : settableProperties) { if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. Method readMethod = property.getReadMethod(); Object valueBeforePersist = readMethod.invoke(objectUnderTest); Object valueAfterPersist = readMethod.invoke(newChild); Object basicValueBeforePersist = getConverter().convertToBasicType(valueBeforePersist); Object basicValueAfterPersist = newConverter.convertToBasicType(valueAfterPersist); assertPersistedValuesAreEqual(valueBeforePersist, valueAfterPersist, basicValueBeforePersist, basicValueAfterPersist, readMethod.getReturnType()); } }