Example usage for java.beans PropertyDescriptor getWriteMethod

List of usage examples for java.beans PropertyDescriptor getWriteMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getWriteMethod.

Prototype

public synchronized Method getWriteMethod() 

Source Link

Document

Gets the method that should be used to write the property value.

Usage

From source file:org.rhq.scripting.javascript.JavascriptCompletor.java

private Map<String, List<Object>> findJavaBeanContextMatches(Object baseObject, Class<?> baseObjectClass,
        String start) throws IntrospectionException {

    Map<String, List<Object>> found = new HashMap<String, List<Object>>();

    BeanInfo info = null;/*www .j  a va 2 s . co  m*/
    if (baseObjectClass.isInterface() || baseObjectClass.equals(Object.class)) {
        info = Introspector.getBeanInfo(baseObjectClass);
    } else {
        info = Introspector.getBeanInfo(baseObjectClass, Object.class);
    }

    Set<Method> methodsCovered = new HashSet<Method>();

    PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
    for (PropertyDescriptor desc : descriptors) {
        if (desc.getName().startsWith(start) && (!IGNORED_METHODS.contains(desc.getName()))) {

            List<Object> list = found.get(desc.getName());
            if (list == null) {
                list = new ArrayList<Object>();
                found.put(desc.getName(), list);
            }
            list.add(desc);

            methodsCovered.add(desc.getReadMethod());
            methodsCovered.add(desc.getWriteMethod());
        }
    }

    MethodDescriptor[] methods = info.getMethodDescriptors();
    for (MethodDescriptor desc : methods) {
        if (desc.getName().startsWith(start) && !methodsCovered.contains(desc.getMethod())
                && !desc.getName().startsWith("_d") && !IGNORED_METHODS.contains(desc.getName())) {

            Method m = desc.getMethod();

            List<Object> list = found.get(desc.getName());
            if (list == null) {
                list = new ArrayList<Object>();
                found.put(desc.getName(), list);
            }
            list.add(m);
        }
    }

    return found;
}

From source file:org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.java

/**
 * <p>Validates the attribute value for the given {@link TypeAttributeDefinition} having a componentName.</p>
 * <p>This implementation instantiates a component object using reflection on the class name specified in the
 * {@link TypeAttributeDefinition}s componentName, gets a {@link PropertyDescriptor} for the attribute of the
 * component object, hydrates the attribute's value from it's String form, sets that value on the component object,
 * and then delegates to// ww w .  jav a  2  s .  c o m
 * {@link #validatePrimitiveAttributeFromDescriptor(org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.TypeAttributeDefinition, String, Object, java.beans.PropertyDescriptor)}.
 * </p>
 *
 * @param typeAttributeDefinition
 * @param attributeName
 * @param value
 * @return
 */
protected List<RemotableAttributeError> validateDataDictionaryAttribute(
        TypeAttributeDefinition typeAttributeDefinition, String attributeName, String value) {
    try {
        // create an object of the proper type per the component
        Object componentObject = Class.forName(typeAttributeDefinition.getComponentName()).newInstance();

        if (attributeName != null) {
            // get the bean utils descriptor for accessing the attribute on that object
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(componentObject,
                    attributeName);
            if (propertyDescriptor != null) {
                // set the value on the object so that it can be checked
                Object attributeValue = getAttributeValue(propertyDescriptor, value);
                propertyDescriptor.getWriteMethod().invoke(componentObject, attributeValue);
                return validatePrimitiveAttributeFromDescriptor(typeAttributeDefinition,
                        typeAttributeDefinition.getComponentName(), componentObject, propertyDescriptor);
            }
        }
    } catch (Exception e) {
        throw new TypeAttributeValidationException(e);
    }
    return Collections.emptyList();
}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * @throws IllegalArgumentException/* w  w w  . j  ava2 s.  c  o  m*/
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException 
 */
