Example usage for org.springframework.beans BeanWrapper isWritableProperty

List of usage examples for org.springframework.beans BeanWrapper isWritableProperty

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper isWritableProperty.

Prototype

boolean isWritableProperty(String propertyName);

Source Link

Document

Determine whether the specified property is writable.

Usage

From source file:org.ng200.openolympus.util.Beans.java

public static <T> void copy(T from, T to) {
    final BeanWrapper src = new BeanWrapperImpl(from);
    final BeanWrapper trg = new BeanWrapperImpl(to);

    for (final String propertyName : Stream.of(src.getPropertyDescriptors()).map(pd -> pd.getName())
            .collect(Collectors.toList())) {
        if (!trg.isWritableProperty(propertyName)) {
            continue;
        }//from  ww w .  j a v  a  2 s .c  o  m

        trg.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
    }
}

From source file:org.jdal.swing.form.FormUtils.java

/**
 * Add a link on primary and dependent JComboBoxes by property name. 
 * When selection changes on primary use propertyName to get a Collection and fill dependent JComboBox with it
 * @param primary JComboBox when selection changes
 * @param dependent JComboBox that are filled with collection   
 * @param propertyName the property name for get the collection from primary selected item
 * @param addNull if true, add a null as first combobox item
 *//*from  w  w  w.j  a v  a2s . c  o m*/
@SuppressWarnings("rawtypes")
public static void link(final JComboBox primary, final JComboBox dependent, final String propertyName,
        final boolean addNull) {

    primary.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Object selected = primary.getSelectedItem();
            if (selected != null) {
                BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(selected);
                if (wrapper.isWritableProperty(propertyName)) {
                    Collection collection = (Collection) wrapper.getPropertyValue(propertyName);
                    Vector<Object> vector = new Vector<Object>(collection);
                    if (addNull)
                        vector.add(0, null);
                    DefaultComboBoxModel model = new DefaultComboBoxModel(vector);
                    dependent.setModel(model);
                } else {
                    log.error("Can't write on propety '" + propertyName + "' of class: '" + selected.getClass()
                            + "'");
                }
            }
        }
    });
}

From source file:com.aw.support.beans.BeanUtils.java

