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:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectLayersPanel.java

private HelpDataModel getHelpContent() {
    HelpDataModel helpContent = new HelpDataModel();
    BeanWrapper wrapper = new BeanWrapperImpl(helpContent);
    // get annotation preference from file system
    try {/*from   w w  w . j  a  v  a2  s  .  com*/
        for (Entry<Object, Object> entry : repository.loadHelpContents().entrySet()) {
            String property = entry.getKey().toString();
            if (wrapper.isWritableProperty(property)) {

                if (HelpDataModel.class.getDeclaredField(property)
                        .getGenericType() instanceof ParameterizedType) {
                    List<String> value = Arrays
                            .asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                    if (!value.get(0).equals("")) {
                        wrapper.setPropertyValue(property, value);
                    }
                } else {
                    wrapper.setPropertyValue(property, entry.getValue());
                }
            }
        }
    }
    // no preference found
    catch (Exception e) {
    }
    return helpContent;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectLayersPanel.java

private String getHelpContent(String aField) {
    String helpFieldContent = "";
    HelpDataModel helpContent = new HelpDataModel();
    BeanWrapper wrapper = new BeanWrapperImpl(helpContent);
    // get annotation preference from file system
    try {//w  w w .  ja va 2  s.  co  m
        for (Entry<Object, Object> entry : repository.loadHelpContents().entrySet()) {
            String property = entry.getKey().toString();
            if (wrapper.isWritableProperty(property)) {
                if (HelpDataModel.class.getDeclaredField(property)
                        .getGenericType() instanceof ParameterizedType) {
                    List<String> value = Arrays
                            .asList(StringUtils.replaceChars(entry.getValue().toString(), "[]", "").split(","));
                    if (!value.get(0).equals("")) {
                        wrapper.setPropertyValue(property, value);
                    }
                } else {
                    if (property.equals(aField)) {
                        helpFieldContent = entry.getValue().toString();
                    }
                    wrapper.setPropertyValue(property, entry.getValue());
                }
            }
        }
    }
    // no preference found
    catch (Exception e) {
    }
    return helpFieldContent;
}

From source file:org.codehaus.groovy.grails.cli.jndi.JndiBindingSupport.java

@SuppressWarnings("rawtypes")
private static void bindProperties(Object obj, Map entryProperties) {
    BeanWrapper dsBean = new BeanWrapperImpl(obj);
    for (Object o : entryProperties.entrySet()) {
        Map.Entry entry2 = (Map.Entry) o;
        final String propertyName = entry2.getKey().toString();
        if (dsBean.isWritableProperty(propertyName)) {
            dsBean.setPropertyValue(propertyName, entry2.getValue());
        }/*from   w ww  . ja  v  a2  s .  c om*/
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

@SuppressWarnings("unchecked")
private Object autoCreatePropertyIfPossible(BeanWrapper wrapper, String propertyName, Object propertyValue) {

    propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
    int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
    int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
    String propertyNameWithIndex = propertyName;
    if (currentKeyStart > -1) {
        propertyName = propertyName.substring(0, currentKeyStart);
    }//from w  w  w . j  a  v a  2  s  . c  o  m

    Class<?> type = wrapper.getPropertyType(propertyName);
    Object val = wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null;

    LOG.debug(
            "Checking if auto-create is possible for property [" + propertyName + "] and type [" + type + "]");
    if (type != null && val == null && (isDomainClass(type) || isEmbedded(wrapper, propertyName))) {
        if (!shouldPropertyValueSkipAutoCreate(propertyValue)
                && isNullAndWritableProperty(wrapper, propertyName)) {
            if (isDomainClass(type)) {
                Object created = autoInstantiateDomainInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            } else if (isEmbedded(wrapper, propertyName)) {
                Object created = autoInstantiateEmbeddedInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            }
        }
    } else {
        final Object beanInstance = wrapper.getWrappedInstance();
        if (type != null && Collection.class.isAssignableFrom(type)) {
            Collection<?> c = null;
            final Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);

            if (isNullAndWritableProperty(wrapper, propertyName)) {
                c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type),
                        referencedType);
            } else {
                if (wrapper.isReadableProperty(propertyName)) {
                    c = decorateCollectionForDomainAssociation(
                            (Collection<?>) wrapper.getPropertyValue(propertyName), referencedType);
                }
            }

            if (wrapper.isWritableProperty(propertyName) && c != null) {
                wrapper.setPropertyValue(propertyName, c);
            }

            val = c;

            if (c != null && currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                int index = Integer.parseInt(indexString);

                // See if we have an instance in the collection. If so, that specific instance
                // is the value to return for this indexed property.
                Object instance = findIndexedValue(c, index);
                if (instance != null) {
                    val = instance;
                }
                // If no value in the collection, this might be a domain class
                else if (isDomainClass(referencedType)) {
                    instance = autoInstantiateDomainInstance(referencedType);
                    if (instance != null) {
                        val = instance;
                        if (index == c.size()) {
                            addAssociationToTarget(propertyName, beanInstance, instance);
                        } else if (index > c.size()) {
                            while (index > c.size()) {
                                addAssociationToTarget(propertyName, beanInstance,
                                        autoInstantiateDomainInstance(referencedType));
                            }

                            addAssociationToTarget(propertyName, beanInstance, instance);
                        }
                    }
                }
            }
        } else if (type != null && Map.class.isAssignableFrom(type)) {
            Map<String, Object> map;
            if (isNullAndWritableProperty(wrapper, propertyName)) {
                map = new HashMap<String, Object>();
                wrapper.setPropertyValue(propertyName, map);
            } else {
                map = (Map) wrapper.getPropertyValue(propertyName);
            }
            val = map;
            wrapper.setPropertyValue(propertyName, val);

            if (currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
                if (isDomainClass(referencedType)) {
                    final Object domainInstance = autoInstantiateDomainInstance(referencedType);
                    val = domainInstance;
                    map.put(indexString, domainInstance);
                }
            }
        }
    }

    return val;
}