public void testAllSettersAreUndoable() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {

    SQLObject so = getSQLObjectUnderTest();
    propertiesToIgnoreForUndo.add("referenceCount");
    propertiesToIgnoreForUndo.add("populated");
    propertiesToIgnoreForUndo.add("exportedKeysPopulated");
    propertiesToIgnoreForUndo.add("importedKeysPopulated");
    propertiesToIgnoreForUndo.add("columnsPopulated");
    propertiesToIgnoreForUndo.add("indicesPopulated");
    propertiesToIgnoreForUndo.add("SQLObjectListeners");
    propertiesToIgnoreForUndo.add("children");
    propertiesToIgnoreForUndo.add("parent");
    propertiesToIgnoreForUndo.add("parentDatabase");
    propertiesToIgnoreForUndo.add("class");
    propertiesToIgnoreForUndo.add("childCount");
    propertiesToIgnoreForUndo.add("undoEventListeners");
    propertiesToIgnoreForUndo.add("connection");
    propertiesToIgnoreForUndo.add("typeMap");
    propertiesToIgnoreForUndo.add("secondaryChangeMode");
    propertiesToIgnoreForUndo.add("zoomInAction");
    propertiesToIgnoreForUndo.add("zoomOutAction");
    propertiesToIgnoreForUndo.add("magicEnabled");
    propertiesToIgnoreForUndo.add("deleteRule");
    propertiesToIgnoreForUndo.add("updateRule");
    propertiesToIgnoreForUndo.add("tableContainer");
    propertiesToIgnoreForUndo.add("session");
    propertiesToIgnoreForUndo.add("workspaceContainer");
    propertiesToIgnoreForUndo.add("runnableDispatcher");
    propertiesToIgnoreForUndo.add("foregroundThread");

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForUndo.add("name");
    }

    SPObjectUndoManager undoManager = new SPObjectUndoManager(so);
    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));
    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        settableProperties.remove("name");
    }
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForUndo.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            if (property.getWriteMethod() == null) {
                continue;
            }
        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1,tab2");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == SQLCheckConstraint.class) {
            newVal = new SQLCheckConstraint("check constraint name", "check constraint condition");
        } else if (property.getPropertyType() == SQLEnumeration.class) {
            newVal = new SQLEnumeration("some enumeration");
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass());
        }

        int oldChangeCount = undoManager.getUndoableEditCount();

        try {
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)  but only register one as an undo
            assertEquals(
                    "Event for set " + property.getName() + " on " + so.getClass().getName()
                            + " added multiple (" + undoManager.printUndoVector() + ") undos!",
                    oldChangeCount + 1, undoManager.getUndoableEditCount());

        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}

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);
        }//  w  ww. j  a v  a2  s  .com

        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:org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy.java

