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.github.erchu.beancp.commons.NameBasedMapConvention.java

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {//from  www  .j  av  a 2 s .  c  o  m
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

From source file:com.seovic.core.DynamicObject.java

/**
 * Update specified target from this object.
 *
 * @param target  target object to update
 *//* ww w .  j  a v a  2 s .  co  m*/
public void update(Object target) {
    if (target == null) {
        throw new IllegalArgumentException("Target to update cannot be null");
    }

    BeanWrapper bw = new BeanWrapperImpl(target);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    for (Map.Entry<String, Object> property : m_properties.entrySet()) {
        String propertyName = property.getKey();
        Object value = property.getValue();

        if (value instanceof Map) {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) {
                value = new DynamicObject((Map<String, Object>) value);
            }
        }

        if (value instanceof DynamicObject) {
            ((DynamicObject) value).update(bw.getPropertyValue(propertyName));
        } else {
            bw.setPropertyValue(propertyName, value);
        }
    }
}

From source file:de.micromata.genome.db.jpa.logging.BaseJpaLoggingImpl.java

/**
 * Inits the.//from w  w w .  j a v  a  2s . com
 */
protected void initProps() {
    final BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(getMasterClass());
    } catch (IntrospectionException e) {
        log.error("unable to introspect hibernate DO for logging -> no searchable fields will be available", e);
        return;
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
            continue;
        }
        EntityLogSearchAttribute ent = pd.getReadMethod().getAnnotation(EntityLogSearchAttribute.class);
        if (ent == null) {
            continue;
        }
        Column col = pd.getReadMethod().getAnnotation(Column.class);
        if (col == null) {
            log.warn("Found EntityLogSearchAttribute but no Column: " + pd);
            continue;
        }
        for (String en : ent.enumName()) {
            searchableAttributeProperties.put(en, new SearchColumnDesc(pd, col.length()));
        }
    }
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

/**
 * Calls the setter method on the target object for the given property. If no setter method
 * exists for the property, this method does nothing.
 *
 * @param target The object to set the property on.
 * @param prop The property to set.//ww  w.j  ava2  s. com
 * @param value The value to pass into the setter.
 * @throws SQLException if an error occurs setting the property.
 */
private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException {

    Method setter = prop.getWriteMethod();

    if (setter == null) {

        return;
    }

    try {

        // Don't call setter if the value object isn't the right type
        // if (this.isCompatibleType(value, params[0])) {
        setter.invoke(target, new Object[] { value });

    } catch (Exception e) {

        throw new SQLException("Cannot set " + prop.getName() + ": " + e.toString(), e);
    }
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

protected void scanForBindingProperty(String parameterName, IParameterSpecification ps) {
    String propertyName = parameterName + Tapestry.PARAMETER_PROPERTY_NAME_SUFFIX;
    PropertyDescriptor pd = getPropertyDescriptor(propertyName);

    // only enhance custom parameter binding properties if they are declared abstract
    if (ps.getDirection() == Direction.CUSTOM) {
        if (pd == null)
            return;

        if (!(isAbstract(pd.getReadMethod()) || isAbstract(pd.getWriteMethod())))
            return;
    }//from w  w w.  j  av  a2 s  . c  o  m

    if (isImplemented(pd))
        return;

    // Need to create the property.
    getEnhancedClass().createProperty(propertyName, IBinding.class.getName());
}

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler./*from  w  w w .jav a  2  s  . c  o  m*/
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}

From source file:ch.ralscha.extdirectspring.util.ParametersResolver.java

