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:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@Override
public boolean isWritableProperty(String propertyName) {
    try {//from  w  ww. j av  a2s .  c o m
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd != null) {
            if (pd.getWriteMethod() != null) {
                return true;
            }
        } else {
            // Maybe an indexed/mapped property...
            getPropertyValue(propertyName);
            return true;
        }
    } catch (InvalidPropertyException ex) {
        // Cannot be evaluated, so can't be writable.
    }
    return false;
}

From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncHelperBase.java

/**
 * Recursively sets values on this syncable working way down in the object tree found in the values map.
 * @param syncable// www  .  j  a  va2 s  .  co  m
 * @param values
 * @param change
 * @throws NoSuchFieldException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
@SuppressWarnings("unchecked")
protected void setValuesOnSyncable(PersistableBusinessObject syncable, Map<String, Object> values,
        AwardSyncChange change) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException,
        ClassNotFoundException, NoSuchMethodException, InstantiationException {
    Class clazz = syncable.getClass();
    boolean setEntry = false;
    for (Map.Entry<String, Object> entry : values.entrySet()) {
        setEntry = false;
        for (PropertyDescriptor propDescriptor : PropertyUtils.getPropertyDescriptors(clazz)) {
            if (StringUtils.equals(propDescriptor.getName(), entry.getKey())) {
                if (entry.getValue() instanceof AwardSyncXmlExport) {
                    AwardSyncXmlExport xmlExport = (AwardSyncXmlExport) entry.getValue();
                    applySyncChange(syncable, change, entry.getKey(), xmlExport);
                    setEntry = true;
                } else if (Collection.class.isAssignableFrom(propDescriptor.getPropertyType())
                        && entry.getValue() instanceof List) {
                    applySyncChange(syncable, change, entry.getKey(),
                            (Collection<AwardSyncXmlExport>) entry.getValue());
                    setEntry = true;
                } else {
                    Method setter = propDescriptor.getWriteMethod();
                    setter.invoke(syncable, entry.getValue());
                    setEntry = true;
                }
            }
        }
        if (!setEntry) {
            throw new NoSuchFieldException();
        }
    }
}

From source file:org.jdbcluster.privilege.PrivilegeCheckerImpl.java

/**
 * calculates instance and parameter specific privileges
 * /*from   w w w.j a  va 2 s. c om*/
 * @param clusterObject cluster object instance
 * @param calledMethod the method called
 * @param args method parameters
 * @return return reqired privileges
 */