public List<PersistentProperty> getPersistentProperties(PersistentEntity entity, MappingContext context,
        ClassMapping classMapping) {//from   w  w w .  j  a  v a  2  s .c  o  m
    final List<PersistentProperty> persistentProperties = new ArrayList<PersistentProperty>();
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());

    // owners are the classes that own this class
    Collection embedded = cpf.getStaticPropertyValue(EMBEDDED, Collection.class);
    if (embedded == null)
        embedded = Collections.emptyList();

    Collection transients = cpf.getStaticPropertyValue(TRANSIENT, Collection.class);
    if (transients == null)
        transients = Collections.emptyList();

    // hasMany associations for defining one-to-many and many-to-many
    Map hasManyMap = getAssociationMap(cpf);
    // mappedBy for defining by which property an association is mapped
    Map mappedByMap = cpf.getStaticPropertyValue(MAPPED_BY, Map.class);
    if (mappedByMap == null)
        mappedByMap = Collections.emptyMap();
    // hasOne for declaring a one-to-one association with the foreign key in the child
    Map hasOneMap = cpf.getStaticPropertyValue(HAS_ONE, Map.class);
    if (hasOneMap == null)
        hasOneMap = Collections.emptyMap();

    for (PropertyDescriptor descriptor : cpf.getPropertyDescriptors()) {
        if (descriptor.getPropertyType() == null || descriptor.getPropertyType() == Object.class) {
            // indexed property
            continue;
        }
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) {
            // non-persistent getter or setter
            continue;
        }
        if (descriptor.getName().equals(VERSION) && !entity.isVersioned()) {
            continue;
        }

        Field field = cpf.getDeclaredField(descriptor.getName());
        if (field != null && java.lang.reflect.Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        final String propertyName = descriptor.getName();
        if (isExcludedProperty(propertyName, classMapping, transients))
            continue;
        Class<?> propertyType = descriptor.getPropertyType();
        Class currentPropType = propertyType;
        // establish if the property is a one-to-many
        // if it is a Set and there are relationships defined
        // and it is defined as persistent
        if (embedded.contains(propertyName)) {
            if (isCollectionType(currentPropType)) {
                Class relatedClassType = (Class) hasManyMap.get(propertyName);
                if (relatedClassType == null) {
                    Class javaClass = entity.getJavaClass();

                    Class genericClass = MappingUtils.getGenericTypeForProperty(javaClass, propertyName);

                    if (genericClass != null) {
                        relatedClassType = genericClass;
                    }
                }
                if (relatedClassType != null) {
                    if (propertyFactory.isSimpleType(relatedClassType)) {
                        Basic basicCollection = propertyFactory.createBasicCollection(entity, context,
                                descriptor);
                        persistentProperties.add(basicCollection);
                    } else {
                        EmbeddedCollection association = propertyFactory.createEmbeddedCollection(entity,
                                context, descriptor);

                        persistentProperties.add(association);
                        if (isPersistentEntity(relatedClassType)) {
                            association.setAssociatedEntity(
                                    getOrCreateAssociatedEntity(entity, context, relatedClassType));
                        } else {
                            PersistentEntity embeddedEntity = context.createEmbeddedEntity(relatedClassType);
                            embeddedEntity.initialize();
                            association.setAssociatedEntity(embeddedEntity);
                        }

                    }
                }
            } else {
                ToOne association = propertyFactory.createEmbedded(entity, context, descriptor);
                PersistentEntity associatedEntity = getOrCreateEmbeddedEntity(entity, context,
                        association.getType());
                association.setAssociatedEntity(associatedEntity);
                persistentProperties.add(association);
            }
        } else if (isCollectionType(currentPropType)) {
            final Association association = establishRelationshipForCollection(descriptor, entity, context,
                    hasManyMap, mappedByMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        }
        // otherwise if the type is a domain class establish relationship
        else if (isPersistentEntity(currentPropType)) {
            final ToOne association = establishDomainClassRelationship(entity, descriptor, context, hasOneMap);
            if (association != null) {
                configureOwningSide(association);
                persistentProperties.add(association);
            }
        } else if (Enum.class.isAssignableFrom(currentPropType) || propertyFactory.isSimpleType(propertyType)) {
            persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
        } else if (MappingFactory.isCustomType(propertyType)) {
            persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
        }
    }
    return persistentProperties;
}

From source file:de.xwic.appkit.core.access.AccessHandler.java

/**
 * Update the entity specified by this EntityTransferObject.
 * @param eto/*  w  ww .ja  va 2 s  .  c o  m*/
 * @return
 */
