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:com.expressui.core.dao.query.EntityQuery.java

/**
 * Clear this query so that all filters (query parameters) and sort-criteria are removed (except for defaults).
 * The method uses reflection to clear any filters defined as bean properties by subclasses. Once cleared,
 * re-execution of query results in all records being found or a default list of default filters are specified.
 *
 * @see #initializeDefaults//from   w  w w . j  a v  a 2s .co  m
 */
public void clear() {
    try {
        for (PropertyDescriptor descriptor : descriptors) {
            Method writeMethod = descriptor.getWriteMethod();
            Method readMethod = descriptor.getReadMethod();
            if (readMethod != null && writeMethod != null
                    && !writeMethod.getDeclaringClass().equals(EntityQuery.class)
                    && !writeMethod.getDeclaringClass().equals(Object.class)) {
                Class type = descriptor.getPropertyType();
                if (type.isPrimitive() && !type.isArray()) {
                    if (ReflectionUtil.isNumberType(type)) {
                        writeMethod.invoke(this, 0);
                    } else if (Boolean.class.isAssignableFrom(type)) {
                        writeMethod.invoke(this, false);
                    }
                } else {
                    writeMethod.invoke(this, new Object[] { null });
                }
            }
        }
    } catch (IllegalAccessException e) {
        Assert.PROGRAMMING.fail(e);
    } catch (InvocationTargetException e) {
        Assert.PROGRAMMING.fail(e);
    }

    initializeDefaults();
}

From source file:com.twinsoft.convertigo.beans.core.MySimpleBeanInfo.java