private Set<String> getDynamicPrivilegesCluster(PrivilegedCluster clusterObject, Method calledMethod,
        Object[] args) {
    DomainChecker dc = DomainCheckerImpl.getInstance();
    Set<String> result = new HashSet<String>();
    PrivilegesCluster pcAnno = clusterObject.getClass().getAnnotation(PrivilegesCluster.class);

    if (pcAnno == null || pcAnno.property().length == 0 || pcAnno.property()[0].length() == 0)
        return result;

    if (isGetMethodInRequiredProperty(pcAnno.property(), calledMethod))
        return result;

    getBeanWrapper().setWrappedInstance(clusterObject);

    for (String propertyPath : pcAnno.property()) {

        PropertyDescriptor pd = getPropertyDescriptor(propertyPath, getBeanWrapper());

        if (pd != null) {
            Field f = getPropertyField(propertyPath, pd);
            String domId = getDomainIdFromField(f);
            DomainPrivilegeList dpl;
            try {
                dpl = (DomainPrivilegeList) dc.getDomainListInstance(domId);
            } catch (ClassCastException e) {
                throw new ConfigurationException(
                        "privileged domain [" + domId + "] needs implemented DomainPrivilegeList Interface", e);
            }
            if (!(pd.getReadMethod().equals(calledMethod) || pd.getWriteMethod().equals(calledMethod))) {
                String value = getPropertyValue(propertyPath, getBeanWrapper());
                Set<String> setToAdd = dpl.getDomainEntryPivilegeList(domId, value);
                if (setToAdd != null)
                    result.addAll(setToAdd);
            } else {
                if (pd.getWriteMethod().equals(calledMethod)) {
                    if ((args.length != 1 || !(args[0] instanceof String)) && args[0] != null)
                        throw new ConfigurationException("privilege checked property [" + propertyPath
                                + "] needs 1 String argument setter");
                    Set<String> ergList = dpl.getDomainEntryPivilegeList(domId, (String) args[0]);
                    if (ergList != null)
                        result.addAll(ergList);
                }
            }
        }
    }
    return result;
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

private void initColumnInfos(Class clazz) {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
    HashMap<String, PropertyDescriptor> mappedPropNames = new HashMap<String, PropertyDescriptor>();
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        if (origDescriptor.getName().equals("class"))
            continue;

        mappedPropNames.put(origDescriptor.getName().toLowerCase(), origDescriptor);
    }/*from w  w  w  .  j  a va 2  s  .  c o m*/

    boolean isMapClass = java.util.Map.class.isAssignableFrom(clazz);
    for (ColumnDescriptor column : _columns) {
        PropertyDescriptor prop = mappedPropNames.get(column.name.toLowerCase());
        if (null != prop) {
            column.name = prop.getName();
            column.clazz = prop.getPropertyType();
            column.isProperty = true;
            column.setter = prop.getWriteMethod();
            if (column.clazz.isPrimitive()) {
                if (Float.TYPE.equals(column.clazz))
                    column.missingValues = 0.0F;
                else if (Double.TYPE.equals(column.clazz))
                    column.missingValues = 0.0;
                else if (Boolean.TYPE.equals(column.clazz))
                    column.missingValues = Boolean.FALSE;
                else
                    column.missingValues = 0; //Will get converted.
            }
        } else if (isMapClass) {
            column.isProperty = false;
        } else {
            column.load = false;
        }
    }
}

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;
        }// www .j  a  va  2s.  c  o m
        descriptor.getWriteMethod().invoke(bean, Conversion.convert(value, descriptor.getPropertyType()));
    }
}

From source file:com.opensymphony.xwork2.ognl.OgnlUtil.java

/**
 * Copies the properties in the object "from" and sets them in the object "to"
 * only setting properties defined in the given "editable" class (or interface)
 * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none
 * is specified.//from w ww .java2  s.  com
 *
 * @param from       the source object
 * @param to         the target object
 * @param context    the action context we're running under
 * @param exclusions collection of method names to excluded from copying ( can be null)
 * @param inclusions collection of method names to included copying  (can be null)
 *                   note if exclusions AND inclusions are supplied and not null nothing will get copied.
 * @param editable the class (or interface) to restrict property setting to
 */
public void copy(final Object from, final Object to, final Map<String, Object> context,
        Collection<String> exclusions, Collection<String> inclusions, Class<?> editable) {
    if (from == null || to == null) {
        LOG.warn(
                "Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event.");
        return;
    }

    TypeConverter converter = getTypeConverterFromContext(context);
    final Map contextFrom = createDefaultContext(from, null);
    Ognl.setTypeConverter(contextFrom, converter);
    final Map contextTo = createDefaultContext(to, null);
    Ognl.setTypeConverter(contextTo, converter);

    PropertyDescriptor[] fromPds;
    PropertyDescriptor[] toPds;

    try {
        fromPds = getPropertyDescriptors(from);
        if (editable != null) {
            toPds = getPropertyDescriptors(editable);
        } else {
            toPds = getPropertyDescriptors(to);
        }
    } catch (IntrospectionException e) {
        LOG.error("An error occurred", e);
        return;
    }

    Map<String, PropertyDescriptor> toPdHash = new HashMap<>();

    for (PropertyDescriptor toPd : toPds) {
        toPdHash.put(toPd.getName(), toPd);
    }

    for (PropertyDescriptor fromPd : fromPds) {
        if (fromPd.getReadMethod() != null) {
            boolean copy = true;
            if (exclusions != null && exclusions.contains(fromPd.getName())) {
                copy = false;
            } else if (inclusions != null && !inclusions.contains(fromPd.getName())) {
                copy = false;
            }

            if (copy) {
                PropertyDescriptor toPd = toPdHash.get(fromPd.getName());
                if ((toPd != null) && (toPd.getWriteMethod() != null)) {
                    try {
                        compileAndExecute(fromPd.getName(), context, new OgnlTask<Object>() {
                            public Void execute(Object expr) throws OgnlException {
                                Object value = Ognl.getValue(expr, contextFrom, from);
                                Ognl.setValue(expr, contextTo, to, value);
                                return null;
                            }
                        });

                    } catch (OgnlException e) {
                        LOG.debug("Got OGNL exception", e);
                    }
                }

            }

        }

    }
}