@SuppressWarnings("unchecked")
public EntityTransferObject updateETO(EntityTransferObject eto) {

    if (log.isDebugEnabled()) {
        log.debug("updateETO: " + eto.getEntityClass().getName() + " ID#" + eto.getEntityId() + " v"
                + eto.getEntityVersion() + " by user " + getCurrentUsername());
    }

    ISecurityManager secMan = DAOSystem.getSecurityManager();

    DAO dao = DAOSystem.findDAOforEntity(eto.getEntityClass().getName());
    IPicklisteDAO plDAO = (IPicklisteDAO) DAOSystem.getDAO(IPicklisteDAO.class);

    IEntity entity;
    if (eto.getEntityId() == 0) {
        // create entity
        entity = dao.createEntity(eto.getEntityClass().getName());
    } else {
        if (IPicklistEntry.class.isAssignableFrom(eto.getEntityClass())) {
            entity = ((IPicklisteDAO) dao).getPickListEntryByID(eto.getEntityId());
        } else if (IPicklistText.class.isAssignableFrom(eto.getEntityClass())) {
            entity = ((IPicklisteDAO) dao).getPickListTextByID(eto.getEntityId());
        } else {
            entity = dao.getEntity(eto.getEntityId());
        }
        // must "disconnect" the entity from the session, to prevent database 
        // synchronisation
        HibernateUtil.currentSession().evict(entity);
    }

    // check version
    if (entity.getVersion() != eto.getEntityVersion()) {
        throw new DataAccessException("The entity has been modified by someone else.");
    }

    String scope = entity.type().getName();

    boolean monitoring = !entity.isChanged()
            && !secMan.hasRight(scope, ApplicationData.SECURITY_ACTION_APPROVE);
    // always set changed flag if the entity is 'new', user has no approve rights and entity is monitored.
    boolean setChanged = monitoring && entity.getId() == 0
            && omSettings.getMonitoringProperties(scope).isTypeMonitored();

    ObjectMonitoringTypeProperties omTp = null;
    if (monitoring) {
        omTp = omSettings.getMonitoringProperties(scope);
    }
    try {

        Map<String, PropertyDescriptor> propertyMap = classProperties.get(entity.getClass());
        Set<String> propertyKeys = eto.getPropertyValues().keySet();
        for (String propName : propertyKeys) {

            PropertyValue pValue = eto.getPropertyValue(propName);
            if (!pValue.isModified()) {
                continue;
            }

            log.debug("Modified attribute: " + propName);
            if (monitoring && omTp.isMonitored(propName)) {
                setChanged = true;
                monitoring = false; // no need to monitor any other properties
                log.debug("ObjectMonitoring detected change.");
            }

            PropertyDescriptor pd = propertyMap.get(propName);
            if (pd == null) {
                log.error("Attribute modified but no such property: " + propName, new IllegalStateException());
                continue;
            }

            //            PropertyDescriptor pd = new PropertyDescriptor(propName, entity.getClass());
            Method mWrite = pd.getWriteMethod();
            if (mWrite == null) {
                log.warn("No write method for property " + propName);
                continue;
            }

            if (secMan.getAccess(scope, propName) != ISecurityManager.READ_WRITE) {
                log.warn("Tried to modify attribute without rights:  " + propName);
                continue;
            }

            Object value;

            if (pValue.isLoaded()) {
                value = pValue.getValue();
                if (pd.getPropertyType().equals(Date.class) && value instanceof Calendar) {
                    value = ((Calendar) value).getTime();

                    // handle collections --
                    // collections may contain PropertyValue 'stubs' instead of
                    // entities to reduce message-size.
                } else if (value != null && value.getClass().isArray()) {
                    value = parseCollection(plDAO, pValue, value);
                }
            } else if (pValue.getType().equals(IPicklistEntry.class)) {
                value = plDAO.getPickListEntryByID(pValue.getEntityId());
            } else {
                if (!pValue.isEntityType()) {
                    // must be a Set that has not been loaded
                    log.warn("Modified but not-loaded set detected in property " + propName);
                    continue;
                }
                if (pValue.getType().getName().equals(entity.type().getName())
                        && pValue.getEntityId() == entity.getId()) {
                    value = entity;
                } else {
                    value = toEntity(pValue.getType().getName(), pValue.getEntityId());
                    // disconnect entity from session to prevent
                    // double update by hibernate
                    HibernateUtil.currentSession().evict(value);
                }
            }

            if (value != null && value.getClass().isArray()) {
                // AXIS turns Set's into arrays - need to be converted
                if (pd.getPropertyType().equals(Set.class)) {
                    Object[] array = (Object[]) value;
                    Set<Object> set = new HashSet<Object>();
                    for (Object element : array) {
                        set.add(element);
                    }
                    mWrite.invoke(entity, new Object[] { set });
                } else {
                    throw new RuntimeException("NOT IMPLEMENTED: Handle Arrays.");
                }
            } else {
                mWrite.invoke(entity, new Object[] { value });
            }
        }
    } catch (Exception ie) {
        throw new DataAccessException("Error writing entity properties: " + ie, ie);
    }
    // FLI: Set the change property just before update, to prevent "overriding" during
    // the field update.
    if (setChanged) {
        entity.setChanged(true);
    }
    dao.update(entity);

    fireEvent(EVENT_UPDATE, new AccessEvent(this, entity));

    EntityTransferObject result = new EntityTransferObject(entity);

    return result;
}

From source file:org.pentaho.reporting.engine.classic.core.util.beans.BeanUtility.java