protected PropertyDescriptor getPropertyDescriptor(String name) throws IntrospectionException {
    checkAdditionalProperties();//  w w w.  jav  a2  s  . co m
    for (int i = 0; i < properties.length; i++) {
        PropertyDescriptor property = properties[i];
        if (name.equals(property.getName())) {
            PropertyDescriptor clone = new PropertyDescriptor(name, property.getReadMethod(),
                    property.getWriteMethod());
            clone.setDisplayName(property.getDisplayName());
            clone.setShortDescription(property.getShortDescription());
            clone.setPropertyEditorClass(property.getPropertyEditorClass());
            clone.setBound(property.isBound());
            clone.setConstrained(property.isConstrained());
            clone.setExpert(property.isExpert());
            clone.setHidden(property.isHidden());
            clone.setPreferred(property.isPreferred());
            for (String attributeName : Collections.list(property.attributeNames())) {
                clone.setValue(attributeName, property.getValue(attributeName));
            }
            return properties[i] = clone;
        }
    }
    return null;
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.input.AbstractInputPresenter.java

/**
 * Sorgt dafuer, dass aenderungen in das Periodenobjekt geschrieben werden.
 * ueberprueft die Benutzereingabe auf ihre Konvertierbarkeit in eine
 * Doublevariable und gibt im Fehlerfall eine Fehlermeldung an den User
 * zurueck.//from  w  w w  .  j a v  a2  s. c  o m
 * 
 * @param newContent
 *            Inhalt des Textfeldes das in das Periodenobjekt geschrieben
 *            werden soll
 * @param textFieldColumn
 *            Spalte des GridLayouts wo das Textfeld liegt
 * @param textFieldRow
 *            Reihe des GridLayouts wo das Textfeld liegt
 * @param destination
 *            Name der Property in welche newContent geschrieben werden soll
 */

public void validateChange(String newContent, int textFieldColumn, int textFieldRow, String destination) {
    destination = shownProperties[Arrays.asList(germanNamesProperties).indexOf(destination)];
    logger.debug("" + newContent);
    try {
        df.parse(newContent).doubleValue();
        df.parse(newContent).doubleValue();
    } catch (Exception e) {
        getView().setWrong(textFieldColumn, textFieldRow, true);
        return;
    }
    getView().setWrong(textFieldColumn, textFieldRow, false);

    for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(period.getClass())) {
        if (Arrays.asList(shownProperties).contains(destination)) {
            if (pd.getDisplayName().equals(destination)) {
                try {
                    pd.getWriteMethod();
                    period.toString();

                    pd.getWriteMethod().invoke(period, new Object[] { df.parse(newContent).doubleValue() });
                    logger.debug("Content should be written: " + (double) pd.getReadMethod().invoke(period));
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                        | ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

private void runAnnotations(final Object object) {
    try {/*from   ww  w  . ja  v a  2  s.co m*/

        if (Iterable.class.isInstance(object) && !Iterator.class.isInstance(object)) {
            for (Object element : (Iterable) object) {
                runAnnotations(element);
            }
        }
        PropertyDescriptor[] propertiesDescriptor = PropertyUtils.getPropertyDescriptors(object);
        for (PropertyDescriptor propertyDescriptor : propertiesDescriptor) {
            // Avoid the "getClass" as a property
            if (propertyDescriptor.getPropertyType().equals(Class.class)
                    || (propertyDescriptor.getReadMethod() == null
                            && propertyDescriptor.getWriteMethod() == null)) {
                continue;
            }
            Field field = findField(object.getClass(), propertyDescriptor.getName());

            if (field != null && field.isAnnotationPresent(SecureProperty.class)
                    && securePropertyHandler != null) {
                secureProperty(object, field);
            }

            if (field != null && field.isAnnotationPresent(InjectValue.class) && injectValueFactory != null) {
                injectValue(object, field);
                continue;
            }

            Object fieldValue = PropertyUtils.getProperty(object, propertyDescriptor.getName());
            if (Iterable.class.isInstance(fieldValue) && !Iterator.class.isInstance(object)) {
                for (Object element : (Iterable) fieldValue) {
                    runAnnotations(element);
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Unable to secure value for " + object.getClass(), e);
    }
}

From source file:org.openengsb.core.ekb.persistence.edb.internal.EDBConverter.java

/**
 * Converts an EDBObject to a model by analyzing the object and trying to call the corresponding setters of the
 * model./*w  w w  .j  a  v a 2s  .c om*/
 */
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) {
    if (!checkEDBObjectModelType(object, model)) {
        return null;
    }
    List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>();
    for (PropertyDescriptor propertyDescriptor : ModelUtils.getPropertyDescriptorsForClass(model)) {
        if (propertyDescriptor.getWriteMethod() == null
                || propertyDescriptor.getName().equals("openEngSBModelTail")) {
            continue;
        }
        Object value = getValueForProperty(propertyDescriptor, object);
        Class<?> propertyClass = propertyDescriptor.getPropertyType();
        if (propertyClass.isPrimitive()) {
            entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value,
                    ClassUtils.primitiveToWrapper(propertyClass)));
        } else {
            entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass));
        }
    }

    for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) {
        EDBObjectEntry entry = objectEntry.getValue();
        Class<?> entryType;
        try {
            entryType = model.getClassLoader().loadClass(entry.getType());
            entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType));
        } catch (ClassNotFoundException e) {
            LOGGER.error("Unable to load class {} of the model tail", entry.getType());
        }
    }
    return ModelUtils.createModel(model, entries);
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

private static void setProperty(Object obj, String fieldName, Object value)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    PropertyDescriptor pd = getPropertyDescriptor(obj.getClass(), fieldName);
    if (pd == null || pd.getWriteMethod() == null) {
        throw new IllegalStateException(
                "In class" + obj.getClass() + "no setter method found for field '" + fieldName + "'");
    }//from   w w w  .j  a  va 2  s  .co m
    Class<?> paramType = pd.getWriteMethod().getParameterTypes()[0];
    if (value != null && !paramType.isAssignableFrom(value.getClass())) {
        value = TypeUtils.cast(value, paramType, null);
    }
    pd.getWriteMethod().invoke(obj, value);
}

From source file:org.openmrs.api.handler.OpenmrsObjectSaveHandler.java

/**
 * This sets the uuid property on the given OpenmrsObject if it is non-null.
 *
 * @see org.openmrs.api.handler.RequiredDataHandler#handle(org.openmrs.OpenmrsObject,
 *      org.openmrs.User, java.util.Date, java.lang.String)
 * @should set empty string properties to null
 * @should not set empty string properties to null for AllowEmptyStrings annotation
 * @should not trim empty strings for AllowLeadingOrTrailingWhitespace annotation
 * @should trim strings without AllowLeadingOrTrailingWhitespace annotation
 * @should trim empty strings for AllowEmptyStrings annotation
 *//*  ww w  . j a  v  a  2  s .  c  o  m*/