public static Object copyProperties(Object source, Object target, String[] propertyNamesToIgnore,
        boolean ignoreProxy, boolean ignoreCollections) {
    List<String> propertyNamesToIgnoreList = propertyNamesToIgnore == null ? Collections.EMPTY_LIST
            : Arrays.asList(propertyNamesToIgnore);
    BeanWrapper sourceWrap = new BeanWrapperImpl(source);
    BeanWrapper targetWrap = new BeanWrapperImpl(target);
    for (PropertyDescriptor propDescriptor : sourceWrap.getPropertyDescriptors()) {
        String propName = propDescriptor.getName();
        //chequear que no esta en la lista a ignorar
        if (propertyNamesToIgnoreList.contains(propName))
            continue;
        //chequear que se puede leer
        if (!sourceWrap.isReadableProperty(propName))
            continue;
        //chequear que se puede escribir
        if (!targetWrap.isWritableProperty(propName))
            continue;

        Object sourceValue = sourceWrap.getPropertyValue(propName);

        //chequear que objeto no es un proxy
        if (ignoreProxy && sourceValue != null && Proxy.isProxyClass(sourceValue.getClass()))
            continue;

        //chequear que objeto no una collection
        if (ignoreCollections && sourceValue instanceof Collection)
            continue;

        targetWrap.setPropertyValue(propName, sourceValue);
    }//  w w  w .  j  a  v  a2s  .c o m
    return target;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.project.PreferencesUtil.java

/**
 * Set annotation preferences of users for a given project such as window size, annotation
 * layers,... reading from the file system.
 *
 * @param aUsername/*from  www.j av  a 2s .  c  o m*/
 *            The {@link User} for whom we need to read the preference (preferences are stored
 *            per user)
 * @param aRepositoryService the repository service.
 * @param aAnnotationService the annotation service.
 * @param aBModel
 *            The {@link BratAnnotatorModel} that will be populated with preferences from the
 *            file
 * @param aMode the mode.
 * @throws BeansException hum?
 * @throws IOException hum?
 */
public static void setAnnotationPreference(String aUsername, RepositoryService aRepositoryService,
        AnnotationService aAnnotationService, BratAnnotatorModel aBModel, Mode aMode)
        throws BeansException, IOException {
    AnnotationPreference preference = new AnnotationPreference();
    BeanWrapper wrapper = new BeanWrapperImpl(preference);
    // get annotation preference from file system
    try {
        for (Entry<Object, Object> entry : aRepositoryService.loadUserSettings(aUsername, aBModel.getProject())
                .entrySet()) {
            String property = entry.getKey().toString();
            int index = property.lastIndexOf(".");
            String propertyName = property.substring(index + 1);
            String mode = property.substring(0, index);
            if (wrapper.isWritableProperty(propertyName) && mode.equals(aMode.getName())) {

                if (AnnotationPreference.class.getDeclaredField(propertyName)
                        .getGenericType() instanceof ParameterizedType) {
                    List<String> value = Arrays
                            .asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                    if (!value.get(0).equals("")) {
                        wrapper.setPropertyValue(propertyName, value);
                    }
                } else {
                    wrapper.setPropertyValue(propertyName, entry.getValue());
                }
            }
        }
        aBModel.setPreferences(preference);

        // Get tagset using the id, from the properties file
        aBModel.getAnnotationLayers().clear();
        if (preference.getAnnotationLayers() != null) {
            for (Long id : preference.getAnnotationLayers()) {
                aBModel.getAnnotationLayers().add(aAnnotationService.getLayer(id));
            }
        }
    }
    // no preference found
    catch (Exception e) {

        /*
         * // disable corefernce annotation for correction/curation pages for 0.4.0 release
         * List<TagSet> tagSets = aAnnotationService.listTagSets(aBModel.getProject());
         * List<TagSet> corefTagSets = new ArrayList<TagSet>(); List<TagSet> noFeatureTagSet =
         * new ArrayList<TagSet>(); for (TagSet tagSet : tagSets) { if (tagSet.getLayer() ==
         * null || tagSet.getFeature() == null) { noFeatureTagSet.add(tagSet); } else if
         * (tagSet.getLayer().getType().equals(ChainAdapter.CHAIN)) { corefTagSets.add(tagSet);
         * } }
         *
         * if (aMode.equals(Mode.CORRECTION) || aMode.equals(Mode.AUTOMATION) ||
         * aMode.equals(Mode.CURATION)) { tagSets.removeAll(corefTagSets); }
         * tagSets.remove(noFeatureTagSet); aBModel.setAnnotationLayers(new
         * HashSet<TagSet>(tagSets));
         */
        /*
         * abAnnotatorModel.setAnnotationLayers(new HashSet<TagSet>(aAnnotationService
         * .listTagSets(abAnnotatorModel.getProject())));
         */

        List<AnnotationLayer> layers = aAnnotationService.listAnnotationLayer(aBModel.getProject());
        aBModel.setAnnotationLayers(layers);
    }
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Copy non-null bean properties from one object to another.
 * //from w ww  .ja v  a2 s  . c o  m
 * @param src the object to copy values from
 * @param dest the object to copy values to
 * @param ignore a set of property names to ignore (optional)
 * @param emptyStringToNull if <em>true</em> then String values that 
 * are empty or contain only whitespace will be treated as if they
 * where <em>null</em>
 */
public static void copyBeanProperties(Object src, Object dest, Set<String> ignore, boolean emptyStringToNull) {
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper to = PropertyAccessorFactory.forBeanPropertyAccess(dest);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null || (emptyStringToNull && (propValue instanceof String)
                && !StringUtils.hasText((String) propValue))) {
            continue;
        }
        if (to.isWritableProperty(propName)) {
            to.setPropertyValue(propName, propValue);
        }
    }
}