private void updateArrayProperty(final PropertyDescriptor pd, final PropertySpecification name, final Object o)
        throws BeanException {
    final Method readMethod = pd.getReadMethod();
    if (readMethod == null) {
        throw new BeanException("Property is not readable, cannot perform array update: " + name);
    }/*w ww.  java 2 s.  co  m*/
    try {
        // System.out.println(readMethod);
        final Object value = readMethod.invoke(bean);
        // we have (possibly) an array.
        final int index = Integer.parseInt(name.getIndex());
        final Object array = validateArray(BeanUtility.getPropertyType(pd), value, index);
        Array.set(array, index, o);

        final Method writeMethod = pd.getWriteMethod();
        writeMethod.invoke(bean, array);
    } catch (BeanException e) {
        throw e;
    } catch (Exception e) {
        BeanUtility.logger.warn("Failed to read property, cannot perform array update: " + name, e);
        throw new BeanException("Failed to read property, cannot perform array update: " + name);
    }
}

From source file:org.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java

/**
 * Utility method which can take one payment and distribute its amount by ratio to the target payments
 * /*from   ww w.j  a v a 2  s .c o  m*/
 * @param source Source Payment
 * @param targets Target Payment
 * @param ratios Ratio to be applied for each target
 */
private void applyRatioToPaymentAmounts(AssetPayment source, AssetPayment[] targets, double[] ratios) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null
                    && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
                if (amount != null && amount.isNonZero()) {
                    KualiDecimal[] ratioAmounts = KualiDecimalUtils.allocateByRatio(amount, ratios);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    if (writeMethod != null) {
                        for (int i = 0; i < ratioAmounts.length; i++) {
                            writeMethod.invoke(targets[i], ratioAmounts[i]);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * XXX This test should use the {@link GenericNewValueMaker} as it has it's own mini
 * version inside it. This test should also be using the annotations to decide which 
 * setters can fire events./* ww w.j a va2s .co m*/
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException
 */
public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {
    SQLObject so = getSQLObjectUnderTest();
    so.populate();

    propertiesToIgnoreForEventGeneration.addAll(getPropertiesToIgnoreForEvents());

    //Ignored because we expect the object to be populated.
    propertiesToIgnoreForEventGeneration.add("exportedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("importedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("columnsPopulated");
    propertiesToIgnoreForEventGeneration.add("indicesPopulated");

    CountingSQLObjectListener listener = new CountingSQLObjectListener();
    SQLPowerUtils.listenToHierarchy(so, listener);

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForEventGeneration.add("name");
    }

    List<PropertyDescriptor> settableProperties;

    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEventGeneration.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            // check for a setter
            if (property.getWriteMethod() == null) {
                continue;
            }

        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLRelationship.UpdateDeleteRule.class) {
            if (oldVal == SQLRelationship.UpdateDeleteRule.CASCADE) {
                newVal = SQLRelationship.UpdateDeleteRule.RESTRICT;
            } else {
                newVal = SQLRelationship.UpdateDeleteRule.CASCADE;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else if (property.getPropertyType() == List.class) {
            newVal = Arrays.asList("one", "two");
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass() + " on property "
                    + property.getDisplayName());
        }

        int oldChangeCount = listener.getChangedCount();

        try {
            System.out.println("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)
            assertTrue(
                    "Event for set " + property.getName() + " on " + so.getClass().getName() + " didn't fire!",
                    listener.getChangedCount() > oldChangeCount);
            if (listener.getChangedCount() == oldChangeCount + 1) {
                assertEquals("Property name mismatch for " + property.getName() + " in " + so.getClass(),
                        property.getName(), ((PropertyChangeEvent) listener.getLastEvent()).getPropertyName());
                assertEquals("New value for " + property.getName() + " was wrong", newVal,
                        ((PropertyChangeEvent) listener.getLastEvent()).getNewValue());
            }
        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}

From source file:org.loy.fesf.core.impl.BaseContext.java

/**
 * <p>/*from  w w w .  j av a  2  s  .  c  o m*/
 * Set the value for the specified property.
 * </p>
 *
 * @param descriptor
 *            <code>PropertyDescriptor</code> for the specified property
 * @param value
 *            The new value for this property (must be of the correct type)
 *
 */
private void writeProperty(final PropertyDescriptor descriptor, final Object value) {
    try {
        Method method = descriptor.getWriteMethod();

        if (method == null) {
            throw new UnsupportedOperationException("Property '" + descriptor.getName() + "' is not writeable");
        }

        method.invoke(this, new Object[] { value });
    } catch (Exception e) {
        throw new UnsupportedOperationException(
                "Exception writing property '" + descriptor.getName() + "': " + e.getMessage());
    }
}