public void handle(OpenmrsObject openmrsObject, User creator, Date dateCreated, String reason) {
    if (openmrsObject.getUuid() == null) {
        openmrsObject.setUuid(UUID.randomUUID().toString());
    }

    //Set all empty string properties, that do not have the AllowEmptyStrings annotation, to null.
    //And also trim leading and trailing white space for properties that do not have the
    //AllowLeadingOrTrailingWhitespace annotation.
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(openmrsObject);
    for (PropertyDescriptor property : properties) {

        if (property.getPropertyType() == null) {
            continue;
        }

        // Ignore properties that don't have a getter (e.g. GlobalProperty.valueReferenceInternal) or
        // don't have a setter (e.g. Patient.familyName)
        if (property.getWriteMethod() == null || property.getReadMethod() == null) {
            continue;
        }

        // Ignore properties that have a deprecated getter or setter
        if (property.getWriteMethod().getAnnotation(Deprecated.class) != null
                || property.getReadMethod().getAnnotation(Deprecated.class) != null) {
            continue;
        }

        //We are dealing with only strings
        if (!property.getPropertyType().equals(String.class)) {
            continue;
        }

        try {
            Object value = PropertyUtils.getProperty(openmrsObject, property.getName());
            if (value == null) {
                continue;
            }

            Object valueBeforeTrim = value;
            if (property.getWriteMethod().getAnnotation(AllowLeadingOrTrailingWhitespace.class) == null) {
                value = ((String) value).trim();

                //If we have actually trimmed any space, set the trimmed value.
                if (!valueBeforeTrim.equals(value)) {
                    PropertyUtils.setProperty(openmrsObject, property.getName(), value);
                }
            }

            //Check if user is interested in setting empty strings to null
            if (property.getWriteMethod().getAnnotation(AllowEmptyStrings.class) != null) {
                continue;
            }

            if ("".equals(value)
                    && !(openmrsObject instanceof Voidable && ((Voidable) openmrsObject).isVoided())) {
                //Set to null only if object is not already voided
                PropertyUtils.setProperty(openmrsObject, property.getName(), null);
            }
        } catch (UnsupportedOperationException ex) {
            // there is no need to log this. These should be (mostly) silently skipped over 
            if (log.isInfoEnabled()) {
                log.info(
                        "The property " + property.getName() + " is no longer supported and should be ignored.",
                        ex);
            }
        } catch (InvocationTargetException ex) {
            if (log.isWarnEnabled()) {
                log.warn("Failed to access property " + property.getName() + "; accessor threw exception.", ex);
            }
        } catch (Exception ex) {
            throw new APIException("failed.change.property.value", new Object[] { property.getName() }, ex);
        }
    }
}

From source file:de.hasait.clap.impl.CLAPClassNode.java

@Override
public final void fillResult(final CLAPParseContext pContext, final CLAPResultImpl pResult) {
    internalFillResult(pContext, pResult);

    T value;//from   w  w w .ja  v a 2 s.co m
    try {
        value = _class.newInstance();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
    boolean anySet = false;
    for (final Entry<CLAPValue<?>, PropertyDescriptor> entry : _propertyDescriptorByOptionMap.entrySet()) {
        final CLAPValue<?> node = entry.getKey();
        if (pResult.getCount(node) > 0) {
            anySet = true;
            final PropertyDescriptor propertyDescriptor = entry.getValue();
            final Object nodeValue = pResult.getValue(node);
            try {
                propertyDescriptor.getWriteMethod().invoke(value, nodeValue);
            } catch (final Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    for (final CLAPKeywordNode node : _keywordNodes) {
        if (pContext.getNodeCount(node) > 0) {
            anySet = true;
        }
    }
    if (anySet) {
        pResult.setCount(this, 1);
        pResult.setValue(this, value);
    }
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java

private void processAnnotatedProperties(Properties properties, String name, MutablePropertyValues mpv,
        Class<?> clazz) {//from w  w  w . j  av  a 2  s .co  m
    // TODO support proxies
    if (clazz != null && clazz.getPackage() != null) {
        if (basePackage != null && !clazz.getPackage().getName().startsWith(basePackage)) {
            return;
        }

        log.info("Configuring properties for bean=" + name + "[" + clazz + "]");

        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining property=[" + clazz.getName() + "." + property.getName() + "]");
            Method setter = property.getWriteMethod();
            Method getter = property.getReadMethod();
            Property annotation = null;
            if (setter != null && setter.isAnnotationPresent(Property.class)) {
                annotation = setter.getAnnotation(Property.class);
            } else if (setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                annotation = getter.getAnnotation(Property.class);
            } else if (setter == null && getter != null && getter.isAnnotationPresent(Property.class)) {
                throwBeanConfigurationException(clazz, property.getName());
            }
            if (annotation != null) {
                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining field=[" + clazz.getName() + "." + field.getName() + "]");
            if (field.isAnnotationPresent(Property.class)) {
                Property annotation = field.getAnnotation(Property.class);
                PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                if (property == null || property.getWriteMethod() == null) {
                    throwBeanConfigurationException(clazz, field.getName());
                }

                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }
    }
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) {
    try {//from   w  w  w  .  j  a  v  a  2  s  . c om
        return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod(), pd.getPropertyEditorClass());
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
    }
}