From source file:org.opencms.configuration.CmsDefaultUserSettings.java

/**
 * Initializes the preference configuration.<p>
 *
 * Note that this method should only be called once the resource types have been initialized, but after addPreference has been called for all configured preferences.
 *
 * @param wpManager the active workplace manager
 *///from www . j a  v a 2s. c  o  m
public void initPreferences(CmsWorkplaceManager wpManager) {

    CURRENT_DEFAULT_SETTINGS = this;
    Class<?> accessorClass = CmsUserSettingsStringPropertyWrapper.class;

    // first initialize all built-in preferences. these are:
    // a) Bean properties of CmsUserSettingsStringPropertyWrapper
    // b) Editor setting preferences
    // c) Gallery setting preferences
    PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(accessorClass);
    for (PropertyDescriptor descriptor : propDescs) {
        String name = descriptor.getName();
        Method getter = descriptor.getReadMethod();
        Method setter = descriptor.getWriteMethod();
        if ((getter == null) || (setter == null)) {
            continue;
        }

        PrefMetadata metadata = getter.getAnnotation(PrefMetadata.class);
        if (metadata == null) {
            CmsBuiltinPreference preference = new CmsBuiltinPreference(name);
            m_preferences.put(preference.getName(), preference);
        } else {
            try {
                Constructor<?> constructor = metadata.type().getConstructor(String.class);
                I_CmsPreference pref = (I_CmsPreference) constructor.newInstance(name);
                m_preferences.put(pref.getName(), pref);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    Map<String, String> editorValues = getEditorSettings();
    if (wpManager.getWorkplaceEditorManager() != null) {
        for (String resType : wpManager.getWorkplaceEditorManager().getConfigurableEditors().keySet()) {
            if (!editorValues.containsKey(resType)) {
                editorValues.put(resType, null);
            }
        }
    }
    for (Map.Entry<String, String> editorSettingEntry : editorValues.entrySet()) {
        CmsEditorPreference pref = new CmsEditorPreference(editorSettingEntry.getKey(),
                editorSettingEntry.getValue());
        m_preferences.put(pref.getName(), pref);
    }

    Map<String, String> galleryValues = new HashMap<String, String>(getStartGalleriesSettings());
    for (String key : wpManager.getGalleries().keySet()) {
        if (!galleryValues.containsKey(key)) {
            galleryValues.put(key, null);
        }
    }
    for (Map.Entry<String, String> galleryEntry : galleryValues.entrySet()) {
        CmsStartGallleryPreference pref = new CmsStartGallleryPreference(galleryEntry.getKey(),
                galleryEntry.getValue());
        m_preferences.put(pref.getName(), pref);
    }

    // Now process configured preferences. Each configuration entry is either
    // for a built-in preference, in which case we create a wrapper around the existing preference,
    // or for a custom user-defined preference.
    for (CmsPreferenceData prefData : m_preferenceData) {
        String name = prefData.getName();
        I_CmsPreference pref = null;
        if (m_preferences.containsKey(name)) {
            // we first remove the existing preference, because in a LinkedHashMap, put(key, value) will not
            // update the position of the entry if the key already exists
            pref = new CmsWrapperPreference(prefData, m_preferences.remove(name));
        } else {
            pref = new CmsUserDefinedPreference(prefData.getName(), prefData.getDefaultValue(),
                    prefData.getPropertyDefinition(), prefData.getTab());
        }
        m_preferences.put(pref.getName(), pref);
        pref.setValue(this, prefData.getDefaultValue());
    }
}

From source file:org.springframework.beans.BeanWrapperImpl.java

@Override
public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException {
    try {// w  w  w. jav  a2 s . c o  m
        BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName);
        String finalPath = getFinalPath(nestedBw, propertyName);
        PropertyTokenHolder tokens = getPropertyNameTokens(finalPath);
        PropertyDescriptor pd = nestedBw.getCachedIntrospectionResults()
                .getPropertyDescriptor(tokens.actualName);
        if (pd != null) {
            if (tokens.keys != null) {
                if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
                    return TypeDescriptor.nested(property(pd), tokens.keys.length);
                }
            } else {
                if (pd.getReadMethod() != null || pd.getWriteMethod() != null) {
                    return new TypeDescriptor(property(pd));
                }
            }
        }
    } catch (InvalidPropertyException ex) {
        // Consider as not determinable.
    }
    return null;
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * Uses reflection to find all the settable properties of the object under test,
 * and fails if any of them can be set without an event happening.
 *///from   w  w w . j  a  va  2s  .  c o m
public void testSettingPropertiesFiresEvents() throws Exception {

    CountingWabitListener listener = new CountingWabitListener();
    SPObject wo = getObjectUnderTest();
    wo.addSPListener(listener);

    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;

        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;
        }

        int oldChangeCount = listener.getPropertyChangeCount();
        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);

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

}