From source file:org.opennms.netmgt.alarmd.northbounder.snmptrap.SnmpTrapNorthbounderConfigDaoTest.java

/**
 * Test bean wrapper./*from   ww w . j av  a 2  s  . c o m*/
 *
 * @throws Exception the exception
 */
@Test
public void testBeanWrapper() throws Exception {
    SnmpTrapSink sink = configDao.getConfig().getSnmpTrapSink("localTest2");
    final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(sink);
    Map<String, String> params = new HashMap<String, String>();
    params.put("ipAddress", "192.168.0.1");
    Assert.assertEquals("127.0.0.2", sink.getIpAddress());
    boolean modified = false;
    for (final String key : params.keySet()) {
        if (wrapper.isWritableProperty(key)) {
            final String stringValue = params.get(key);
            final Object value = wrapper.convertIfNecessary(stringValue,
                    (Class<?>) wrapper.getPropertyType(key));
            wrapper.setPropertyValue(key, value);
            modified = true;
        }
    }
    Assert.assertTrue(modified);
    Assert.assertEquals("192.168.0.1", sink.getIpAddress());
    configDao.save();
    configDao.reload();
    Assert.assertEquals("192.168.0.1", configDao.getConfig().getSnmpTrapSink("localTest2").getIpAddress());
}

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

@Test
public void testReadableAndWritableForIndexedProperties() {
    BeanWrapper bw = new BeanWrapperImpl(IndexedTestBean.class);

    assertTrue(bw.isReadableProperty("array"));
    assertTrue(bw.isReadableProperty("list"));
    assertTrue(bw.isReadableProperty("set"));
    assertTrue(bw.isReadableProperty("map"));
    assertFalse(bw.isReadableProperty("xxx"));

    assertTrue(bw.isWritableProperty("array"));
    assertTrue(bw.isWritableProperty("list"));
    assertTrue(bw.isWritableProperty("set"));
    assertTrue(bw.isWritableProperty("map"));
    assertFalse(bw.isWritableProperty("xxx"));

    assertTrue(bw.isReadableProperty("array[0]"));
    assertTrue(bw.isReadableProperty("array[0].name"));
    assertTrue(bw.isReadableProperty("list[0]"));
    assertTrue(bw.isReadableProperty("list[0].name"));
    assertTrue(bw.isReadableProperty("set[0]"));
    assertTrue(bw.isReadableProperty("set[0].name"));
    assertTrue(bw.isReadableProperty("map[key1]"));
    assertTrue(bw.isReadableProperty("map[key1].name"));
    assertTrue(bw.isReadableProperty("map[key4][0]"));
    assertTrue(bw.isReadableProperty("map[key4][0].name"));
    assertTrue(bw.isReadableProperty("map[key4][1]"));
    assertTrue(bw.isReadableProperty("map[key4][1].name"));
    assertFalse(bw.isReadableProperty("array[key1]"));

    assertTrue(bw.isWritableProperty("array[0]"));
    assertTrue(bw.isWritableProperty("array[0].name"));
    assertTrue(bw.isWritableProperty("list[0]"));
    assertTrue(bw.isWritableProperty("list[0].name"));
    assertTrue(bw.isWritableProperty("set[0]"));
    assertTrue(bw.isWritableProperty("set[0].name"));
    assertTrue(bw.isWritableProperty("map[key1]"));
    assertTrue(bw.isWritableProperty("map[key1].name"));
    assertTrue(bw.isWritableProperty("map[key4][0]"));
    assertTrue(bw.isWritableProperty("map[key4][0].name"));
    assertTrue(bw.isWritableProperty("map[key4][1]"));
    assertTrue(bw.isWritableProperty("map[key4][1].name"));
    assertFalse(bw.isWritableProperty("array[key1]"));
}