private Map<String, Object> fillReadRequestFromMap(ExtDirectStoreReadRequest to, Map<String, Object> from) {
    Set<String> foundParameters = new HashSet<String>();

    for (Entry<String, Object> entry : from.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        if (key.equals("filter")) {
            List<Filter> filters = new ArrayList<Filter>();

            if (value instanceof String) {
                List<Map<String, Object>> rawFilters = this.jsonHandler.readValue((String) value,
                        new TypeReference<List<Map<String, Object>>>() {/* empty */
                        });//from w  w w.j a v a2s . c  om

                for (Map<String, Object> rawFilter : rawFilters) {
                    Filter filter = Filter.createFilter(rawFilter, this.conversionService);
                    if (filter != null) {
                        filters.add(filter);
                    }
                }
            } else if (value instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> filterList = (List<Map<String, Object>>) value;
                for (Map<String, Object> rawFilter : filterList) {
                    Filter filter = Filter.createFilter(rawFilter, this.conversionService);
                    if (filter != null) {
                        filters.add(filter);
                    }
                }
            }
            to.setFilters(filters);
            foundParameters.add(key);
        } else if (key.equals("sort") && value != null && value instanceof List) {

            List<SortInfo> sorters = new ArrayList<SortInfo>();
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> rawSorters = (List<Map<String, Object>>) value;

            for (Map<String, Object> aRawSorter : rawSorters) {
                sorters.add(SortInfo.create(aRawSorter));
            }

            to.setSorters(sorters);
            foundParameters.add(key);
        } else if (key.equals("group") && value != null && value instanceof List) {
            List<GroupInfo> groups = new ArrayList<GroupInfo>();
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> rawGroups = (List<Map<String, Object>>) value;

            for (Map<String, Object> aRawGroupInfo : rawGroups) {
                groups.add(GroupInfo.create(aRawGroupInfo));
            }

            to.setGroups(groups);
            foundParameters.add(key);
        } else {

            PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(to.getClass(), key);
            if (descriptor != null && descriptor.getWriteMethod() != null) {
                try {

                    descriptor.getWriteMethod().invoke(to,
                            this.conversionService.convert(value, descriptor.getPropertyType()));

                    foundParameters.add(key);
                } catch (IllegalArgumentException e) {
                    log.error("fillObjectFromMap", e);
                } catch (IllegalAccessException e) {
                    log.error("fillObjectFromMap", e);
                } catch (InvocationTargetException e) {
                    log.error("fillObjectFromMap", e);
                }
            }
        }
    }

    if (to.getLimit() != null) {
        // this test is no longer needed with extjs 4.0.7 and extjs 4.1.0
        // these two libraries always send page, start and limit
        if (to.getPage() != null && to.getStart() == null) {
            to.setStart(to.getLimit() * (to.getPage() - 1));
            // the else if is still valid for extjs 3 code
        } else if (to.getPage() == null && to.getStart() != null) {
            to.setPage(to.getStart() / to.getLimit() + 1);
        }
    }

    if (to.getSort() != null && to.getDir() != null) {
        List<SortInfo> sorters = new ArrayList<SortInfo>();
        sorters.add(new SortInfo(to.getSort(), SortDirection.fromString(to.getDir())));
        to.setSorters(sorters);
    }

    if (to.getGroupBy() != null && to.getGroupDir() != null) {
        List<GroupInfo> groups = new ArrayList<GroupInfo>();
        groups.add(new GroupInfo(to.getGroupBy(), SortDirection.fromString(to.getGroupDir())));
        to.setGroups(groups);
    }

    Map<String, Object> remainingParameters = new HashMap<String, Object>();
    for (Entry<String, Object> entry : from.entrySet()) {
        if (!foundParameters.contains(entry.getKey())) {
            remainingParameters.put(entry.getKey(), entry.getValue());
        }
    }
    to.setParams(remainingParameters);

    return remainingParameters;
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

/**
 * Gets exposed property or parameter name for properties with an appropriate setter (=write) method.
 *
 * @param inputParameter/*from   www.jav a2  s . c o  m*/
 *         for exposure
 * @return property name
 */
private String getWritableExposedPropertyOrPropertyName(PropertyDescriptor inputParameter) {

    final Method writeMethod = inputParameter.getWriteMethod();
    final Expose expose = writeMethod.getAnnotation(Expose.class);
    String propertyName;
    if (expose != null) {
        propertyName = expose.value();
    } else {
        propertyName = inputParameter.getName();
    }
    return propertyName;
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandlerImpl.java

/**
 * Appends all property values on the given {@link StringBuilder}
 *///from   w w w.ja  v a 2 s. co m
private void appendPropertyValues(final StringBuilder sb, final Object bean) {
    if (bean == null) {
        sb.append("<null>");
        return;
    } else if (bean instanceof String) {
        sb.append(bean);
        return;
    }
    BeanWrapper bw = new BeanWrapperImpl(bean);
    boolean first = true;
    for (PropertyDescriptor desc : bw.getPropertyDescriptors()) {
        if (desc.getWriteMethod() == null) {
            // Only log readable and writable properties
            continue;
        }
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        String name = desc.getName();
        sb.append(name).append('=');
        Object value = bw.getPropertyValue(name);
        appendValue(sb, FormatObject.maskIfNeeded(name, value));
    }
}