Example usage for org.springframework.beans BeanWrapper getPropertyValue

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

Introduction

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

Prototype

@Nullable
Object getPropertyValue(String propertyName) throws BeansException;

Source Link

Document

Get the current value of the specified property.

Usage

From source file:org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.BooleanPropertyColumn.java

@Override
public void populateItem(final Item<ICellPopulator<T>> item, final String componentId,
        final IModel<T> rowModel) {
    BeanWrapper bwi = new BeanWrapperImpl(rowModel.getObject());
    Object obj = bwi.getPropertyValue(getPropertyExpression());

    item.add(new Label(componentId, StringUtils.EMPTY));
    if (Boolean.valueOf(obj.toString())) {
        item.add(new AttributeModifier("class", "glyphicon glyphicon-ok"));
        item.add(new AttributeModifier("style", "display: table-cell; text-align: center;"));
    }//w  w w  . j  a v  a  2  s.  c  o m
}

From source file:org.apache.syncope.client.console.wicket.extensions.markup.html.repeater.data.table.KeyPropertyColumn.java

@Override
public void populateItem(final Item<ICellPopulator<T>> item, final String componentId,
        final IModel<T> rowModel) {
    BeanWrapper bwi = new BeanWrapperImpl(rowModel.getObject());
    Object obj = bwi.getPropertyValue(getPropertyExpression());

    item.add(new Label(componentId, StringUtils.EMPTY));
    item.add(new AttributeModifier("title", obj.toString()));
    item.add(new AttributeModifier("class", "fa fa-key"));
    item.add(new AttributeModifier("style", "display: table-cell; text-align: center;"));
}

From source file:org.apache.syncope.console.pages.ReportletConfModalPage.java

private ListView<String> buildPropView() {
    LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override//w  w w  .  java2s . com
        protected List<String> load() {
            List<String> result = new ArrayList<String>();
            if (ReportletConfModalPage.this.reportletConf != null) {
                for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) {
                    if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) {
                        result.add(field.getName());
                    }
                }
            }

            return result;
        }
    };

    propView = new ListView<String>("propView", propViewModel) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            Label label = new Label("key", fieldName);
            item.add(label);

            Field field = null;
            try {
                field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName);
            } catch (Exception e) {
                LOG.error("Could not find field {} in class {}", fieldName,
                        ReportletConfModalPage.this.reportletConf.getClass(), e);
            }
            if (field == null) {
                return;
            }

            FormAttributeField annotation = field.getAnnotation(FormAttributeField.class);

            BeanWrapper wrapper = PropertyAccessorFactory
                    .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf);

            Panel panel;

            if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) {
                panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (String.class.equals(field.getType()) && annotation != null && annotation.roleSearch()) {
                panel = new RoleSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && annotation != null) {
                    List<String> choices;
                    switch (annotation.schema()) {
                    case UserSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.USER);
                        break;

                    case UserDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.USER);
                        break;

                    case UserVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.USER);
                        break;

                    case RoleSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.ROLE);
                        break;

                    case MembershipSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    default:
                        choices = Collections.emptyList();
                    }

                    panel = new AjaxPalettePanel("value",
                            new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf,
                                    fieldName),
                            new ListModel<String>(choices), true);
                } else if (listItemType.isEnum()) {
                    panel = new CheckBoxMultipleChoiceFieldPanel("value",
                            new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName),
                            new ListModel(Arrays.asList(listItemType.getEnumConstants())));
                } else {
                    if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) {
                        ((List) wrapper.getPropertyValue(fieldName)).add(null);
                    }

                    panel = new MultiFieldPanel("value",
                            new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName),
                            buildSinglePanel(field.getType(), fieldName, "panel"));
                }
            } else {
                panel = buildSinglePanel(field.getType(), fieldName, "value");
            }

            item.add(panel);
        }
    };

    return propView;
}

From source file:org.apache.syncope.console.pages.Schema.java