From source file:ca.sqlpower.wabit.dao.session.WorkspacePersisterListener.java

public void propertyChanged(PropertyChangeEvent evt) {

    if (wouldEcho())
        return;/*from w ww .j  a v a 2s .co  m*/

    this.transactionStarted(TransactionEvent.createStartTransactionEvent(this,
            "Creating start transaction event from propertyChange on object "
                    + evt.getSource().getClass().getSimpleName() + " and property name "
                    + evt.getPropertyName()));

    SPObject source = (SPObject) evt.getSource();
    String uuid = source.getUUID();
    String propertyName = evt.getPropertyName();
    Object oldValue = evt.getOldValue();
    Object newValue = evt.getNewValue();

    PropertyDescriptor propertyDescriptor;
    try {
        propertyDescriptor = PropertyUtils.getPropertyDescriptor(source, propertyName);
    } catch (Exception ex) {
        this.rollback();
        throw new RuntimeException(ex);
    }

    //Not persisting non-settable properties
    if (propertyDescriptor == null || propertyDescriptor.getWriteMethod() == null) {
        this.transactionEnded(TransactionEvent.createEndTransactionEvent(this));
        return;
    }

    for (PropertyToIgnore ignoreProperty : ignoreList) {
        if (ignoreProperty.getPropertyName().equals(propertyName)
                && ignoreProperty.getClassType().isAssignableFrom(source.getClass())) {
            this.transactionEnded(TransactionEvent.createEndTransactionEvent(this));
            return;
        }
    }

    //XXX special case that I want to remove even though I'm implementing it
    List<Object> additionalParams = new ArrayList<Object>();
    if (source instanceof OlapQuery && propertyName.equals("currentCube")) {
        additionalParams.add(((OlapQuery) source).getOlapDataSource());
    }

    DataType typeForClass = PersisterUtils.getDataType(newValue == null ? Void.class : newValue.getClass());
    Object oldBasicType;
    Object newBasicType;
    oldBasicType = converter.convertToBasicType(oldValue, additionalParams.toArray());
    newBasicType = converter.convertToBasicType(newValue, additionalParams.toArray());

    logger.debug("Calling persistProperty on propertyChange");
    this.persistProperty(uuid, propertyName, typeForClass, oldBasicType, newBasicType);

    this.transactionEnded(TransactionEvent.createEndTransactionEvent(this));
}