From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java

/**
 * Apply the given property values, resolving any runtime references
 * to other beans in this bean factory. Must use deep copy, so we
 * don't permanently modify this property.
 * @param beanName the bean name passed for better exception information
 * @param mbd the merged bean definition
 * @param bw the BeanWrapper wrapping the target object
 * @param pvs the new property values/*from   www. j  a  v  a2s . c  om*/
 */
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs.isEmpty()) {
        return;
    }

    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }

    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;

    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            } catch (BeansException ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    } else {
        original = Arrays.asList(pvs.getPropertyValues());
    }

    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName)
                    && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            } else if (convertible && originalValue instanceof TypedStringValue
                    && !((TypedStringValue) originalValue).isDynamic()
                    && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            } else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }

    // Set our (possibly massaged) deep copy.
    try {
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values",
                ex);
    }
}

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;//from w  w w . java  2s .  c  om
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.springframework.jms.listener.endpoint.DefaultJmsActivationSpecFactory.java

/**
 * This implementation supports Spring's extended "maxConcurrency"
 * and "prefetchSize" settings through detecting corresponding
 * ActivationSpec properties: "maxSessions"/"maxNumberOfWorks" and
 * "maxMessagesPerSessions"/"maxMessages", respectively
 * (following ActiveMQ's and JORAM's naming conventions).
 *//*  ww w  .ja v  a 2  s .com*/
@Override
protected void populateActivationSpecProperties(BeanWrapper bw, JmsActivationSpecConfig config) {
    super.populateActivationSpecProperties(bw, config);
    if (config.getMaxConcurrency() > 0) {
        if (bw.isWritableProperty("maxSessions")) {
            // ActiveMQ
            bw.setPropertyValue("maxSessions", Integer.toString(config.getMaxConcurrency()));
        } else if (bw.isWritableProperty("maxNumberOfWorks")) {
            // JORAM
            bw.setPropertyValue("maxNumberOfWorks", Integer.toString(config.getMaxConcurrency()));
        } else if (bw.isWritableProperty("maxConcurrency")) {
            // WebSphere
            bw.setPropertyValue("maxConcurrency", Integer.toString(config.getMaxConcurrency()));
        }
    }
    if (config.getPrefetchSize() > 0) {
        if (bw.isWritableProperty("maxMessagesPerSessions")) {
            // ActiveMQ
            bw.setPropertyValue("maxMessagesPerSessions", Integer.toString(config.getPrefetchSize()));
        } else if (bw.isWritableProperty("maxMessages")) {
            // JORAM
            bw.setPropertyValue("maxMessages", Integer.toString(config.getPrefetchSize()));
        } else if (bw.isWritableProperty("maxBatchSize")) {
            // WebSphere
            bw.setPropertyValue("maxBatchSize", Integer.toString(config.getPrefetchSize()));
        }
    }
}

From source file:org.springframework.jms.listener.endpoint.DefaultJmsActivationSpecFactory.java

/**
 * This implementation maps {@code SESSION_TRANSACTED} onto an
 * ActivationSpec property named "useRAManagedTransaction", if available
 * (following ActiveMQ's naming conventions).
 *//*w  w  w  . jav a  2s. c o  m*/
@Override
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
    if (ackMode == Session.SESSION_TRANSACTED && bw.isWritableProperty("useRAManagedTransaction")) {
        // ActiveMQ
        bw.setPropertyValue("useRAManagedTransaction", "true");
    } else {
        super.applyAcknowledgeMode(bw, ackMode);
    }
}