private <T extends AbstractSchemaModalPage> List<IColumn> getColumns(final WebMarkupContainer webContainer,
        final ModalWindow modalWindow, final AttributableType attributableType, final SchemaType schemaType,
        final Collection<String> fields) {

    List<IColumn> columns = new ArrayList<IColumn>();

    for (final String field : fields) {
        final Field clazzField = ReflectionUtils.findField(schemaType.getToClass(), field);

        if (clazzField != null) {
            if (clazzField.getType().equals(Boolean.class) || clazzField.getType().equals(boolean.class)) {
                columns.add(new AbstractColumn<AbstractSchemaTO, String>(new ResourceModel(field)) {

                    private static final long serialVersionUID = 8263694778917279290L;

                    @Override/*from  ww w. j a  va  2s.  co  m*/
                    public void populateItem(final Item<ICellPopulator<AbstractSchemaTO>> item,
                            final String componentId, final IModel<AbstractSchemaTO> model) {

                        BeanWrapper bwi = new BeanWrapperImpl(model.getObject());
                        Object obj = bwi.getPropertyValue(field);

                        item.add(new Label(componentId, ""));
                        item.add(new AttributeModifier("class", new Model<String>(obj.toString())));
                    }

                    @Override
                    public String getCssClass() {
                        return "small_fixedsize";
                    }
                });
            } else {
                IColumn column = new PropertyColumn(new ResourceModel(field), field, field) {

                    private static final long serialVersionUID = 3282547854226892169L;

                    @Override
                    public String getCssClass() {
                        String css = super.getCssClass();
                        if ("name".equals(field)) {
                            css = StringUtils.isBlank(css) ? "medium_fixedsize" : css + " medium_fixedsize";
                        }
                        return css;
                    }
                };
                columns.add(column);
            }
        }
    }

    columns.add(new AbstractColumn<AbstractSchemaTO, String>(new ResourceModel("actions", "")) {

        private static final long serialVersionUID = 2054811145491901166L;

        @Override
        public String getCssClass() {
            return "action";
        }

        @Override
        public void populateItem(final Item<ICellPopulator<AbstractSchemaTO>> item, final String componentId,
                final IModel<AbstractSchemaTO> model) {

            final AbstractSchemaTO schemaTO = model.getObject();

            final ActionLinksPanel panel = new ActionLinksPanel(componentId, model, getPageReference());

            panel.addWithRoles(new ActionLink() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target) {
                    modalWindow.setPageCreator(new ModalWindow.PageCreator() {

                        private static final long serialVersionUID = -7834632442532690940L;

                        @Override
                        public Page createPage() {
                            AbstractSchemaModalPage page = SchemaModalPageFactory
                                    .getSchemaModalPage(attributableType, schemaType);

                            page.setSchemaModalPage(Schema.this.getPageReference(), modalWindow, schemaTO,
                                    false);

                            return page;
                        }
                    });

                    modalWindow.show(target);
                }
            }, ActionType.EDIT, allowedReadRoles);

            panel.addWithRoles(new ActionLink() {

                private static final long serialVersionUID = -3722207913631435501L;

                @Override
                public void onClick(final AjaxRequestTarget target) {

                    switch (schemaType) {
                    case DERIVED:
                        restClient.deleteDerSchema(attributableType, schemaTO.getName());
                        break;

                    case VIRTUAL:
                        restClient.deleteVirSchema(attributableType, schemaTO.getName());
                        break;

                    default:
                        restClient.deleteSchema(attributableType, schemaTO.getName());
                        break;
                    }

                    info(getString(Constants.OPERATION_SUCCEEDED));
                    feedbackPanel.refresh(target);

                    target.add(webContainer);
                }
            }, ActionType.DELETE, allowedDeleteRoles);

            item.add(panel);
        }
    });

    return columns;
}

From source file:org.codehaus.groovy.grails.commons.GrailsClassUtils.java

/**
 * <p>Looks for a property of the reference instance with a given name.</p>
 * <p>If found its value is returned. We follow the Java bean conventions with augmentation for groovy support
 * and static fields/properties. We will therefore match, in this order:
 * </p>//w w  w. jav a2  s  .c  o m
 * <ol>
 * <li>Standard public bean property (with getter or just public field, using normal introspection)
 * <li>Public static property with getter method
 * <li>Public static field
 * </ol>
 *
 * @return property value or null if no property found
 */