From source file:com.aw.core.dao.AWQueryExecuter.java

private String[] buildColumnNames(ResultSet rs, BeanWrapper wrapper) throws SQLException {
    ResultSetMetaData meta = rs.getMetaData();
    List<String> colNames = new ArrayList<String>(meta.getColumnCount());

    for (int i = 0; i < meta.getColumnCount(); i++) {
        String colName = meta.getColumnName(i + 1);
        if (wrapper != null && wrapper.isWritableProperty(colName))
            colNames.add(colName);/*from ww w .  j  a v  a2 s. c  om*/
    }
    return colNames.toArray(new String[colNames.size()]);
}

From source file:com.aw.core.util.QTTablaABeanMapper.java

public Object buildNewBean(Class type, DataRowProvider rs) {
    Object bean = instantiateBean(type);
    BeanWrapper wrap = new BeanWrapperImpl(bean);
    for (Iterator iterator = colNameToSetters.keySet().iterator(); iterator.hasNext();) {
        String colName = (String) iterator.next();
        String setter = (String) colNameToSetters.get(colName); //vaPrecioCostoVVFUnit
        Object value = null;//w  ww.  j av  a2 s .  c om
        try {
            value = rs.getObject(colName);
            if (wrap.isWritableProperty(setter)) {
                //logger.debug("Setting "+value+ " "+colName+"-->"+setter);
                Object convertedValue = ObjectConverter.convert(value, wrap.getPropertyType(setter));
                wrap.setPropertyValue(setter, convertedValue);
                //wrap.setPropertyValue(setter, value);
            } else {
                logger.debug("Not set " + value + " " + colName + "-->(setter R/O):" + setter);
            }
        } catch (Throwable e) {
            logger.error("Error: No se puede settear propertyName:" + setter + " db.ColName:" + colName
                    + " con valor:" + value);
            throw AWBusinessException.wrapUnhandledException(logger, e);
        }
    }
    return bean;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.security.dao.AbstractDao.java

/**
 * Finds all entities that have the same type as the given example and all fields are equal to
 * non-null fields in the example./*w ww.  ja  v  a 2s.c om*/
 */
protected <TT> CriteriaQuery<TT> queryByExample(TT aExample, String aOrderBy, boolean aAscending) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    @SuppressWarnings("unchecked")
    CriteriaQuery<TT> query = cb.createQuery((Class<TT>) aExample.getClass());
    @SuppressWarnings("unchecked")
    Root<TT> root = query.from((Class<TT>) aExample.getClass());
    query.select(root);

    List<Predicate> predicates = new ArrayList<Predicate>();
    BeanWrapper a = PropertyAccessorFactory.forBeanPropertyAccess(aExample);

    // Iterate over all properties
    for (PropertyDescriptor d : a.getPropertyDescriptors()) {
        Object value = a.getPropertyValue(d.getName());

        // Only consider writeable properties. This filters out e.g. the "class" (getClass())
        // property.
        if (value != null && a.isWritableProperty(d.getName())) {
            predicates.add(cb.equal(root.get(d.getName()), value));
        }
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }

    if (aOrderBy != null) {
        if (aAscending) {
            query.orderBy(cb.asc(root.get(aOrderBy)));
        } else {
            query.orderBy(cb.desc(root.get(aOrderBy)));
        }
    }

    return query;
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from exclude annotations to further 
 * populate exclude paths already parsed from XML.
 *//*from w ww  .  ja va  2 s .  c  o  m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initExcludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class excludeAnnotation : excludeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(excludeAnnotation) != null) {
                        entity.getExcludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for excluded properties",
                            se);
                }
            }
        }
    }
}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from include annotations to further 
 * populate include paths already parsed from XML.
 *//*w  w w  .  j a  v a 2  s  . c  o m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initIncludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class includeAnnotation : includeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(includeAnnotation) != null) {
                        entity.getIncludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for included properties",
                            se);
                }
            }
        }
    }
}