public static Object getPropertyOrStaticPropertyOrFieldValue(Object obj, String name) throws BeansException {
    BeanWrapper ref = new BeanWrapperImpl(obj);
    if (ref.isReadableProperty(name)) {
        return ref.getPropertyValue(name);
    }
    // Look for public fields
    if (isPublicField(obj, name)) {
        return getFieldValue(obj, name);
    }

    // Look for statics
    Class<?> clazz = obj.getClass();
    if (isStaticProperty(clazz, name)) {
        return getStaticPropertyValue(clazz, name);
    }
    return null;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

public static void autoAssociateBidirectionalOneToOnes(DefaultGrailsDomainClass domainClass, Object target) {
    List<GrailsDomainClassProperty> associations = domainClass.getAssociations();
    for (GrailsDomainClassProperty association : associations) {
        if (association.isOneToOne() && association.isBidirectional() && association.isOwningSide()) {
            if (isInitialized(target, association.getName())) {
                GrailsDomainClassProperty otherSide = association.getOtherSide();
                if (otherSide != null) {
                    BeanWrapper bean = new BeanWrapperImpl(target);
                    Object inverseObject = bean.getPropertyValue(association.getName());
                    if (inverseObject != null) {
                        if (isInitialized(inverseObject, otherSide.getName())) {
                            BeanWrapper inverseBean = new BeanWrapperImpl(inverseObject);
                            Object propertyValue = inverseBean.getPropertyValue(otherSide.getName());
                            if (propertyValue == null) {
                                inverseBean.setPropertyValue(otherSide.getName(), target);
                            }/*from w  w w  . j  a  v a2s  .  c  om*/
                        }
                    }
                }
            }
        }
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod.java

/**
 * Performs automatic association retrieval
 * @param domainClass The domain class to retrieve associations for
 * @param target The target object//  w ww .  j av a 2 s  .  co m
 */
@SuppressWarnings("unchecked")
private void autoRetrieveAssocations(GrailsDomainClass domainClass, Object target) {
    BeanWrapper bean = new BeanWrapperImpl(target);
    HibernateTemplate t = getHibernateTemplate();
    GrailsDomainClassProperty[] props = domainClass.getPersistentProperties();
    for (int i = 0; i < props.length; i++) {
        GrailsDomainClassProperty prop = props[i];
        if (!prop.isManyToOne() && !prop.isOneToOne()) {
            continue;
        }

        Object propValue = bean.getPropertyValue(prop.getName());
        if (propValue == null || t.contains(propValue)) {
            continue;
        }

        GrailsDomainClass otherSide = (GrailsDomainClass) application
                .getArtefact(DomainClassArtefactHandler.TYPE, prop.getType().getName());
        if (otherSide == null) {
            continue;
        }

        BeanWrapper propBean = new BeanWrapperImpl(propValue);
        try {
            Serializable id = (Serializable) propBean.getPropertyValue(otherSide.getIdentifier().getName());
            if (id != null) {
                final Object propVal = t.get(prop.getType(), id);
                if (propVal != null) {
                    bean.setPropertyValue(prop.getName(), propVal);
                }
            }
        } catch (InvalidPropertyException ipe) {
            // property is not accessable
        }
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod.java

/**
 * Sets the flush mode to manual. which ensures that the database changes are not persisted to the database
 * if a validation error occurs. If save() is called again and validation passes the code will check if there
 * is a manual flush mode and flush manually if necessary
 *
 * @param domainClass The domain class/*from w  w  w  . j  av  a 2s .  com*/
 * @param target The target object that failed validation
 * @param errors The Errors instance  @return This method will return null signaling a validation failure
 */
protected Object handleValidationError(GrailsDomainClass domainClass, final Object target, Errors errors) {
    // if a validation error occurs set the object to read-only to prevent a flush
    setObjectToReadOnly(target);
    if (domainClass instanceof DefaultGrailsDomainClass) {
        DefaultGrailsDomainClass dgdc = (DefaultGrailsDomainClass) domainClass;
        List<GrailsDomainClassProperty> associations = dgdc.getAssociations();
        for (GrailsDomainClassProperty association : associations) {
            if (association.isOneToOne() || association.isManyToOne()) {
                BeanWrapper bean = new BeanWrapperImpl(target);
                Object propertyValue = bean.getPropertyValue(association.getName());
                if (propertyValue != null) {
                    setObjectToReadOnly(propertyValue);
                }

            }
        }
    }
    setErrorsOnInstance(target, errors);
    return null;
}

From source file:org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler.java

public Map handleSave(HttpServletRequest request, HttpServletResponse reponse, ScaffoldCallback callback) {

    Object domainObject = domain.newInstance();
    WebRequest webRequest = (WebRequest) RequestContextHolder.currentRequestAttributes();
    InvokerHelper.setProperty(domainObject, "properties", webRequest.getParameterMap());

    Errors domainObjectErrors = (Errors) InvokerHelper.getProperty(domainObject, "errors");

    Map model = new HashMap();
    model.put(domain.getSingularName(), domainObject);

    if (!domainObjectErrors.hasErrors() && this.domain.save(domainObject, callback)) {
        BeanWrapper domainBean = new BeanWrapperImpl(domainObject);
        Object identity = domainBean.getPropertyValue(domain.getIdentityPropertyName());
        model.put(PARAM_ID, identity);/*from  ww  w .  j a v  a  2 s  .  co  m*/
        callback.setInvoked(true);
    }
    return model;
}

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 ww  w.j a  v  a 2  s  .  co  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;
}